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" ())
166 (declare-function orgtbl-ascii-plot
"org-table" (&optional ask
))
167 (declare-function org-plot
/gnuplot
"org-plot" (&optional params
))
169 (declare-function org-element-at-point
"org-element" ())
170 (declare-function org-element-cache-reset
"org-element" (&optional all
))
171 (declare-function org-element-cache-refresh
"org-element" (pos))
172 (declare-function org-element-contents
"org-element" (element))
173 (declare-function org-element-context
"org-element" (&optional element
))
174 (declare-function org-element-interpret-data
"org-element"
175 (data &optional parent
))
176 (declare-function org-element-nested-p
"org-element" (elem-a elem-b
))
177 (declare-function org-element-parse-buffer
"org-element"
178 (&optional granularity visible-only
))
179 (declare-function org-element-property
"org-element" (property element
))
180 (declare-function org-element-put-property
"org-element"
181 (element property value
))
182 (declare-function org-element-swap-A-B
"org-element" (elem-a elem-b
))
183 (declare-function org-element-parse-buffer
"org-element"
184 (&optional granularity visible-only
))
185 (declare-function org-element-type
"org-element" (element))
187 (defsubst org-uniquify
(list)
188 "Non-destructively remove duplicate elements from LIST."
189 (let ((res (copy-sequence list
))) (delete-dups res
)))
191 (defsubst org-get-at-bol
(property)
192 "Get text property PROPERTY at the beginning of line."
193 (get-text-property (point-at-bol) property
))
195 (defsubst org-trim
(s)
196 "Remove whitespace at the beginning and the end of string S."
197 (replace-regexp-in-string
199 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s
)))
201 ;; load languages based on value of `org-babel-load-languages'
202 (defvar org-babel-load-languages
)
205 (defun org-babel-do-load-languages (sym value
)
206 "Load the languages defined in `org-babel-load-languages'."
207 (set-default sym value
)
209 (let ((active (cdr pair
)) (lang (symbol-name (car pair
))))
212 (require (intern (concat "ob-" lang
))))
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-execute:" lang
)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-expand-body:" lang
)))))))
218 org-babel-load-languages
))
220 (declare-function org-babel-tangle-file
"ob-tangle" (file &optional target-file lang
))
222 (defun org-babel-load-file (file &optional compile
)
223 "Load Emacs Lisp source code blocks in the Org-mode FILE.
224 This function exports the source code using `org-babel-tangle'
225 and then loads the resulting file using `load-file'. With prefix
226 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
227 file to byte-code before it is loaded."
228 (interactive "fFile to load: \nP")
229 (let* ((age (lambda (file)
231 (time-subtract (current-time)
232 (nth 5 (or (file-attributes (file-truename file
))
233 (file-attributes file
)))))))
234 (base-name (file-name-sans-extension file
))
235 (exported-file (concat base-name
".el")))
236 ;; tangle if the org-mode file is newer than the elisp file
237 (unless (and (file-exists-p exported-file
)
238 (> (funcall age file
) (funcall age exported-file
)))
240 (car (org-babel-tangle-file file exported-file
"emacs-lisp"))))
243 (progn (byte-compile-file exported-file
'load
)
244 "Compiled and loaded")
245 (progn (load-file exported-file
) "Loaded"))
248 (defcustom org-babel-load-languages
'((emacs-lisp . t
))
249 "Languages which can be evaluated in Org-mode buffers.
250 This list can be used to load support for any of the languages
251 below, note that each language will depend on a different set of
252 system executables and/or Emacs modes. When a language is
253 \"loaded\", then code blocks in that language can be evaluated
254 with `org-babel-execute-src-block' bound by default to C-c
255 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
256 be set to remove code block evaluation from the C-c C-c
257 keybinding. By default only Emacs Lisp (which has no
258 requirements) is loaded."
260 :set
'org-babel-do-load-languages
262 :type
'(alist :tag
"Babel Languages"
265 (const :tag
"Awk" awk
)
268 (const :tag
"Asymptote" asymptote
)
269 (const :tag
"Calc" calc
)
270 (const :tag
"Clojure" clojure
)
271 (const :tag
"CSS" css
)
272 (const :tag
"Ditaa" ditaa
)
273 (const :tag
"Dot" dot
)
274 (const :tag
"Emacs Lisp" emacs-lisp
)
275 (const :tag
"Forth" forth
)
276 (const :tag
"Fortran" fortran
)
277 (const :tag
"Gnuplot" gnuplot
)
278 (const :tag
"Haskell" haskell
)
281 (const :tag
"Java" java
)
282 (const :tag
"Javascript" js
)
283 (const :tag
"LaTeX" latex
)
284 (const :tag
"Ledger" ledger
)
285 (const :tag
"Lilypond" lilypond
)
286 (const :tag
"Lisp" lisp
)
287 (const :tag
"Makefile" makefile
)
288 (const :tag
"Maxima" maxima
)
289 (const :tag
"Matlab" matlab
)
290 (const :tag
"Mscgen" mscgen
)
291 (const :tag
"Ocaml" ocaml
)
292 (const :tag
"Octave" octave
)
293 (const :tag
"Org" org
)
294 (const :tag
"Perl" perl
)
295 (const :tag
"Pico Lisp" picolisp
)
296 (const :tag
"PlantUML" plantuml
)
297 (const :tag
"Python" python
)
298 (const :tag
"Ruby" ruby
)
299 (const :tag
"Sass" sass
)
300 (const :tag
"Scala" scala
)
301 (const :tag
"Scheme" scheme
)
302 (const :tag
"Screen" screen
)
303 (const :tag
"Shell Script" shell
)
304 (const :tag
"Shen" shen
)
305 (const :tag
"Sql" sql
)
306 (const :tag
"Sqlite" sqlite
)
307 (const :tag
"ebnf2ps" ebnf2ps
))
308 :value-type
(boolean :tag
"Activate" :value t
)))
310 ;;;; Customization variables
311 (defcustom org-clone-delete-id nil
312 "Remove ID property of clones of a subtree.
313 When non-nil, clones of a subtree don't inherit the ID property.
314 Otherwise they inherit the ID property with a new unique
324 (defun org-version (&optional here full message
)
325 "Show the org-mode version.
326 Interactively, or when MESSAGE is non-nil, show it in echo area.
327 With prefix argument, or when HERE is non-nil, insert it at point.
328 In non-interactive uses, a reduced version string is output unless
330 (interactive (list current-prefix-arg t
(not current-prefix-arg
)))
331 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
332 (save-load-suffixes (when (boundp 'load-suffixes
) load-suffixes
))
333 (load-suffixes (list ".el"))
334 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
336 (and (fboundp 'org-release
) (fboundp 'org-git-version
))
337 (org-load-noerror-mustsuffix (concat org-dir
"org-version"))))
338 (load-suffixes save-load-suffixes
)
339 (org-version (org-release))
340 (git-version (org-git-version))
341 (version (format "Org-mode version %s (%s @ %s)"
345 (if (string= org-dir org-install-dir
)
347 (concat "mixed installation! " org-install-dir
" and " org-dir
))
348 "org-loaddefs.el can not be found!")))
349 (version1 (if full version org-version
)))
350 (when here
(insert version1
))
351 (when message
(message "%s" version1
))
354 (defconst org-version
(org-version))
361 (defconst org-block-regexp
362 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
363 "Regular expression for hiding blocks.")
365 (defconst org-dblock-start-re
366 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
367 "Matches the start line of a dynamic block, with parameters.")
369 (defconst org-dblock-end-re
"^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
370 "Matches the end of a dynamic block.")
372 ;;;; Clock and Planning
374 (defconst org-clock-string
"CLOCK:"
375 "String used as prefix for timestamps clocking work hours on an item.")
377 (defconst org-closed-string
"CLOSED:"
378 "String used as the prefix for timestamps logging closing a TODO entry.")
380 (defconst org-deadline-string
"DEADLINE:"
381 "String to mark deadline entries.
382 A deadline is this string, followed by a time stamp. Should be a word,
383 terminated by a colon. You can insert a schedule keyword and
384 a timestamp with \\[org-deadline].")
386 (defconst org-scheduled-string
"SCHEDULED:"
387 "String to mark scheduled TODO entries.
388 A schedule is this string, followed by a time stamp. Should be a word,
389 terminated by a colon. You can insert a schedule keyword and
390 a timestamp with \\[org-schedule].")
392 (defconst org-ds-keyword-length
396 (list org-deadline-string org-scheduled-string
397 org-clock-string org-closed-string
))))
398 "Maximum length of the DEADLINE and SCHEDULED keywords.")
400 (defconst org-planning-line-re
403 (list org-closed-string org-deadline-string org-scheduled-string
)
405 "Matches a line with planning info.
406 Matched keyword is in group 1.")
408 (defconst org-clock-line-re
409 (concat "^[ \t]*" org-clock-string
)
410 "Matches a line with clock info.")
412 (defconst org-deadline-regexp
(concat "\\<" org-deadline-string
)
413 "Matches the DEADLINE keyword.")
415 (defconst org-deadline-time-regexp
416 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
417 "Matches the DEADLINE keyword together with a time stamp.")
419 (defconst org-deadline-time-hour-regexp
420 (concat "\\<" org-deadline-string
421 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
422 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
424 (defconst org-deadline-line-regexp
425 (concat "\\<\\(" org-deadline-string
"\\).*")
426 "Matches the DEADLINE keyword and the rest of the line.")
428 (defconst org-scheduled-regexp
(concat "\\<" org-scheduled-string
)
429 "Matches the SCHEDULED keyword.")
431 (defconst org-scheduled-time-regexp
432 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>")
433 "Matches the SCHEDULED keyword together with a time stamp.")
435 (defconst org-scheduled-time-hour-regexp
436 (concat "\\<" org-scheduled-string
437 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
438 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
440 (defconst org-closed-time-regexp
441 (concat "\\<" org-closed-string
" *\\[\\([^]]+\\)\\]")
442 "Matches the CLOSED keyword together with a time stamp.")
444 (defconst org-keyword-time-regexp
447 (list org-scheduled-string org-deadline-string org-closed-string
450 " *[[<]\\([^]>]+\\)[]>]")
451 "Matches any of the 4 keywords, together with the time stamp.")
453 (defconst org-keyword-time-not-clock-regexp
457 (list org-scheduled-string org-deadline-string org-closed-string
) t
)
458 " *[[<]\\([^]>]+\\)[]>]")
459 "Matches any of the 3 keywords, together with the time stamp.")
461 (defconst org-maybe-keyword-time-regexp
464 (list org-scheduled-string org-deadline-string org-closed-string
468 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
471 "Matches a timestamp, possibly preceded by a keyword.")
473 (defconst org-all-time-keywords
474 (mapcar (lambda (w) (substring w
0 -
1))
475 (list org-scheduled-string org-deadline-string
476 org-clock-string org-closed-string
))
477 "List of time keywords.")
481 (defconst org-drawer-regexp
"^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
482 "Matches first or last line of a hidden block.
483 Group 1 contains drawer's name or \"END\".")
485 (defconst org-property-start-re
"^[ \t]*:PROPERTIES:[ \t]*$"
486 "Regular expression matching the first line of a property drawer.")
488 (defconst org-property-end-re
"^[ \t]*:END:[ \t]*$"
489 "Regular expression matching the last line of a property drawer.")
491 (defconst org-clock-drawer-start-re
"^[ \t]*:CLOCK:[ \t]*$"
492 "Regular expression matching the first line of a clock drawer.")
494 (defconst org-clock-drawer-end-re
"^[ \t]*:END:[ \t]*$"
495 "Regular expression matching the last line of a clock drawer.")
497 (defconst org-property-drawer-re
498 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
499 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*"
500 "[ \t]*:END:[ \t]*$")
501 "Matches an entire property drawer.")
503 (defconst org-clock-drawer-re
504 (concat "\\(" org-clock-drawer-start-re
"\\)[^\000]*?\\("
505 org-clock-drawer-end-re
"\\)\n?")
506 "Matches an entire clock drawer.")
510 (defconst org-heading-keyword-regexp-format
511 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
512 "Printf format for a regexp matching a headline with some keyword.
513 This regexp will match the headline of any node which has the
514 exact keyword that is put into the format. The keyword isn't in
515 any group by default, but the stars and the body are.")
517 (defconst org-heading-keyword-maybe-regexp-format
518 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
519 "Printf format for a regexp matching a headline, possibly with some keyword.
520 This regexp can match any headline with the specified keyword, or
521 without a keyword. The keyword isn't in any group by default,
522 but the stars and the body are.")
524 (defconst org-archive-tag
"ARCHIVE"
525 "The tag that marks a subtree as archived.
526 An archived subtree does not open during visibility cycling, and does
527 not contribute to the agenda listings.")
529 (defconst org-comment-string
"COMMENT"
530 "Entries starting with this keyword will never be exported.
531 An entry can be toggled between COMMENT and normal with
532 \\[org-toggle-comment].")
535 ;;;; LaTeX Environments and Fragments
537 (defconst org-latex-regexps
538 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t
)
539 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
540 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
541 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil
)
542 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil
)
543 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil
)
544 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil
)
545 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil
))
546 "Regular expressions for matching embedded LaTeX.")
550 (defconst org-effort-property
"Effort"
551 "The property that is being used to keep track of effort estimates.
552 Effort estimates given in this property need to have the format H:MM.")
556 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
557 "Detect an org-type or table-type table.")
559 (defconst org-table-line-regexp
"^[ \t]*|"
560 "Detect an org-type table line.")
562 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
563 "Detect an org-type table line.")
565 (defconst org-table-hline-regexp
"^[ \t]*|-"
566 "Detect an org-type table hline.")
568 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
569 "Detect a table-type table hline.")
571 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
572 "Detect the first line outside a table when searching from within it.
573 This works for both table types.")
575 (defconst org-TBLFM-regexp
"^[ \t]*#\\+TBLFM: "
576 "Detect a #+TBLFM line.")
580 (defconst org-ts-regexp
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp-both
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
584 "Regular expression for fast time stamp matching.")
586 (defconst org-ts-regexp0
587 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
588 "Regular expression matching time strings for analysis.
589 This one does not require the space after the date, so it can be used
590 on a string that terminates immediately after the date.")
592 (defconst org-ts-regexp1
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
593 "Regular expression matching time strings for analysis.")
595 (defconst org-ts-regexp2
(concat "<" org-ts-regexp1
"[^>\n]\\{0,16\\}>")
596 "Regular expression matching time stamps, with groups.")
598 (defconst org-ts-regexp3
(concat "[[<]" org-ts-regexp1
"[^]>\n]\\{0,16\\}[]>]")
599 "Regular expression matching time stamps (also [..]), with groups.")
601 (defconst org-tr-regexp
(concat org-ts-regexp
"--?-?" org-ts-regexp
)
602 "Regular expression matching a time stamp range.")
604 (defconst org-tr-regexp-both
605 (concat org-ts-regexp-both
"--?-?" org-ts-regexp-both
)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tsr-regexp
(concat org-ts-regexp
"\\(--?-?"
609 org-ts-regexp
"\\)?")
610 "Regular expression matching a time stamp or time stamp range.")
612 (defconst org-tsr-regexp-both
613 (concat org-ts-regexp-both
"\\(--?-?"
614 org-ts-regexp-both
"\\)?")
615 "Regular expression matching a time stamp or time stamp range.
616 The time stamps may be either active or inactive.")
618 (defconst org-repeat-re
619 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
620 "Regular expression for specifying repeated events.
621 After a match, group 1 contains the repeat expression.")
623 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
624 "Formats for `format-time-string' which are used for time stamps.")
627 ;;; The custom variables
630 "Outline-based notes management and organizer."
635 (defcustom org-mode-hook nil
636 "Mode hook for Org-mode, run after the mode was turned on."
640 (defcustom org-load-hook nil
641 "Hook that is run after org.el has been loaded."
645 (defcustom org-log-buffer-setup-hook nil
646 "Hook that is run after an Org log buffer is created."
651 (defvar org-modules
) ; defined below
652 (defvar org-modules-loaded nil
653 "Have the modules been loaded already?")
655 (defun org-load-modules-maybe (&optional force
)
656 "Load all extensions listed in `org-modules'."
657 (when (or force
(not org-modules-loaded
))
659 (condition-case nil
(require ext
)
660 (error (message "Problems while trying to load feature `%s'" ext
))))
662 (setq org-modules-loaded t
)))
664 (defun org-set-modules (var value
)
665 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
667 (when (featurep 'org
)
668 (org-load-modules-maybe 'force
)
669 (org-element-cache-reset 'all
)))
671 (defcustom org-modules
'(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail
)
672 "Modules that should always be loaded together with org.el.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 You can also use this system to load external packages (i.e. neither Org
679 core modules, nor modules from the CONTRIB directory). Just add symbols
680 to the end of the list. If the package is called org-xyz.el, then you need
681 to add the symbol `xyz', and the package must have a call to:
685 For export specific modules, see also `org-export-backends'."
687 :set
'org-set-modules
689 :package-version
'(Org .
"8.0")
692 (const :tag
" bbdb: Links to BBDB entries" org-bbdb
)
693 (const :tag
" bibtex: Links to BibTeX entries" org-bibtex
)
694 (const :tag
" crypt: Encryption of subtrees" org-crypt
)
695 (const :tag
" ctags: Access to Emacs tags with links" org-ctags
)
696 (const :tag
" docview: Links to doc-view buffers" org-docview
)
697 (const :tag
" gnus: Links to GNUS folders/messages" org-gnus
)
698 (const :tag
" habit: Track your consistency with habits" org-habit
)
699 (const :tag
" id: Global IDs for identifying entries" org-id
)
700 (const :tag
" info: Links to Info nodes" org-info
)
701 (const :tag
" inlinetask: Tasks independent of outline hierarchy" org-inlinetask
)
702 (const :tag
" irc: Links to IRC/ERC chat sessions" org-irc
)
703 (const :tag
" mhe: Links to MHE folders/messages" org-mhe
)
704 (const :tag
" mouse: Additional mouse support" org-mouse
)
705 (const :tag
" protocol: Intercept calls from emacsclient" org-protocol
)
706 (const :tag
" rmail: Links to RMAIL folders/messages" org-rmail
)
707 (const :tag
" w3m: Special cut/paste from w3m to Org-mode." org-w3m
)
709 (const :tag
"C annotate-file: Annotate a file with org syntax" org-annotate-file
)
710 (const :tag
"C bookmark: Org-mode links to bookmarks" org-bookmark
)
711 (const :tag
"C bullets: Add overlays to headlines stars" org-bullets
)
712 (const :tag
"C checklist: Extra functions for checklists in repeated tasks" org-checklist
)
713 (const :tag
"C choose: Use TODO keywords to mark decisions states" org-choose
)
714 (const :tag
"C collector: Collect properties into tables" org-collector
)
715 (const :tag
"C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend
)
716 (const :tag
"C drill: Flashcards and spaced repetition for Org-mode" org-drill
)
717 (const :tag
"C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol
)
718 (const :tag
"C eshell Support for links to working directories in eshell" org-eshell
)
719 (const :tag
"C eval-light: Evaluate inbuffer-code on demand" org-eval-light
)
720 (const :tag
"C eval: Include command output as text" org-eval
)
721 (const :tag
"C eww: Store link to url of eww" org-eww
)
722 (const :tag
"C expiry: Expiry mechanism for Org-mode entries" org-expiry
)
723 (const :tag
"C favtable: Lookup table of favorite references and links" org-favtable
)
724 (const :tag
"C git-link: Provide org links to specific file version" org-git-link
)
725 (const :tag
"C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query
)
726 (const :tag
"C invoice: Help manage client invoices in Org-mode" org-invoice
)
727 (const :tag
"C jira: Add a jira:ticket protocol to Org-mode" org-jira
)
728 (const :tag
"C learn: SuperMemo's incremental learning algorithm" org-learn
)
729 (const :tag
"C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal
)
730 (const :tag
"C mac-link: Grab links and url from various mac Applications" org-mac-link
)
731 (const :tag
"C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix
)
732 (const :tag
"C man: Support for links to manpages in Org-mode" org-man
)
733 (const :tag
"C mew: Links to Mew folders/messages" org-mew
)
734 (const :tag
"C mtags: Support for muse-like tags" org-mtags
)
735 (const :tag
"C notmuch: Provide org links to notmuch searches or messages" org-notmuch
)
736 (const :tag
"C panel: Simple routines for us with bad memory" org-panel
)
737 (const :tag
"C registry: A registry for Org-mode links" org-registry
)
738 (const :tag
"C screen: Visit screen sessions through Org-mode links" org-screen
)
739 (const :tag
"C secretary: Team management with org-mode" org-secretary
)
740 (const :tag
"C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert
)
741 (const :tag
"C toc: Table of contents for Org-mode buffer" org-toc
)
742 (const :tag
"C track: Keep up with Org-mode development" org-track
)
743 (const :tag
"C velocity Something like Notational Velocity for Org" org-velocity
)
744 (const :tag
"C vm: Links to VM folders/messages" org-vm
)
745 (const :tag
"C wikinodes: CamelCase wiki-like links" org-wikinodes
)
746 (const :tag
"C wl: Links to Wanderlust folders/messages" org-wl
)
747 (repeat :tag
"External packages" :inline t
(symbol :tag
"Package"))))
749 (defvar org-export--registered-backends
) ; From ox.el.
750 (declare-function org-export-derived-backend-p
"ox" (backend &rest backends
))
751 (declare-function org-export-backend-name
"ox" (backend))
752 (defcustom org-export-backends
'(ascii html icalendar latex
)
753 "List of export back-ends that should be always available.
755 If a description starts with <C>, the file is not part of Emacs
756 and loading it will require that you have downloaded and properly
757 installed the Org mode distribution.
759 Unlike to `org-modules', libraries in this list will not be
760 loaded along with Org, but only once the export framework is
763 This variable needs to be set before org.el is loaded. If you
764 need to make a change while Emacs is running, use the customize
765 interface or run the following code, where VAL stands for the new
766 value of the variable, after updating it:
769 \(setq org-export--registered-backends
772 \(let ((name (org-export-backend-name backend)))
776 \(and (org-export-derived-backend-p b name)
777 \(throw 'parentp t)))))))
778 org-export--registered-backends))
779 \(let ((new-list (mapcar 'org-export-backend-name
780 org-export--registered-backends)))
781 \(dolist (backend val)
783 \((not (load (format \"ox-%s\" backend) t t))
784 \(message \"Problems while trying to load export back-end `%s'\"
786 \((not (memq backend new-list)) (push backend new-list))))
787 \(set-default 'org-export-backends new-list)))
789 Adding a back-end to this list will also pull the back-end it
794 :package-version
'(Org .
"8.0")
795 :initialize
'custom-initialize-set
796 :set
(lambda (var val
)
797 (if (not (featurep 'ox
)) (set-default var val
)
798 ;; Any back-end not required anymore (not present in VAL and not
799 ;; a parent of any back-end in the new value) is removed from the
800 ;; list of registered back-ends.
801 (setq org-export--registered-backends
804 (let ((name (org-export-backend-name backend
)))
808 (and (org-export-derived-backend-p b name
)
809 (throw 'parentp t
)))))))
810 org-export--registered-backends
))
811 ;; Now build NEW-LIST of both new back-ends and required
813 (let ((new-list (mapcar 'org-export-backend-name
814 org-export--registered-backends
)))
815 (dolist (backend val
)
817 ((not (load (format "ox-%s" backend
) t t
))
818 (message "Problems while trying to load export back-end `%s'"
820 ((not (memq backend new-list
)) (push backend new-list
))))
821 ;; Set VAR to that list with fixed dependencies.
822 (set-default var new-list
))))
823 :type
'(set :greedy t
824 (const :tag
" ascii Export buffer to ASCII format" ascii
)
825 (const :tag
" beamer Export buffer to Beamer presentation" beamer
)
826 (const :tag
" html Export buffer to HTML format" html
)
827 (const :tag
" icalendar Export buffer to iCalendar format" icalendar
)
828 (const :tag
" latex Export buffer to LaTeX format" latex
)
829 (const :tag
" man Export buffer to MAN format" man
)
830 (const :tag
" md Export buffer to Markdown format" md
)
831 (const :tag
" odt Export buffer to ODT format" odt
)
832 (const :tag
" org Export buffer to Org format" org
)
833 (const :tag
" texinfo Export buffer to Texinfo format" texinfo
)
834 (const :tag
"C confluence Export buffer to Confluence Wiki format" confluence
)
835 (const :tag
"C deck Export buffer to deck.js presentations" deck
)
836 (const :tag
"C freemind Export buffer to Freemind mindmap format" freemind
)
837 (const :tag
"C groff Export buffer to Groff format" groff
)
838 (const :tag
"C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter
)
839 (const :tag
"C RSS 2.0 Export buffer to RSS 2.0 format" rss
)
840 (const :tag
"C s5 Export buffer to s5 presentations" s5
)
841 (const :tag
"C taskjuggler Export buffer to TaskJuggler format" taskjuggler
)))
846 (condition-case nil
(require (intern (format "ox-%s" backend
)))
847 (error (message "Problems while trying to load export back-end `%s'"
849 org-export-backends
))
851 (defcustom org-support-shift-select nil
852 "Non-nil means make shift-cursor commands select text when possible.
854 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
855 start selecting a region, or enlarge regions started in this way.
856 In Org-mode, in special contexts, these same keys are used for
857 other purposes, important enough to compete with shift selection.
858 Org tries to balance these needs by supporting `shift-select-mode'
859 outside these special contexts, under control of this variable.
861 The default of this variable is nil, to avoid confusing behavior. Shifted
862 cursor keys will then execute Org commands in the following contexts:
863 - on a headline, changing TODO state (left/right) and priority (up/down)
864 - on a time stamp, changing the time
865 - in a plain list item, changing the bullet type
866 - in a property definition line, switching between allowed values
867 - in the BEGIN line of a clock table (changing the time block).
868 Outside these contexts, the commands will throw an error.
870 When this variable is t and the cursor is not in a special
871 context, Org-mode will support shift-selection for making and
872 enlarging regions. To make this more effective, the bullet
873 cycling will no longer happen anywhere in an item line, but only
874 if the cursor is exactly on the bullet.
876 If you set this variable to the symbol `always', then the keys
877 will not be special in headlines, property lines, and item lines,
878 to make shift selection work there as well. If this is what you
879 want, you can use the following alternative commands: `C-c C-t'
880 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
881 can be used to switch TODO sets, `C-c -' to cycle item bullet
882 types, and properties can be edited by hand or in column view.
884 However, when the cursor is on a timestamp, shift-cursor commands
885 will still edit the time stamp - this is just too good to give up.
887 XEmacs user should have this variable set to nil, because
888 `shift-select-mode' is in Emacs 23 or later only."
891 (const :tag
"Never" nil
)
892 (const :tag
"When outside special context" t
)
893 (const :tag
"Everywhere except timestamps" always
)))
895 (defcustom org-loop-over-headlines-in-active-region nil
896 "Shall some commands act upon headlines in the active region?
898 When set to `t', some commands will be performed in all headlines
899 within the active region.
901 When set to `start-level', some commands will be performed in all
902 headlines within the active region, provided that these headlines
903 are of the same level than the first one.
905 When set to a string, those commands will be performed on the
906 matching headlines within the active region. Such string must be
907 a tags/property/todo match as it is used in the agenda tags view.
909 The list of commands is: `org-schedule', `org-deadline',
910 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
911 `org-archive-to-archive-sibling'. The archiving commands skip
912 already archived entries."
913 :type
'(choice (const :tag
"Don't loop" nil
)
914 (const :tag
"All headlines in active region" t
)
915 (const :tag
"In active region, headlines at the same level than the first one" start-level
)
916 (string :tag
"Tags/Property/Todo matcher"))
921 (defgroup org-startup nil
922 "Options concerning startup of Org-mode."
926 (defcustom org-startup-folded t
927 "Non-nil means entering Org-mode will switch to OVERVIEW.
928 This can also be configured on a per-file basis by adding one of
929 the following lines anywhere in the buffer:
931 #+STARTUP: fold (or `overview', this is equivalent)
932 #+STARTUP: nofold (or `showall', this is equivalent)
934 #+STARTUP: showeverything
936 By default, this option is ignored when Org opens agenda files
937 for the first time. If you want the agenda to honor the startup
938 option, set `org-agenda-inhibit-startup' to nil."
941 (const :tag
"nofold: show all" nil
)
942 (const :tag
"fold: overview" t
)
943 (const :tag
"content: all headlines" content
)
944 (const :tag
"show everything, even drawers" showeverything
)))
946 (defcustom org-startup-truncated t
947 "Non-nil means entering Org-mode will set `truncate-lines'.
948 This is useful since some lines containing links can be very long and
949 uninteresting. Also tables look terrible when wrapped."
953 (defcustom org-startup-indented nil
954 "Non-nil means turn on `org-indent-mode' on startup.
955 This can also be configured on a per-file basis by adding one of
956 the following lines anywhere in the buffer:
960 :group
'org-structure
962 (const :tag
"Not" nil
)
963 (const :tag
"Globally (slow on startup in large files)" t
)))
965 (defcustom org-use-sub-superscripts t
966 "Non-nil means interpret \"_\" and \"^\" for display.
968 If you want to control how Org exports those characters, see
969 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
970 used to be an alias for `org-export-with-sub-superscripts' in
971 Org <8.0, it is not anymore.
973 When this option is turned on, you can use TeX-like syntax for
974 sub- and superscripts within the buffer. Several characters after
975 \"_\" or \"^\" will be considered as a single item - so grouping
976 with {} is normally not needed. For example, the following things
977 will be parsed as single sub- or superscripts:
979 10^24 or 10^tau several digits will be considered 1 item.
980 10^-12 or 10^-tau a leading sign with digits or a word
981 x^2-y^3 will be read as x^2 - y^3, because items are
982 terminated by almost any nonword/nondigit char.
983 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
985 Still, ambiguity is possible. So when in doubt, use {} to enclose
986 the sub/superscript. If you set this variable to the symbol `{}',
987 the braces are *required* in order to trigger interpretations as
988 sub/superscript. This can be helpful in documents that need \"_\"
989 frequently in plain text."
992 :package-version
'(Org .
"8.0")
994 (const :tag
"Always interpret" t
)
995 (const :tag
"Only with braces" {})
996 (const :tag
"Never interpret" nil
)))
998 (defcustom org-startup-with-beamer-mode nil
999 "Non-nil means turn on `org-beamer-mode' on startup.
1000 This can also be configured on a per-file basis by adding one of
1001 the following lines anywhere in the buffer:
1008 (defcustom org-startup-align-all-tables nil
1009 "Non-nil means align all tables when visiting a file.
1010 This is useful when the column width in tables is forced with <N> cookies
1011 in table fields. Such tables will look correct only after the first re-align.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1019 (defcustom org-startup-with-inline-images nil
1020 "Non-nil means show inline images when loading a new Org file.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: inlineimages
1024 #+STARTUP: noinlineimages"
1029 (defcustom org-startup-with-latex-preview nil
1030 "Non-nil means preview LaTeX fragments when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: latexpreview
1035 #+STARTUP: nolatexpreview"
1038 :package-version
'(Org .
"8.0")
1041 (defcustom org-insert-mode-line-in-empty-file nil
1042 "Non-nil means insert the first line setting Org-mode in empty files.
1043 When the function `org-mode' is called interactively in an empty file, this
1044 normally means that the file name does not automatically trigger Org-mode.
1045 To ensure that the file will always be in Org-mode in the future, a
1046 line enforcing Org-mode will be inserted into the buffer, if this option
1051 (defcustom org-replace-disputed-keys nil
1052 "Non-nil means use alternative key bindings for some keys.
1053 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1054 These keys are also used by other packages like shift-selection-mode'
1055 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1056 If you want to use Org-mode together with one of these other modes,
1057 or more generally if you would like to move some Org-mode commands to
1058 other keys, set this variable and configure the keys with the variable
1059 `org-disputed-keys'.
1061 This option is only relevant at load-time of Org-mode, and must be set
1062 *before* org.el is loaded. Changing it requires a restart of Emacs to
1067 (defcustom org-use-extra-keys nil
1068 "Non-nil means use extra key sequence definitions for certain commands.
1069 This happens automatically if you run XEmacs or if `window-system'
1070 is nil. This variable lets you do the same manually. You must
1071 set it before loading org.
1073 Example: on Carbon Emacs 22 running graphically, with an external
1074 keyboard on a Powerbook, the default way of setting M-left might
1075 not work for either Alt or ESC. Setting this variable will make
1080 (org-defvaralias 'org-CUA-compatible
'org-replace-disputed-keys
)
1082 (defcustom org-disputed-keys
1083 '(([(shift up
)] .
[(meta p
)])
1084 ([(shift down
)] .
[(meta n
)])
1085 ([(shift left
)] .
[(meta -
)])
1086 ([(shift right
)] .
[(meta +)])
1087 ([(control shift right
)] .
[(meta shift
+)])
1088 ([(control shift left
)] .
[(meta shift -
)]))
1089 "Keys for which Org-mode and other modes compete.
1090 This is an alist, cars are the default keys, second element specifies
1091 the alternative to use when `org-replace-disputed-keys' is t.
1093 Keys can be specified in any syntax supported by `define-key'.
1094 The value of this option takes effect only at Org-mode's startup,
1095 therefore you'll have to restart Emacs to apply it after changing."
1099 (defun org-key (key)
1100 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1101 Or return the original if not disputed.
1102 Also apply the translations defined in `org-xemacs-key-equivalents'."
1103 (when org-replace-disputed-keys
1104 (let* ((nkey (key-description key
))
1105 (x (org-find-if (lambda (x)
1106 (equal (key-description (car x
)) nkey
))
1107 org-disputed-keys
)))
1108 (setq key
(if x
(cdr x
) key
))))
1109 (when (featurep 'xemacs
)
1110 (setq key
(or (cdr (assoc key org-xemacs-key-equivalents
)) key
)))
1113 (defun org-find-if (predicate seq
)
1116 (if (funcall predicate
(car seq
))
1117 (throw 'exit
(car seq
))
1120 (defun org-defkey (keymap key def
)
1121 "Define a key, possibly translated, as returned by `org-key'."
1122 (define-key keymap
(org-key key
) def
))
1124 (defcustom org-ellipsis nil
1125 "The ellipsis to use in the Org-mode outline.
1126 When nil, just use the standard three dots.
1127 When a string, use that string instead.
1128 When a face, use the standard 3 dots, but with the specified face.
1129 The change affects only Org-mode (which will then use its own display table).
1130 Changing this requires executing \\[org-mode] in a buffer to become
1133 :type
'(choice (const :tag
"Default" nil
)
1134 (face :tag
"Face" :value org-warning
)
1135 (string :tag
"String" :value
"...#")))
1137 (defvar org-display-table nil
1138 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1140 (defgroup org-keywords nil
1141 "Keywords in Org-mode."
1145 (defcustom org-closed-keep-when-no-todo nil
1146 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1148 :group
'org-keywords
1150 :package-version
'(Org .
"8.0")
1153 (defgroup org-structure nil
1154 "Options concerning the general structure of Org-mode files."
1155 :tag
"Org Structure"
1158 (defgroup org-reveal-location nil
1159 "Options about how to make context of a location visible."
1160 :tag
"Org Reveal Location"
1161 :group
'org-structure
)
1163 (defconst org-context-choice
1165 (const :tag
"Always" t
)
1166 (const :tag
"Never" nil
)
1167 (repeat :greedy t
:tag
"Individual contexts"
1169 (choice :tag
"Context"
1176 (const bookmark-jump
)
1180 "Contexts for the reveal options.")
1182 (defcustom org-show-hierarchy-above
'((default . t
))
1183 "Non-nil means show full hierarchy when revealing a location.
1184 Org-mode often shows locations in an org-mode file which might have
1185 been invisible before. When this is set, the hierarchy of headings
1186 above the exposed location is shown.
1187 Turning this off for example for sparse trees makes them very compact.
1188 Instead of t, this can also be an alist specifying this option for different
1189 contexts. Valid contexts are
1190 agenda when exposing an entry from the agenda
1191 org-goto when using the command `org-goto' on key C-c C-j
1192 occur-tree when using the command `org-occur' on key C-c /
1193 tags-tree when constructing a sparse tree based on tags matches
1194 link-search when exposing search matches associated with a link
1195 mark-goto when exposing the jump goal of a mark
1196 bookmark-jump when exposing a bookmark location
1197 isearch when exiting from an incremental search
1198 default default for all contexts not set explicitly"
1199 :group
'org-reveal-location
1200 :type org-context-choice
)
1202 (defcustom org-show-following-heading
'((default . nil
))
1203 "Non-nil means show following heading when revealing a location.
1204 Org-mode often shows locations in an org-mode file which might have
1205 been invisible before. When this is set, the heading following the
1207 Turning this off for example for sparse trees makes them very compact,
1208 but makes it harder to edit the location of the match. In such a case,
1209 use the command \\[org-reveal] to show more context.
1210 Instead of t, this can also be an alist specifying this option for different
1211 contexts. See `org-show-hierarchy-above' for valid contexts."
1212 :group
'org-reveal-location
1213 :type org-context-choice
)
1215 (defcustom org-show-siblings
'((default . nil
) (isearch t
) (bookmark-jump t
))
1216 "Non-nil means show all sibling heading when revealing a location.
1217 Org-mode often shows locations in an org-mode file which might have
1218 been invisible before. When this is set, the sibling of the current entry
1219 heading are all made visible. If `org-show-hierarchy-above' is t,
1220 the same happens on each level of the hierarchy above the current entry.
1222 By default this is on for the isearch context, off for all other contexts.
1223 Turning this off for example for sparse trees makes them very compact,
1224 but makes it harder to edit the location of the match. In such a case,
1225 use the command \\[org-reveal] to show more context.
1226 Instead of t, this can also be an alist specifying this option for different
1227 contexts. See `org-show-hierarchy-above' for valid contexts."
1228 :group
'org-reveal-location
1229 :type org-context-choice
1231 :package-version
'(Org .
"8.0"))
1233 (defcustom org-show-entry-below
'((default . nil
))
1234 "Non-nil means show the entry below a headline when revealing a location.
1235 Org-mode often shows locations in an org-mode file which might have
1236 been invisible before. When this is set, the text below the headline that is
1237 exposed is also shown.
1239 By default this is off for all contexts.
1240 Instead of t, this can also be an alist specifying this option for different
1241 contexts. See `org-show-hierarchy-above' for valid contexts."
1242 :group
'org-reveal-location
1243 :type org-context-choice
)
1245 (defcustom org-indirect-buffer-display
'other-window
1246 "How should indirect tree buffers be displayed?
1247 This applies to indirect buffers created with the commands
1248 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1250 current-window Display in the current window
1251 other-window Just display in another window.
1252 dedicated-frame Create one new frame, and re-use it each time.
1253 new-frame Make a new frame each time. Note that in this case
1254 previously-made indirect buffers are kept, and you need to
1255 kill these buffers yourself."
1256 :group
'org-structure
1257 :group
'org-agenda-windows
1259 (const :tag
"In current window" current-window
)
1260 (const :tag
"In current frame, other window" other-window
)
1261 (const :tag
"Each time a new frame" new-frame
)
1262 (const :tag
"One dedicated frame" dedicated-frame
)))
1264 (defcustom org-use-speed-commands nil
1265 "Non-nil means activate single letter commands at beginning of a headline.
1266 This may also be a function to test for appropriate locations where speed
1267 commands should be active.
1269 For example, to activate speed commands when the point is on any
1270 star at the beginning of the headline, you can do this:
1272 (setq org-use-speed-commands
1273 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1274 :group
'org-structure
1276 (const :tag
"Never" nil
)
1277 (const :tag
"At beginning of headline stars" t
)
1280 (defcustom org-speed-commands-user nil
1281 "Alist of additional speed commands.
1282 This list will be checked before `org-speed-commands-default'
1283 when the variable `org-use-speed-commands' is non-nil
1284 and when the cursor is at the beginning of a headline.
1285 The car if each entry is a string with a single letter, which must
1286 be assigned to `self-insert-command' in the global map.
1287 The cdr is either a command to be called interactively, a function
1288 to be called, or a form to be evaluated.
1289 An entry that is just a list with a single string will be interpreted
1290 as a descriptive headline that will be added when listing the speed
1291 commands in the Help buffer using the `?' speed command."
1292 :group
'org-structure
1293 :type
'(repeat :value
("k" . ignore
)
1294 (choice :value
("k" . ignore
)
1295 (list :tag
"Descriptive Headline" (string :tag
"Headline"))
1296 (cons :tag
"Letter and Command"
1297 (string :tag
"Command letter")
1302 (defcustom org-bookmark-names-plist
1303 '(:last-capture
"org-capture-last-stored"
1304 :last-refile
"org-refile-last-stored"
1305 :last-capture-marker
"org-capture-last-stored-marker")
1306 "Names for bookmarks automatically set by some Org commands.
1307 This can provide strings as names for a number of bookmarks Org sets
1308 automatically. The following keys are currently implemented:
1310 :last-capture-marker
1312 When a key does not show up in the property list, the corresponding bookmark
1314 :group
'org-structure
1317 (defgroup org-cycle nil
1318 "Options concerning visibility cycling in Org-mode."
1320 :group
'org-structure
)
1322 (defcustom org-cycle-skip-children-state-if-no-children t
1323 "Non-nil means skip CHILDREN state in entries that don't have any."
1327 (defcustom org-cycle-max-level nil
1328 "Maximum level which should still be subject to visibility cycling.
1329 Levels higher than this will, for cycling, be treated as text, not a headline.
1330 When `org-odd-levels-only' is set, a value of N in this variable actually
1331 means 2N-1 stars as the limiting headline.
1332 When nil, cycle all levels.
1333 Note that the limiting level of cycling is also influenced by
1334 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1335 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1339 (const :tag
"No limit" nil
)
1340 (integer :tag
"Maximum level")))
1342 (defcustom org-hide-block-startup nil
1343 "Non-nil means entering Org-mode will fold all blocks.
1344 This can also be set in on a per-file basis with
1346 #+STARTUP: hideblocks
1347 #+STARTUP: showblocks"
1352 (defcustom org-cycle-global-at-bob nil
1353 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1354 This makes it possible to do global cycling without having to use S-TAB or
1355 \\[universal-argument] TAB. For this special case to work, the first line
1356 of the buffer must not be a headline -- it may be empty or some other text.
1357 When used in this way, `org-cycle-hook' is disabled temporarily to make
1358 sure the cursor stays at the beginning of the buffer. When this option is
1359 nil, don't do anything special at the beginning of the buffer."
1363 (defcustom org-cycle-level-after-item
/entry-creation t
1364 "Non-nil means cycle entry level or item indentation in new empty entries.
1366 When the cursor is at the end of an empty headline, i.e., with only stars
1367 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1368 and then all possible ancestor states, before returning to the original state.
1369 This makes data entry extremely fast: M-RET to create a new headline,
1370 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1372 When the cursor is at the end of an empty plain list item, one TAB will
1373 make it a subitem, two or more tabs will back up to make this an item
1374 higher up in the item hierarchy."
1378 (defcustom org-cycle-emulate-tab t
1379 "Where should `org-cycle' emulate TAB.
1381 white Only in completely white lines
1382 whitestart Only at the beginning of lines, before the first non-white char
1383 t Everywhere except in headlines
1384 exc-hl-bol Everywhere except at the start of a headline
1385 If TAB is used in a place where it does not emulate TAB, the current subtree
1386 visibility is cycled."
1388 :type
'(choice (const :tag
"Never" nil
)
1389 (const :tag
"Only in completely white lines" white
)
1390 (const :tag
"Before first char in a line" whitestart
)
1391 (const :tag
"Everywhere except in headlines" t
)
1392 (const :tag
"Everywhere except at bol in headlines" exc-hl-bol
)))
1394 (defcustom org-cycle-separator-lines
2
1395 "Number of empty lines needed to keep an empty line between collapsed trees.
1396 If you leave an empty line between the end of a subtree and the following
1397 headline, this empty line is hidden when the subtree is folded.
1398 Org-mode will leave (exactly) one empty line visible if the number of
1399 empty lines is equal or larger to the number given in this variable.
1400 So the default 2 means at least 2 empty lines after the end of a subtree
1401 are needed to produce free space between a collapsed subtree and the
1404 If the number is negative, and the number of empty lines is at least -N,
1405 all empty lines are shown.
1407 Special case: when 0, never leave empty lines in collapsed view."
1410 (put 'org-cycle-separator-lines
'safe-local-variable
'integerp
)
1412 (defcustom org-pre-cycle-hook nil
1413 "Hook that is run before visibility cycling is happening.
1414 The function(s) in this hook must accept a single argument which indicates
1415 the new state that will be set right after running this hook. The
1416 argument is a symbol. Before a global state change, it can have the values
1417 `overview', `content', or `all'. Before a local state change, it can have
1418 the values `folded', `children', or `subtree'."
1422 (defcustom org-cycle-hook
'(org-cycle-hide-archived-subtrees
1423 org-cycle-hide-drawers
1424 org-cycle-hide-inline-tasks
1425 org-cycle-show-empty-lines
1426 org-optimize-window-after-visibility-change
)
1427 "Hook that is run after `org-cycle' has changed the buffer visibility.
1428 The function(s) in this hook must accept a single argument which indicates
1429 the new state that was set by the most recent `org-cycle' command. The
1430 argument is a symbol. After a global state change, it can have the values
1431 `overview', `contents', or `all'. After a local state change, it can have
1432 the values `folded', `children', or `subtree'."
1436 (defgroup org-edit-structure nil
1437 "Options concerning structure editing in Org-mode."
1438 :tag
"Org Edit Structure"
1439 :group
'org-structure
)
1441 (defcustom org-odd-levels-only nil
1442 "Non-nil means skip even levels and only use odd levels for the outline.
1443 This has the effect that two stars are being added/taken away in
1444 promotion/demotion commands. It also influences how levels are
1445 handled by the exporters.
1446 Changing it requires restart of `font-lock-mode' to become effective
1447 for fontification also in regions already fontified.
1448 You may also set this on a per-file basis by adding one of the following
1449 lines to the buffer:
1453 :group
'org-edit-structure
1454 :group
'org-appearance
1457 (defcustom org-adapt-indentation t
1458 "Non-nil means adapt indentation to outline node level.
1460 When this variable is set, Org assumes that you write outlines by
1461 indenting text in each node to align with the headline (after the stars).
1462 The following issues are influenced by this variable:
1464 - When this is set and the *entire* text in an entry is indented, the
1465 indentation is increased by one space in a demotion command, and
1466 decreased by one in a promotion command. If any line in the entry
1467 body starts with text at column 0, indentation is not changed at all.
1469 - Property drawers and planning information is inserted indented when
1470 this variable s set. When nil, they will not be indented.
1472 - TAB indents a line relative to context. The lines below a headline
1473 will be indented when this variable is set.
1475 Note that this is all about true indentation, by adding and removing
1476 space characters. See also `org-indent.el' which does level-dependent
1477 indentation in a virtual way, i.e. at display time in Emacs."
1478 :group
'org-edit-structure
1481 (defcustom org-special-ctrl-a
/e nil
1482 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1484 When t, `C-a' will bring back the cursor to the beginning of the
1485 headline text, i.e. after the stars and after a possible TODO
1486 keyword. In an item, this will be the position after bullet and
1487 check-box, if any. When the cursor is already at that position,
1488 another `C-a' will bring it to the beginning of the line.
1490 `C-e' will jump to the end of the headline, ignoring the presence
1491 of tags in the headline. A second `C-e' will then jump to the
1492 true end of the line, after any tags. This also means that, when
1493 this variable is non-nil, `C-e' also will never jump beyond the
1494 end of the heading of a folded section, i.e. not after the
1497 When set to the symbol `reversed', the first `C-a' or `C-e' works
1498 normally, going to the true line boundary first. Only a directly
1499 following, identical keypress will bring the cursor to the
1502 This may also be a cons cell where the behavior for `C-a' and
1503 `C-e' is set separately."
1504 :group
'org-edit-structure
1506 (const :tag
"off" nil
)
1507 (const :tag
"on: after stars/bullet and before tags first" t
)
1508 (const :tag
"reversed: true line boundary first" reversed
)
1509 (cons :tag
"Set C-a and C-e separately"
1510 (choice :tag
"Special C-a"
1511 (const :tag
"off" nil
)
1512 (const :tag
"on: after stars/bullet first" t
)
1513 (const :tag
"reversed: before stars/bullet first" reversed
))
1514 (choice :tag
"Special C-e"
1515 (const :tag
"off" nil
)
1516 (const :tag
"on: before tags first" t
)
1517 (const :tag
"reversed: after tags first" reversed
)))))
1518 (org-defvaralias 'org-special-ctrl-a
'org-special-ctrl-a
/e
)
1520 (defcustom org-special-ctrl-k nil
1521 "Non-nil means `C-k' will behave specially in headlines.
1522 When nil, `C-k' will call the default `kill-line' command.
1523 When t, the following will happen while the cursor is in the headline:
1525 - When the cursor is at the beginning of a headline, kill the entire
1526 line and possible the folded subtree below the line.
1527 - When in the middle of the headline text, kill the headline up to the tags.
1528 - When after the headline text, kill the tags."
1529 :group
'org-edit-structure
1532 (defcustom org-ctrl-k-protect-subtree nil
1533 "Non-nil means, do not delete a hidden subtree with C-k.
1534 When set to the symbol `error', simply throw an error when C-k is
1535 used to kill (part-of) a headline that has hidden text behind it.
1536 Any other non-nil value will result in a query to the user, if it is
1537 OK to kill that hidden subtree. When nil, kill without remorse."
1538 :group
'org-edit-structure
1541 (const :tag
"Do not protect hidden subtrees" nil
)
1542 (const :tag
"Protect hidden subtrees with a security query" t
)
1543 (const :tag
"Never kill a hidden subtree with C-k" error
)))
1545 (defcustom org-special-ctrl-o t
1546 "Non-nil means, make `C-o' insert a row in tables."
1547 :group
'org-edit-structure
1550 (defcustom org-catch-invisible-edits nil
1551 "Check if in invisible region before inserting or deleting a character.
1554 nil Do not check, so just do invisible edits.
1555 error Throw an error and do nothing.
1556 show Make point visible, and do the requested edit.
1557 show-and-error Make point visible, then throw an error and abort the edit.
1558 smart Make point visible, and do insertion/deletion if it is
1559 adjacent to visible text and the change feels predictable.
1560 Never delete a previously invisible character or add in the
1561 middle or right after an invisible region. Basically, this
1562 allows insertion and backward-delete right before ellipses.
1563 FIXME: maybe in this case we should not even show?"
1564 :group
'org-edit-structure
1567 (const :tag
"Do not check" nil
)
1568 (const :tag
"Throw error when trying to edit" error
)
1569 (const :tag
"Unhide, but do not do the edit" show-and-error
)
1570 (const :tag
"Show invisible part and do the edit" show
)
1571 (const :tag
"Be smart and do the right thing" smart
)))
1573 (defcustom org-yank-folded-subtrees t
1574 "Non-nil means when yanking subtrees, fold them.
1575 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1576 it starts with a heading and all other headings in it are either children
1577 or siblings, then fold all the subtrees. However, do this only if no
1578 text after the yank would be swallowed into a folded tree by this action."
1579 :group
'org-edit-structure
1582 (defcustom org-yank-adjusted-subtrees nil
1583 "Non-nil means when yanking subtrees, adjust the level.
1584 With this setting, `org-paste-subtree' is used to insert the subtree, see
1585 this function for details."
1586 :group
'org-edit-structure
1589 (defcustom org-M-RET-may-split-line
'((default . t
))
1590 "Non-nil means M-RET will split the line at the cursor position.
1591 When nil, it will go to the end of the line before making a
1593 You may also set this option in a different way for different
1594 contexts. Valid contexts are:
1596 headline when creating a new headline
1597 item when creating a new item
1598 table in a table field
1599 default the value to be used for all contexts not explicitly
1601 :group
'org-structure
1604 (const :tag
"Always" t
)
1605 (const :tag
"Never" nil
)
1606 (repeat :greedy t
:tag
"Individual contexts"
1608 (choice :tag
"Context"
1616 (defcustom org-insert-heading-respect-content nil
1617 "Non-nil means insert new headings after the current subtree.
1618 When nil, the new heading is created directly after the current line.
1619 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1620 this variable on for the duration of the command."
1621 :group
'org-structure
1624 (defcustom org-blank-before-new-entry
'((heading . auto
)
1625 (plain-list-item . auto
))
1626 "Should `org-insert-heading' leave a blank line before new heading/item?
1627 The value is an alist, with `heading' and `plain-list-item' as CAR,
1628 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1629 which case Org will look at the surrounding headings/items and try to
1630 make an intelligent decision whether to insert a blank line or not.
1632 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1633 the setting here is ignored and no empty line is inserted to avoid breaking
1634 the list structure."
1635 :group
'org-edit-structure
1637 (cons (const heading
)
1638 (choice (const :tag
"Never" nil
)
1639 (const :tag
"Always" t
)
1640 (const :tag
"Auto" auto
)))
1641 (cons (const plain-list-item
)
1642 (choice (const :tag
"Never" nil
)
1643 (const :tag
"Always" t
)
1644 (const :tag
"Auto" auto
)))))
1646 (defcustom org-insert-heading-hook nil
1647 "Hook being run after inserting a new heading."
1648 :group
'org-edit-structure
1651 (defcustom org-enable-fixed-width-editor t
1652 "Non-nil means lines starting with \":\" are treated as fixed-width.
1653 This currently only means they are never auto-wrapped.
1654 When nil, such lines will be treated like ordinary lines."
1655 :group
'org-edit-structure
1658 (defcustom org-goto-auto-isearch t
1659 "Non-nil means typing characters in `org-goto' starts incremental search.
1660 When nil, you can use these keybindings to navigate the buffer:
1662 q Quit the org-goto interface
1663 n Go to the next visible heading
1664 p Go to the previous visible heading
1665 f Go one heading forward on same level
1666 b Go one heading backward on same level
1667 u Go one heading up"
1668 :group
'org-edit-structure
1671 (defgroup org-sparse-trees nil
1672 "Options concerning sparse trees in Org-mode."
1673 :tag
"Org Sparse Trees"
1674 :group
'org-structure
)
1676 (defcustom org-highlight-sparse-tree-matches t
1677 "Non-nil means highlight all matches that define a sparse tree.
1678 The highlights will automatically disappear the next time the buffer is
1679 changed by an edit command."
1680 :group
'org-sparse-trees
1683 (defcustom org-remove-highlights-with-change t
1684 "Non-nil means any change to the buffer will remove temporary highlights.
1685 Such highlights are created by `org-occur' and `org-clock-display'.
1686 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1687 The highlights created by `org-toggle-latex-fragment' always need
1688 `C-c C-x C-l' to be removed."
1689 :group
'org-sparse-trees
1694 (defcustom org-occur-hook
'(org-first-headline-recenter)
1695 "Hook that is run after `org-occur' has constructed a sparse tree.
1696 This can be used to recenter the window to show as much of the structure
1698 :group
'org-sparse-trees
1701 (defgroup org-imenu-and-speedbar nil
1702 "Options concerning imenu and speedbar in Org-mode."
1703 :tag
"Org Imenu and Speedbar"
1704 :group
'org-structure
)
1706 (defcustom org-imenu-depth
2
1707 "The maximum level for Imenu access to Org-mode headlines.
1708 This also applied for speedbar access."
1709 :group
'org-imenu-and-speedbar
1712 (defgroup org-table nil
1713 "Options concerning tables in Org-mode."
1717 (defcustom org-enable-table-editor
'optimized
1718 "Non-nil means lines starting with \"|\" are handled by the table editor.
1719 When nil, such lines will be treated like ordinary lines.
1721 When equal to the symbol `optimized', the table editor will be optimized to
1723 - Automatic overwrite mode in front of whitespace in table fields.
1724 This makes the structure of the table stay in tact as long as the edited
1725 field does not exceed the column width.
1726 - Minimize the number of realigns. Normally, the table is aligned each time
1727 TAB or RET are pressed to move to another field. With optimization this
1728 happens only if changes to a field might have changed the column width.
1729 Optimization requires replacing the functions `self-insert-command',
1730 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1731 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1732 very good at guessing when a re-align will be necessary, but you can always
1733 force one with \\[org-ctrl-c-ctrl-c].
1735 If you would like to use the optimized version in Org-mode, but the
1736 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1738 This variable can be used to turn on and off the table editor during a session,
1739 but in order to toggle optimization, a restart is required.
1741 See also the variable `org-table-auto-blank-field'."
1744 (const :tag
"off" nil
)
1746 (const :tag
"on, optimized" optimized
)))
1748 (defcustom org-self-insert-cluster-for-undo
(or (featurep 'xemacs
)
1749 (version<= emacs-version
"24.1"))
1750 "Non-nil means cluster self-insert commands for undo when possible.
1751 If this is set, then, like in the Emacs command loop, 20 consecutive
1752 characters will be undone together.
1753 This is configurable, because there is some impact on typing performance."
1757 (defcustom org-table-tab-recognizes-table.el t
1758 "Non-nil means TAB will automatically notice a table.el table.
1759 When it sees such a table, it moves point into it and - if necessary -
1760 calls `table-recognize-table'."
1761 :group
'org-table-editing
1764 (defgroup org-link nil
1765 "Options concerning links in Org-mode."
1769 (defvar org-link-abbrev-alist-local nil
1770 "Buffer-local version of `org-link-abbrev-alist', which see.
1771 The value of this is taken from the #+LINK lines.")
1772 (make-variable-buffer-local 'org-link-abbrev-alist-local
)
1774 (defcustom org-link-abbrev-alist nil
1775 "Alist of link abbreviations.
1776 The car of each element is a string, to be replaced at the start of a link.
1777 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1778 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1780 [[linkkey:tag][description]]
1782 The 'linkkey' must be a word word, starting with a letter, followed
1783 by letters, numbers, '-' or '_'.
1785 If REPLACE is a string, the tag will simply be appended to create the link.
1786 If the string contains \"%s\", the tag will be inserted there. If the string
1787 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1788 at that point (see the function `url-hexify-string'). If the string contains
1789 the specifier \"%(my-function)\", then the custom function `my-function' will
1790 be invoked: this function takes the tag as its only argument and must return
1793 REPLACE may also be a function that will be called with the tag as the
1794 only argument to create the link, which should be returned as a string.
1796 See the manual for examples."
1800 (string :tag
"Protocol")
1802 (string :tag
"Format")
1805 (defcustom org-descriptive-links t
1806 "Non-nil means Org will display descriptive links.
1807 E.g. [[http://orgmode.org][Org website]] will be displayed as
1808 \"Org Website\", hiding the link itself and just displaying its
1809 description. When set to `nil', Org will display the full links
1812 You can interactively set the value of this variable by calling
1813 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1817 (defcustom org-link-file-path-type
'adaptive
1818 "How the path name in file links should be stored.
1821 relative Relative to the current directory, i.e. the directory of the file
1822 into which the link is being inserted.
1823 absolute Absolute path, if possible with ~ for home directory.
1824 noabbrev Absolute path, no abbreviation of home directory.
1825 adaptive Use relative path for files in the current directory and sub-
1826 directories of it. For other files, use an absolute path."
1834 (defvaralias 'org-activate-links
'org-highlight-links
)
1835 (defcustom org-highlight-links
'(bracket angle plain radio tag date footnote
)
1836 "Types of links that should be highlighted in Org-mode files.
1838 This is a list of symbols, each one of them leading to the
1839 highlighting of a certain link type.
1841 You can still open links that are not highlighted.
1843 In principle, it does not hurt to turn on highlighting for all
1844 link types. There may be a small gain when turning off unused
1845 link types. The types are:
1847 bracket The recommended [[link][description]] or [[link]] links with hiding.
1848 angle Links in angular brackets that may contain whitespace like
1849 <bbdb:Carsten Dominik>.
1850 plain Plain links in normal text, no whitespace, like http://google.com.
1851 radio Text that is matched by a radio target, see manual for details.
1852 tag Tag settings in a headline (link to tag search).
1853 date Time stamps (link to calendar).
1854 footnote Footnote labels.
1856 If you set this variable during an Emacs session, use `org-mode-restart'
1857 in the Org buffer so that the change takes effect."
1859 :group
'org-appearance
1860 :type
'(set :greedy t
1861 (const :tag
"Double bracket links" bracket
)
1862 (const :tag
"Angular bracket links" angle
)
1863 (const :tag
"Plain text links" plain
)
1864 (const :tag
"Radio target matches" radio
)
1865 (const :tag
"Tags" tag
)
1866 (const :tag
"Timestamps" date
)
1867 (const :tag
"Footnotes" footnote
)))
1869 (defcustom org-make-link-description-function nil
1870 "Function to use for generating link descriptions from links.
1871 When nil, the link location will be used. This function must take
1872 two parameters: the first one is the link, the second one is the
1873 description generated by `org-insert-link'. The function should
1874 return the description to use."
1876 :type
'(choice (const nil
) (function)))
1878 (defgroup org-link-store nil
1879 "Options concerning storing links in Org-mode."
1880 :tag
"Org Store Link"
1883 (defcustom org-url-hexify-p t
1884 "When non-nil, hexify URL when creating a link."
1887 :group
'org-link-store
)
1889 (defcustom org-email-link-description-format
"Email %c: %.30s"
1890 "Format of the description part of a link to an email or usenet message.
1891 The following %-escapes will be replaced by corresponding information:
1893 %F full \"From\" field
1894 %f name, taken from \"From\" field, address if no name
1895 %T full \"To\" field
1896 %t first name in \"To\" field, address if no name
1897 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1898 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1903 You may use normal field width specification between the % and the letter.
1904 This is for example useful to limit the length of the subject.
1906 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1907 :group
'org-link-store
1910 (defcustom org-from-is-user-regexp
1912 (when (and user-mail-address
(not (string= user-mail-address
"")))
1913 (setq r1
(concat "\\<" (regexp-quote user-mail-address
) "\\>")))
1914 (when (and user-full-name
(not (string= user-full-name
"")))
1915 (setq r2
(concat "\\<" (regexp-quote user-full-name
) "\\>")))
1916 (if (and r1 r2
) (concat r1
"\\|" r2
) (or r1 r2
)))
1917 "Regexp matched against the \"From:\" header of an email or usenet message.
1918 It should match if the message is from the user him/herself."
1919 :group
'org-link-store
1922 (defcustom org-context-in-file-links t
1923 "Non-nil means file links from `org-store-link' contain context.
1924 A search string will be added to the file name with :: as separator and
1925 used to find the context when the link is activated by the command
1926 `org-open-at-point'. When this option is t, the entire active region
1927 will be placed in the search string of the file link. If set to a
1928 positive integer, only the first n lines of context will be stored.
1930 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1931 negates this setting for the duration of the command."
1932 :group
'org-link-store
1933 :type
'(choice boolean integer
))
1935 (defcustom org-keep-stored-link-after-insertion nil
1936 "Non-nil means keep link in list for entire session.
1938 The command `org-store-link' adds a link pointing to the current
1939 location to an internal list. These links accumulate during a session.
1940 The command `org-insert-link' can be used to insert links into any
1941 Org-mode file (offering completion for all stored links). When this
1942 option is nil, every link which has been inserted once using \\[org-insert-link]
1943 will be removed from the list, to make completing the unused links
1945 :group
'org-link-store
1948 (defgroup org-link-follow nil
1949 "Options concerning following links in Org-mode."
1950 :tag
"Org Follow Link"
1953 (defcustom org-link-translation-function nil
1954 "Function to translate links with different syntax to Org syntax.
1955 This can be used to translate links created for example by the Planner
1956 or emacs-wiki packages to Org syntax.
1957 The function must accept two parameters, a TYPE containing the link
1958 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1959 which is everything after the link protocol. It should return a cons
1960 with possibly modified values of type and path.
1961 Org contains a function for this, so if you set this variable to
1962 `org-translate-link-from-planner', you should be able follow many
1963 links created by planner."
1964 :group
'org-link-follow
1965 :type
'(choice (const nil
) (function)))
1967 (defcustom org-follow-link-hook nil
1968 "Hook that is run after a link has been followed."
1969 :group
'org-link-follow
1972 (defcustom org-tab-follows-link nil
1973 "Non-nil means on links TAB will follow the link.
1974 Needs to be set before org.el is loaded.
1975 This really should not be used, it does not make sense, and the
1976 implementation is bad."
1977 :group
'org-link-follow
1980 (defcustom org-return-follows-link nil
1981 "Non-nil means on links RET will follow the link.
1982 In tables, the special behavior of RET has precedence."
1983 :group
'org-link-follow
1986 (defcustom org-mouse-1-follows-link
1987 (if (boundp 'mouse-1-click-follows-link
) mouse-1-click-follows-link t
)
1988 "Non-nil means mouse-1 on a link will follow the link.
1989 A longer mouse click will still set point. Does not work on XEmacs.
1990 Needs to be set before org.el is loaded."
1991 :group
'org-link-follow
1993 :package-version
'(Org .
"8.3")
1995 (const :tag
"A double click follows the link" double
)
1996 (const :tag
"Unconditionally follow the link with mouse-1" t
)
1997 (integer :tag
"mouse-1 click does not follow the link if longer than N ms" 450)))
1999 (defcustom org-mark-ring-length
4
2000 "Number of different positions to be recorded in the ring.
2001 Changing this requires a restart of Emacs to work correctly."
2002 :group
'org-link-follow
2005 (defcustom org-link-search-must-match-exact-headline
'query-to-create
2006 "Non-nil means internal links in Org files must exactly match a headline.
2007 When nil, the link search tries to match a phrase with all words
2008 in the search text."
2009 :group
'org-link-follow
2012 (const :tag
"Use fuzzy text search" nil
)
2013 (const :tag
"Match only exact headline" t
)
2014 (const :tag
"Match exact headline or query to create it"
2017 (defcustom org-link-frame-setup
2018 '((vm . vm-visit-folder-other-frame
)
2019 (vm-imap . vm-visit-imap-folder-other-frame
)
2020 (gnus . org-gnus-no-new-news
)
2021 (file . find-file-other-window
)
2022 (wl . wl-other-frame
))
2023 "Setup the frame configuration for following links.
2024 When following a link with Emacs, it may often be useful to display
2025 this link in another window or frame. This variable can be used to
2026 set this up for the different types of links.
2029 `vm-visit-folder-other-window'
2030 `vm-visit-folder-other-frame'
2031 For Gnus, use any of
2034 `org-gnus-no-new-news'
2035 For FILE, use any of
2037 `find-file-other-window'
2038 `find-file-other-frame'
2039 For Wanderlust use any of
2042 For the calendar, use the variable `calendar-setup'.
2043 For BBDB, it is currently only possible to display the matches in
2045 :group
'org-link-follow
2049 (const vm-visit-folder
)
2050 (const vm-visit-folder-other-window
)
2051 (const vm-visit-folder-other-frame
)))
2052 (cons (const vm-imap
)
2054 (const vm-visit-imap-folder
)
2055 (const vm-visit-imap-folder-other-window
)
2056 (const vm-visit-imap-folder-other-frame
)))
2060 (const gnus-other-frame
)
2061 (const org-gnus-no-new-news
)))
2065 (const find-file-other-window
)
2066 (const find-file-other-frame
)))
2070 (const wl-other-frame
)))))
2072 (defcustom org-display-internal-link-with-indirect-buffer nil
2073 "Non-nil means use indirect buffer to display infile links.
2074 Activating internal links (from one location in a file to another location
2075 in the same file) normally just jumps to the location. When the link is
2076 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2078 another window. When this option is set, the other window actually displays
2079 an indirect buffer clone of the current buffer, to avoid any visibility
2080 changes to the current buffer."
2081 :group
'org-link-follow
2084 (defcustom org-open-non-existing-files nil
2085 "Non-nil means `org-open-file' will open non-existing files.
2086 When nil, an error will be generated.
2087 This variable applies only to external applications because they
2088 might choke on non-existing files. If the link is to a file that
2089 will be opened in Emacs, the variable is ignored."
2090 :group
'org-link-follow
2093 (defcustom org-open-directory-means-index-dot-org nil
2094 "Non-nil means a link to a directory really means to index.org.
2095 When nil, following a directory link will run dired or open a finder/explorer
2096 window on that directory."
2097 :group
'org-link-follow
2100 (defcustom org-confirm-shell-link-function
'yes-or-no-p
2101 "Non-nil means ask for confirmation before executing shell links.
2102 Shell links can be dangerous: just think about a link
2104 [[shell:rm -rf ~/*][Google Search]]
2106 This link would show up in your Org-mode document as \"Google Search\",
2107 but really it would remove your entire home directory.
2108 Therefore we advise against setting this variable to nil.
2109 Just change it to `y-or-n-p' if you want to confirm with a
2110 single keystroke rather than having to type \"yes\"."
2111 :group
'org-link-follow
2113 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
2114 (const :tag
"with y-or-n (faster)" y-or-n-p
)
2115 (const :tag
"no confirmation (dangerous)" nil
)))
2116 (put 'org-confirm-shell-link-function
2117 'safe-local-variable
2118 (lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
2120 (defcustom org-confirm-shell-link-not-regexp
""
2121 "A regexp to skip confirmation for shell links."
2122 :group
'org-link-follow
2126 (defcustom org-confirm-elisp-link-function
'yes-or-no-p
2127 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2128 Elisp links can be dangerous: just think about a link
2130 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2132 This link would show up in your Org-mode document as \"Google Search\",
2133 but really it would remove your entire home directory.
2134 Therefore we advise against setting this variable to nil.
2135 Just change it to `y-or-n-p' if you want to confirm with a
2136 single keystroke rather than having to type \"yes\"."
2137 :group
'org-link-follow
2139 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
2140 (const :tag
"with y-or-n (faster)" y-or-n-p
)
2141 (const :tag
"no confirmation (dangerous)" nil
)))
2142 (put 'org-confirm-shell-link-function
2143 'safe-local-variable
2144 (lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
2146 (defcustom org-confirm-elisp-link-not-regexp
""
2147 "A regexp to skip confirmation for Elisp links."
2148 :group
'org-link-follow
2152 (defconst org-file-apps-defaults-gnu
2156 "Default file applications on a UNIX or GNU/Linux system.
2157 See `org-file-apps'.")
2159 (defconst org-file-apps-defaults-macosx
2162 (system .
"open %s")
2164 ("eps.gz" .
"gv %s")
2166 ("fig" .
"xfig %s"))
2167 "Default file applications on a MacOS X system.
2168 The system \"open\" is known as a default, but we use X11 applications
2169 for some files for which the OS does not have a good default.
2170 See `org-file-apps'.")
2172 (defconst org-file-apps-defaults-windowsnt
2176 (list (if (featurep 'xemacs
)
2177 'mswindows-shell-execute
2181 (list (if (featurep 'xemacs
)
2182 'mswindows-shell-execute
2185 "Default file applications on a Windows NT system.
2186 The system \"open\" is used for most files.
2187 See `org-file-apps'.")
2189 (defcustom org-file-apps
2190 '((auto-mode . emacs
)
2191 ("\\.mm\\'" . default
)
2192 ("\\.x?html?\\'" . default
)
2193 ("\\.pdf\\'" . default
))
2194 "External applications for opening `file:path' items in a document.
2195 Org-mode uses system defaults for different file types, but
2196 you can use this variable to set the application for a given file
2197 extension. The entries in this list are cons cells where the car identifies
2198 files and the cdr the corresponding command. Possible values for the
2200 \"string\" A string as a file identifier can be interpreted in different
2201 ways, depending on its contents:
2203 - Alphanumeric characters only:
2204 Match links with this file extension.
2205 Example: (\"pdf\" . \"evince %s\")
2206 to open PDFs with evince.
2208 - Regular expression: Match links where the
2209 filename matches the regexp. If you want to
2210 use groups here, use shy groups.
2212 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2213 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2214 to open *.html and *.xhtml with firefox.
2216 - Regular expression which contains (non-shy) groups:
2217 Match links where the whole link, including \"::\", and
2218 anything after that, matches the regexp.
2219 In a custom command string, %1, %2, etc. are replaced with
2220 the parts of the link that were matched by the groups.
2221 For backwards compatibility, if a command string is given
2222 that does not use any of the group matches, this case is
2223 handled identically to the second one (i.e. match against
2225 In a custom lisp form, you can access the group matches with
2226 (match-string n link).
2228 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2229 to open [[file:document.pdf::5]] with evince at page 5.
2231 `directory' Matches a directory
2232 `remote' Matches a remote file, accessible through tramp or efs.
2233 Remote files most likely should be visited through Emacs
2234 because external applications cannot handle such paths.
2235 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2236 so all files Emacs knows how to handle. Using this with
2237 command `emacs' will open most files in Emacs. Beware that this
2238 will also open html files inside Emacs, unless you add
2239 (\"html\" . default) to the list as well.
2240 t Default for files not matched by any of the other options.
2241 `system' The system command to open files, like `open' on Windows
2242 and Mac OS X, and mailcap under GNU/Linux. This is the command
2243 that will be selected if you call `C-c C-o' with a double
2244 \\[universal-argument] \\[universal-argument] prefix.
2246 Possible values for the command are:
2247 `emacs' The file will be visited by the current Emacs process.
2248 `default' Use the default application for this file type, which is the
2249 association for t in the list, most likely in the system-specific
2251 This can be used to overrule an unwanted setting in the
2252 system-specific variable.
2253 `system' Use the system command for opening files, like \"open\".
2254 This command is specified by the entry whose car is `system'.
2255 Most likely, the system-specific version of this variable
2256 does define this command, but you can overrule/replace it
2258 string A command to be executed by a shell; %s will be replaced
2259 by the path to the file.
2260 sexp A Lisp form which will be evaluated. The file path will
2261 be available in the Lisp variable `file'.
2262 For more examples, see the system specific constants
2263 `org-file-apps-defaults-macosx'
2264 `org-file-apps-defaults-windowsnt'
2265 `org-file-apps-defaults-gnu'."
2266 :group
'org-link-follow
2268 (cons (choice :value
""
2269 (string :tag
"Extension")
2270 (const :tag
"System command to open files" system
)
2271 (const :tag
"Default for unrecognized files" t
)
2272 (const :tag
"Remote file" remote
)
2273 (const :tag
"Links to a directory" directory
)
2274 (const :tag
"Any files that have Emacs modes"
2277 (const :tag
"Visit with Emacs" emacs
)
2278 (const :tag
"Use default" default
)
2279 (const :tag
"Use the system command" system
)
2280 (string :tag
"Command")
2281 (sexp :tag
"Lisp form")))))
2283 (defcustom org-doi-server-url
"http://dx.doi.org/"
2284 "The URL of the DOI server."
2287 :group
'org-link-follow
)
2289 (defgroup org-refile nil
2290 "Options concerning refiling entries in Org-mode."
2294 (defcustom org-directory
"~/org"
2295 "Directory with org files.
2296 This is just a default location to look for Org files. There is no need
2297 at all to put your files into this directory. It is only used in the
2298 following situations:
2300 1. When a capture template specifies a target file that is not an
2301 absolute path. The path will then be interpreted relative to
2303 2. When a capture note is filed away in an interactive way (when exiting the
2304 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2305 with `org-directory' as the default path."
2310 (defcustom org-default-notes-file
(convert-standard-filename "~/.notes")
2311 "Default target for storing notes.
2312 Used as a fall back file for org-capture.el, for templates that
2313 do not specify a target file."
2317 (const :tag
"Default from remember-data-file" nil
)
2320 (defcustom org-goto-interface
'outline
2321 "The default interface to be used for `org-goto'.
2323 outline The interface shows an outline of the relevant file
2324 and the correct heading is found by moving through
2325 the outline or by searching with incremental search.
2326 outline-path-completion Headlines in the current buffer are offered via
2327 completion. This is the interface also used by
2328 the refile command."
2331 (const :tag
"Outline" outline
)
2332 (const :tag
"Outline-path-completion" outline-path-completion
)))
2334 (defcustom org-goto-max-level
5
2335 "Maximum target level when running `org-goto' with refile interface."
2339 (defcustom org-reverse-note-order nil
2340 "Non-nil means store new notes at the beginning of a file or entry.
2341 When nil, new notes will be filed to the end of a file or entry.
2342 This can also be a list with cons cells of regular expressions that
2343 are matched against file names, and values."
2347 (const :tag
"Reverse always" t
)
2348 (const :tag
"Reverse never" nil
)
2349 (repeat :tag
"By file name regexp"
2350 (cons regexp boolean
))))
2352 (defcustom org-log-refile nil
2353 "Information to record when a task is refiled.
2355 Possible values are:
2357 nil Don't add anything
2358 time Add a time stamp to the task
2359 note Prompt for a note and add it with template `org-log-note-headings'
2361 This option can also be set with on a per-file-basis with
2363 #+STARTUP: nologrefile
2364 #+STARTUP: logrefile
2365 #+STARTUP: lognoterefile
2367 You can have local logging settings for a subtree by setting the LOGGING
2368 property to one or more of these keywords.
2370 When bulk-refiling from the agenda, the value `note' is forbidden and
2371 will temporarily be changed to `time'."
2373 :group
'org-progress
2376 (const :tag
"No logging" nil
)
2377 (const :tag
"Record timestamp" time
)
2378 (const :tag
"Record timestamp with note." note
)))
2380 (defcustom org-refile-targets nil
2381 "Targets for refiling entries with \\[org-refile].
2382 This is a list of cons cells. Each cell contains:
2383 - a specification of the files to be considered, either a list of files,
2384 or a symbol whose function or variable value will be used to retrieve
2385 a file name or a list of file names. If you use `org-agenda-files' for
2386 that, all agenda files will be scanned for targets. Nil means consider
2387 headings in the current buffer.
2388 - A specification of how to find candidate refile targets. This may be
2390 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2391 This tag has to be present in all target headlines, inheritance will
2393 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2395 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2396 headlines that are refiling targets.
2397 - a cons cell (:level . N). Any headline of level N is considered a target.
2398 Note that, when `org-odd-levels-only' is set, level corresponds to
2399 order in hierarchy, not to the number of stars.
2400 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2401 Note that, when `org-odd-levels-only' is set, level corresponds to
2402 order in hierarchy, not to the number of stars.
2404 Each element of this list generates a set of possible targets.
2405 The union of these sets is presented (with completion) to
2406 the user by `org-refile'.
2408 You can set the variable `org-refile-target-verify-function' to a function
2409 to verify each headline found by the simple criteria above.
2411 When this variable is nil, all top-level headlines in the current buffer
2412 are used, equivalent to the value `((nil . (:level . 1))'."
2416 (choice :value org-agenda-files
2417 (const :tag
"All agenda files" org-agenda-files
)
2418 (const :tag
"Current buffer" nil
)
2419 (function) (variable) (file))
2420 (choice :tag
"Identify target headline by"
2421 (cons :tag
"Specific tag" (const :value
:tag
) (string))
2422 (cons :tag
"TODO keyword" (const :value
:todo
) (string))
2423 (cons :tag
"Regular expression" (const :value
:regexp
) (regexp))
2424 (cons :tag
"Level number" (const :value
:level
) (integer))
2425 (cons :tag
"Max Level number" (const :value
:maxlevel
) (integer))))))
2427 (defcustom org-refile-target-verify-function nil
2428 "Function to verify if the headline at point should be a refile target.
2429 The function will be called without arguments, with point at the
2430 beginning of the headline. It should return t and leave point
2431 where it is if the headline is a valid target for refiling.
2433 If the target should not be selected, the function must return nil.
2434 In addition to this, it may move point to a place from where the search
2435 should be continued. For example, the function may decide that the entire
2436 subtree of the current entry should be excluded and move point to the end
2443 (defcustom org-refile-use-cache nil
2444 "Non-nil means cache refile targets to speed up the process.
2445 The cache for a particular file will be updated automatically when
2446 the buffer has been killed, or when any of the marker used for flagging
2447 refile targets no longer points at a live buffer.
2448 If you have added new entries to a buffer that might themselves be targets,
2449 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2450 find that easier, `C-u C-u C-u C-c C-w'."
2455 (defcustom org-refile-use-outline-path nil
2456 "Non-nil means provide refile targets as paths.
2457 So a level 3 headline will be available as level1/level2/level3.
2459 When the value is `file', also include the file name (without directory)
2460 into the path. In this case, you can also stop the completion after
2461 the file name, to get entries inserted as top level in the file.
2463 When `full-file-path', include the full file path."
2466 (const :tag
"Not" nil
)
2467 (const :tag
"Yes" t
)
2468 (const :tag
"Start with file name" file
)
2469 (const :tag
"Start with full file path" full-file-path
)))
2471 (defcustom org-outline-path-complete-in-steps t
2472 "Non-nil means complete the outline path in hierarchical steps.
2473 When Org-mode uses the refile interface to select an outline path
2474 \(see variable `org-refile-use-outline-path'), the completion of
2475 the path can be done is a single go, or if can be done in steps down
2476 the headline hierarchy. Going in steps is probably the best if you
2477 do not use a special completion package like `ido' or `icicles'.
2478 However, when using these packages, going in one step can be very
2479 fast, while still showing the whole path to the entry."
2483 (defcustom org-refile-allow-creating-parent-nodes nil
2484 "Non-nil means allow to create new nodes as refile targets.
2485 New nodes are then created by adding \"/new node name\" to the completion
2486 of an existing node. When the value of this variable is `confirm',
2487 new node creation must be confirmed by the user (recommended).
2488 When nil, the completion must match an existing entry.
2490 Note that, if the new heading is not seen by the criteria
2491 listed in `org-refile-targets', multiple instances of the same
2492 heading would be created by trying again to file under the new
2496 (const :tag
"Never" nil
)
2497 (const :tag
"Always" t
)
2498 (const :tag
"Prompt for confirmation" confirm
)))
2500 (defcustom org-refile-active-region-within-subtree nil
2501 "Non-nil means also refile active region within a subtree.
2503 By default `org-refile' doesn't allow refiling regions if they
2504 don't contain a set of subtrees, but it might be convenient to
2505 do so sometimes: in that case, the first line of the region is
2506 converted to a headline before refiling."
2511 (defgroup org-todo nil
2512 "Options concerning TODO items in Org-mode."
2516 (defgroup org-progress nil
2517 "Options concerning Progress logging in Org-mode."
2521 (defvar org-todo-interpretation-widgets
2522 '((:tag
"Sequence (cycling hits every state)" sequence
)
2523 (:tag
"Type (cycling directly to DONE)" type
))
2524 "The available interpretation symbols for customizing `org-todo-keywords'.
2525 Interested libraries should add to this list.")
2527 (defcustom org-todo-keywords
'((sequence "TODO" "DONE"))
2528 "List of TODO entry keyword sequences and their interpretation.
2529 \\<org-mode-map>This is a list of sequences.
2531 Each sequence starts with a symbol, either `sequence' or `type',
2532 indicating if the keywords should be interpreted as a sequence of
2533 action steps, or as different types of TODO items. The first
2534 keywords are states requiring action - these states will select a headline
2535 for inclusion into the global TODO list Org-mode produces. If one of
2536 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2537 signify that no further action is necessary. If \"|\" is not found,
2538 the last keyword is treated as the only DONE state of the sequence.
2540 The command \\[org-todo] cycles an entry through these states, and one
2541 additional state where no keyword is present. For details about this
2542 cycling, see the manual.
2544 TODO keywords and interpretation can also be set on a per-file basis with
2545 the special #+SEQ_TODO and #+TYP_TODO lines.
2547 Each keyword can optionally specify a character for fast state selection
2548 \(in combination with the variable `org-use-fast-todo-selection')
2549 and specifiers for state change logging, using the same syntax that
2550 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2551 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2552 indicates to record a time stamp each time this state is selected.
2554 Each keyword may also specify if a timestamp or a note should be
2555 recorded when entering or leaving the state, by adding additional
2556 characters in the parenthesis after the keyword. This looks like this:
2557 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2558 record only the time of the state change. With X and Y being either
2559 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2560 Y when leaving the state if and only if the *target* state does not
2561 define X. You may omit any of the fast-selection key or X or /Y,
2562 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2564 For backward compatibility, this variable may also be just a list
2565 of keywords. In this case the interpretation (sequence or type) will be
2566 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2568 :group
'org-keywords
2570 (repeat :tag
"Old syntax, just keywords"
2571 (string :tag
"Keyword"))
2572 (repeat :tag
"New syntax"
2575 :tag
"Interpretation"
2576 ;;Quick and dirty way to see
2577 ;;`org-todo-interpretations'. This takes the
2578 ;;place of item arguments
2586 org-todo-interpretation-widgets
))
2589 (string :tag
"Keyword"))))))
2591 (defvar org-todo-keywords-1 nil
2592 "All TODO and DONE keywords active in a buffer.")
2593 (make-variable-buffer-local 'org-todo-keywords-1
)
2594 (defvar org-todo-keywords-for-agenda nil
)
2595 (defvar org-done-keywords-for-agenda nil
)
2596 (defvar org-todo-keyword-alist-for-agenda nil
)
2597 (defvar org-tag-alist-for-agenda nil
2598 "Alist of all tags from all agenda files.")
2599 (defvar org-tag-groups-alist-for-agenda nil
2600 "Alist of all groups tags from all current agenda files.")
2601 (defvar org-tag-groups-alist nil
)
2602 (make-variable-buffer-local 'org-tag-groups-alist
)
2603 (defvar org-agenda-contributing-files nil
)
2604 (defvar org-not-done-keywords nil
)
2605 (make-variable-buffer-local 'org-not-done-keywords
)
2606 (defvar org-done-keywords nil
)
2607 (make-variable-buffer-local 'org-done-keywords
)
2608 (defvar org-todo-heads nil
)
2609 (make-variable-buffer-local 'org-todo-heads
)
2610 (defvar org-todo-sets nil
)
2611 (make-variable-buffer-local 'org-todo-sets
)
2612 (defvar org-todo-log-states nil
)
2613 (make-variable-buffer-local 'org-todo-log-states
)
2614 (defvar org-todo-kwd-alist nil
)
2615 (make-variable-buffer-local 'org-todo-kwd-alist
)
2616 (defvar org-todo-key-alist nil
)
2617 (make-variable-buffer-local 'org-todo-key-alist
)
2618 (defvar org-todo-key-trigger nil
)
2619 (make-variable-buffer-local 'org-todo-key-trigger
)
2621 (defcustom org-todo-interpretation
'sequence
2622 "Controls how TODO keywords are interpreted.
2623 This variable is in principle obsolete and is only used for
2624 backward compatibility, if the interpretation of todo keywords is
2625 not given already in `org-todo-keywords'. See that variable for
2628 :group
'org-keywords
2629 :type
'(choice (const sequence
)
2632 (defcustom org-use-fast-todo-selection t
2633 "Non-nil means use the fast todo selection scheme with C-c C-t.
2634 This variable describes if and under what circumstances the cycling
2635 mechanism for TODO keywords will be replaced by a single-key, direct
2638 When nil, fast selection is never used.
2640 When the symbol `prefix', it will be used when `org-todo' is called
2641 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2642 `C-u t' in an agenda buffer.
2644 When t, fast selection is used by default. In this case, the prefix
2645 argument forces cycling instead.
2647 In all cases, the special interface is only used if access keys have
2648 actually been assigned by the user, i.e. if keywords in the configuration
2649 are followed by a letter in parenthesis, like TODO(t)."
2652 (const :tag
"Never" nil
)
2653 (const :tag
"By default" t
)
2654 (const :tag
"Only with C-u C-c C-t" prefix
)))
2656 (defcustom org-provide-todo-statistics t
2657 "Non-nil means update todo statistics after insert and toggle.
2658 ALL-HEADLINES means update todo statistics by including headlines
2659 with no TODO keyword as well, counting them as not done.
2660 A list of TODO keywords means the same, but skip keywords that are
2662 When set to a list of two lists, the first list contains keywords
2663 to consider as TODO keywords, the second list contains keywords
2664 to consider as DONE keywords.
2666 When this is set, todo statistics is updated in the parent of the
2667 current entry each time a todo state is changed."
2670 (const :tag
"Yes, only for TODO entries" t
)
2671 (const :tag
"Yes, including all entries" all-headlines
)
2672 (repeat :tag
"Yes, for TODOs in this list"
2673 (string :tag
"TODO keyword"))
2674 (list :tag
"Yes, for TODOs and DONEs in these lists"
2675 (repeat (string :tag
"TODO keyword"))
2676 (repeat (string :tag
"DONE keyword")))
2677 (other :tag
"No TODO statistics" nil
)))
2679 (defcustom org-hierarchical-todo-statistics t
2680 "Non-nil means TODO statistics covers just direct children.
2681 When nil, all entries in the subtree are considered.
2682 This has only an effect if `org-provide-todo-statistics' is set.
2683 To set this to nil for only a single subtree, use a COOKIE_DATA
2684 property and include the word \"recursive\" into the value."
2688 (defcustom org-after-todo-state-change-hook nil
2689 "Hook which is run after the state of a TODO item was changed.
2690 The new state (a string with a TODO keyword, or nil) is available in the
2691 Lisp variable `org-state'."
2695 (defvar org-blocker-hook nil
2696 "Hook for functions that are allowed to block a state change.
2698 Functions in this hook should not modify the buffer.
2699 Each function gets as its single argument a property list,
2700 see `org-trigger-hook' for more information about this list.
2702 If any of the functions in this hook returns nil, the state change
2705 (defvar org-trigger-hook nil
2706 "Hook for functions that are triggered by a state change.
2708 Each function gets as its single argument a property list with at
2709 least the following elements:
2711 (:type type-of-change :position pos-at-entry-start
2712 :from old-state :to new-state)
2714 Depending on the type, more properties may be present.
2716 This mechanism is currently implemented for:
2720 :type todo-state-change
2721 :from previous state (keyword as a string), or nil, or a symbol
2722 'todo' or 'done', to indicate the general type of state.
2723 :to new state, like in :from")
2725 (defcustom org-enforce-todo-dependencies nil
2726 "Non-nil means undone TODO entries will block switching the parent to DONE.
2727 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2728 be blocked if any prior sibling is not yet done.
2729 Finally, if the parent is blocked because of ordered siblings of its own,
2730 the child will also be blocked."
2731 :set
(lambda (var val
)
2734 (add-hook 'org-blocker-hook
2735 'org-block-todo-from-children-or-siblings-or-parent
)
2736 (remove-hook 'org-blocker-hook
2737 'org-block-todo-from-children-or-siblings-or-parent
)))
2741 (defcustom org-enforce-todo-checkbox-dependencies nil
2742 "Non-nil means unchecked boxes will block switching the parent to DONE.
2743 When this is nil, checkboxes have no influence on switching TODO states.
2744 When non-nil, you first need to check off all check boxes before the TODO
2745 entry can be switched to DONE.
2746 This variable needs to be set before org.el is loaded, and you need to
2747 restart Emacs after a change to make the change effective. The only way
2748 to change is while Emacs is running is through the customize interface."
2749 :set
(lambda (var val
)
2752 (add-hook 'org-blocker-hook
2753 'org-block-todo-from-checkboxes
)
2754 (remove-hook 'org-blocker-hook
2755 'org-block-todo-from-checkboxes
)))
2759 (defcustom org-treat-insert-todo-heading-as-state-change nil
2760 "Non-nil means inserting a TODO heading is treated as state change.
2761 So when the command \\[org-insert-todo-heading] is used, state change
2762 logging will apply if appropriate. When nil, the new TODO item will
2763 be inserted directly, and no logging will take place."
2767 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2768 "Non-nil means switching TODO states with S-cursor counts as state change.
2769 This is the default behavior. However, setting this to nil allows a
2770 convenient way to select a TODO state and bypass any logging associated
2775 (defcustom org-todo-state-tags-triggers nil
2776 "Tag changes that should be triggered by TODO state changes.
2777 This is a list. Each entry is
2779 (state-change (tag . flag) .......)
2781 State-change can be a string with a state, and empty string to indicate the
2782 state that has no TODO keyword, or it can be one of the symbols `todo'
2783 or `done', meaning any not-done or done state, respectively."
2787 (cons (choice :tag
"When changing to"
2788 (const :tag
"Not-done state" todo
)
2789 (const :tag
"Done state" done
)
2790 (string :tag
"State"))
2792 (cons :tag
"Tag action"
2794 (choice (const :tag
"Add" t
) (const :tag
"Remove" nil
)))))))
2796 (defcustom org-log-done nil
2797 "Information to record when a task moves to the DONE state.
2799 Possible values are:
2801 nil Don't add anything, just change the keyword
2802 time Add a time stamp to the task
2803 note Prompt for a note and add it with template `org-log-note-headings'
2805 This option can also be set with on a per-file-basis with
2807 #+STARTUP: nologdone
2809 #+STARTUP: lognotedone
2811 You can have local logging settings for a subtree by setting the LOGGING
2812 property to one or more of these keywords."
2814 :group
'org-progress
2816 (const :tag
"No logging" nil
)
2817 (const :tag
"Record CLOSED timestamp" time
)
2818 (const :tag
"Record CLOSED timestamp with note." note
)))
2820 ;; Normalize old uses of org-log-done.
2822 ((eq org-log-done t
) (setq org-log-done
'time
))
2823 ((and (listp org-log-done
) (memq 'done org-log-done
))
2824 (setq org-log-done
'note
)))
2826 (defcustom org-log-reschedule nil
2827 "Information to record when the scheduling date of a tasks is modified.
2829 Possible values are:
2831 nil Don't add anything, just change the date
2832 time Add a time stamp to the task
2833 note Prompt for a note and add it with template `org-log-note-headings'
2835 This option can also be set with on a per-file-basis with
2837 #+STARTUP: nologreschedule
2838 #+STARTUP: logreschedule
2839 #+STARTUP: lognotereschedule"
2841 :group
'org-progress
2843 (const :tag
"No logging" nil
)
2844 (const :tag
"Record timestamp" time
)
2845 (const :tag
"Record timestamp with note." note
)))
2847 (defcustom org-log-redeadline nil
2848 "Information to record when the deadline date of a tasks is modified.
2850 Possible values are:
2852 nil Don't add anything, just change the date
2853 time Add a time stamp to the task
2854 note Prompt for a note and add it with template `org-log-note-headings'
2856 This option can also be set with on a per-file-basis with
2858 #+STARTUP: nologredeadline
2859 #+STARTUP: logredeadline
2860 #+STARTUP: lognoteredeadline
2862 You can have local logging settings for a subtree by setting the LOGGING
2863 property to one or more of these keywords."
2865 :group
'org-progress
2867 (const :tag
"No logging" nil
)
2868 (const :tag
"Record timestamp" time
)
2869 (const :tag
"Record timestamp with note." note
)))
2871 (defcustom org-log-note-clock-out nil
2872 "Non-nil means record a note when clocking out of an item.
2873 This can also be configured on a per-file basis by adding one of
2874 the following lines anywhere in the buffer:
2876 #+STARTUP: lognoteclock-out
2877 #+STARTUP: nolognoteclock-out"
2879 :group
'org-progress
2882 (defcustom org-log-done-with-time t
2883 "Non-nil means the CLOSED time stamp will contain date and time.
2884 When nil, only the date will be recorded."
2885 :group
'org-progress
2888 (defcustom org-log-note-headings
2889 '((done .
"CLOSING NOTE %t")
2890 (state .
"State %-12s from %-12S %t")
2891 (note .
"Note taken on %t")
2892 (reschedule .
"Rescheduled from %S on %t")
2893 (delschedule .
"Not scheduled, was %S on %t")
2894 (redeadline .
"New deadline from %S on %t")
2895 (deldeadline .
"Removed deadline, was %S on %t")
2896 (refile .
"Refiled on %t")
2898 "Headings for notes added to entries.
2899 The value is an alist, with the car being a symbol indicating the note
2900 context, and the cdr is the heading to be used. The heading may also be the
2902 %t in the heading will be replaced by a time stamp.
2903 %T will be an active time stamp instead the default inactive one
2904 %d will be replaced by a short-format time stamp.
2905 %D will be replaced by an active short-format time stamp.
2906 %s will be replaced by the new TODO state, in double quotes.
2907 %S will be replaced by the old TODO state, in double quotes.
2908 %u will be replaced by the user name.
2909 %U will be replaced by the full user name.
2911 In fact, it is not a good idea to change the `state' entry, because
2912 agenda log mode depends on the format of these entries."
2914 :group
'org-progress
2915 :type
'(list :greedy t
2916 (cons (const :tag
"Heading when closing an item" done
) string
)
2918 "Heading when changing todo state (todo sequence only)"
2920 (cons (const :tag
"Heading when just taking a note" note
) string
)
2921 (cons (const :tag
"Heading when rescheduling" reschedule
) string
)
2922 (cons (const :tag
"Heading when an item is no longer scheduled" delschedule
) string
)
2923 (cons (const :tag
"Heading when changing deadline" redeadline
) string
)
2924 (cons (const :tag
"Heading when deleting a deadline" deldeadline
) string
)
2925 (cons (const :tag
"Heading when refiling" refile
) string
)
2926 (cons (const :tag
"Heading when clocking out" clock-out
) string
)))
2928 (unless (assq 'note org-log-note-headings
)
2929 (push '(note .
"%t") org-log-note-headings
))
2931 (defcustom org-log-into-drawer nil
2932 "Non-nil means insert state change notes and time stamps into a drawer.
2933 When nil, state changes notes will be inserted after the headline and
2934 any scheduling and clock lines, but not inside a drawer.
2936 The value of this variable should be the name of the drawer to use.
2937 LOGBOOK is proposed as the default drawer for this purpose, you can
2938 also set this to a string to define the drawer of your choice.
2940 A value of t is also allowed, representing \"LOGBOOK\".
2942 A value of t or nil can also be set with on a per-file-basis with
2944 #+STARTUP: logdrawer
2945 #+STARTUP: nologdrawer
2947 If this variable is set, `org-log-state-notes-insert-after-drawers'
2950 You can set the property LOG_INTO_DRAWER to overrule this setting for
2953 :group
'org-progress
2955 (const :tag
"Not into a drawer" nil
)
2956 (const :tag
"LOGBOOK" t
)
2957 (string :tag
"Other")))
2959 (org-defvaralias 'org-log-state-notes-into-drawer
'org-log-into-drawer
)
2961 (defun org-log-into-drawer ()
2962 "Return the value of `org-log-into-drawer', but let properties overrule.
2963 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2964 used instead of the default value."
2965 (let ((p (org-entry-get nil
"LOG_INTO_DRAWER" 'inherit t
)))
2967 ((not p
) org-log-into-drawer
)
2968 ((equal p
"nil") nil
)
2969 ((equal p
"t") "LOGBOOK")
2972 (defcustom org-log-state-notes-insert-after-drawers nil
2973 "Non-nil means insert state change notes after any drawers in entry.
2974 Only the drawers that *immediately* follow the headline and the
2975 deadline/scheduled line are skipped.
2976 When nil, insert notes right after the heading and perhaps the line
2977 with deadline/scheduling if present.
2979 This variable will have no effect if `org-log-into-drawer' is
2982 :group
'org-progress
2985 (defcustom org-log-states-order-reversed t
2986 "Non-nil means the latest state note will be directly after heading.
2987 When nil, the state change notes will be ordered according to time.
2989 This option can also be set with on a per-file-basis with
2991 #+STARTUP: logstatesreversed
2992 #+STARTUP: nologstatesreversed"
2994 :group
'org-progress
2997 (defcustom org-todo-repeat-to-state nil
2998 "The TODO state to which a repeater should return the repeating task.
2999 By default this is the first task in a TODO sequence, or the previous state
3000 in a TODO_TYP set. But you can specify another task here.
3001 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3004 :type
'(choice (const :tag
"Head of sequence" nil
)
3005 (string :tag
"Specific state")))
3007 (defcustom org-log-repeat
'time
3008 "Non-nil means record moving through the DONE state when triggering repeat.
3009 An auto-repeating task is immediately switched back to TODO when
3010 marked DONE. If you are not logging state changes (by adding \"@\"
3011 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3012 record a closing note, there will be no record of the task moving
3013 through DONE. This variable forces taking a note anyway.
3015 nil Don't force a record
3016 time Record a time stamp
3017 note Prompt for a note and add it with template `org-log-note-headings'
3019 This option can also be set with on a per-file-basis with
3021 #+STARTUP: nologrepeat
3022 #+STARTUP: logrepeat
3023 #+STARTUP: lognoterepeat
3025 You can have local logging settings for a subtree by setting the LOGGING
3026 property to one or more of these keywords."
3028 :group
'org-progress
3030 (const :tag
"Don't force a record" nil
)
3031 (const :tag
"Force recording the DONE state" time
)
3032 (const :tag
"Force recording a note with the DONE state" note
)))
3035 (defgroup org-priorities nil
3036 "Priorities in Org-mode."
3037 :tag
"Org Priorities"
3040 (defcustom org-enable-priority-commands t
3041 "Non-nil means priority commands are active.
3042 When nil, these commands will be disabled, so that you never accidentally
3044 :group
'org-priorities
3047 (defcustom org-highest-priority ?A
3048 "The highest priority of TODO items. A character like ?A, ?B etc.
3049 Must have a smaller ASCII number than `org-lowest-priority'."
3050 :group
'org-priorities
3053 (defcustom org-lowest-priority ?C
3054 "The lowest priority of TODO items. A character like ?A, ?B etc.
3055 Must have a larger ASCII number than `org-highest-priority'."
3056 :group
'org-priorities
3059 (defcustom org-default-priority ?B
3060 "The default priority of TODO items.
3061 This is the priority an item gets if no explicit priority is given.
3062 When starting to cycle on an empty priority the first step in the cycle
3063 depends on `org-priority-start-cycle-with-default'. The resulting first
3064 step priority must not exceed the range from `org-highest-priority' to
3065 `org-lowest-priority' which means that `org-default-priority' has to be
3066 in this range exclusive or inclusive the range boundaries. Else the
3067 first step refuses to set the default and the second will fall back
3068 to (depending on the command used) the highest or lowest priority."
3069 :group
'org-priorities
3072 (defcustom org-priority-start-cycle-with-default t
3073 "Non-nil means start with default priority when starting to cycle.
3074 When this is nil, the first step in the cycle will be (depending on the
3075 command used) one higher or lower than the default priority.
3076 See also `org-default-priority'."
3077 :group
'org-priorities
3080 (defcustom org-get-priority-function nil
3081 "Function to extract the priority from a string.
3082 The string is normally the headline. If this is nil Org computes the
3083 priority from the priority cookie like [#A] in the headline. It returns
3084 an integer, increasing by 1000 for each priority level.
3085 The user can set a different function here, which should take a string
3086 as an argument and return the numeric priority."
3087 :group
'org-priorities
3093 (defgroup org-time nil
3094 "Options concerning time stamps and deadlines in Org-mode."
3098 (defcustom org-insert-labeled-timestamps-at-point nil
3099 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3100 When nil, these labeled time stamps are forces into the second line of an
3101 entry, just after the headline. When scheduling from the global TODO list,
3102 the time stamp will always be forced into the second line."
3106 (defcustom org-time-stamp-rounding-minutes
'(0 5)
3107 "Number of minutes to round time stamps to.
3108 These are two values, the first applies when first creating a time stamp.
3109 The second applies when changing it with the commands `S-up' and `S-down'.
3110 When changing the time stamp, this means that it will change in steps
3111 of N minutes, as given by the second value.
3113 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3114 numbers should be factors of 60, so for example 5, 10, 15.
3116 When this is larger than 1, you can still force an exact time stamp by using
3117 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3118 and by using a prefix arg to `S-up/down' to specify the exact number
3119 of minutes to shift."
3121 :get
(lambda (var) ; Make sure both elements are there
3122 (if (integerp (default-value var
))
3123 (list (default-value var
) 5)
3124 (default-value var
)))
3126 (integer :tag
"when inserting times")
3127 (integer :tag
"when modifying times")))
3129 ;; Normalize old customizations of this variable.
3130 (when (integerp org-time-stamp-rounding-minutes
)
3131 (setq org-time-stamp-rounding-minutes
3132 (list org-time-stamp-rounding-minutes
3133 org-time-stamp-rounding-minutes
)))
3135 (defcustom org-display-custom-times nil
3136 "Non-nil means overlay custom formats over all time stamps.
3137 The formats are defined through the variable `org-time-stamp-custom-formats'.
3138 To turn this on on a per-file basis, insert anywhere in the file:
3139 #+STARTUP: customtime"
3143 (make-variable-buffer-local 'org-display-custom-times
)
3145 (defcustom org-time-stamp-custom-formats
3146 '("<%m/%d/%y %a>" .
"<%m/%d/%y %a %H:%M>") ; american
3147 "Custom formats for time stamps. See `format-time-string' for the syntax.
3148 These are overlaid over the default ISO format if the variable
3149 `org-display-custom-times' is set. Time like %H:%M should be at the
3150 end of the second format. The custom formats are also honored by export
3151 commands, if custom time display is turned on at the time of export."
3155 (defun org-time-stamp-format (&optional long inactive
)
3156 "Get the right format for a time string."
3157 (let ((f (if long
(cdr org-time-stamp-formats
)
3158 (car org-time-stamp-formats
))))
3160 (concat "[" (substring f
1 -
1) "]")
3163 (defcustom org-time-clocksum-format
3164 '(:days
"%dd " :hours
"%d" :require-hours t
:minutes
":%02d" :require-minutes t
)
3165 "The format string used when creating CLOCKSUM lines.
3166 This is also used when Org mode generates a time duration.
3168 The value can be a single format string containing two
3169 %-sequences, which will be filled with the number of hours and
3170 minutes in that order.
3172 Alternatively, the value can be a plist associating any of the
3173 keys :years, :months, :weeks, :days, :hours or :minutes with
3174 format strings. The time duration is formatted using only the
3175 time components that are needed and concatenating the results.
3176 If a time unit in absent, it falls back to the next smallest
3179 The keys :require-years, :require-months, :require-days,
3180 :require-weeks, :require-hours, :require-minutes are also
3181 meaningful. A non-nil value for these keys indicates that the
3182 corresponding time component should always be included, even if
3188 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3191 means durations longer than a day will be expressed in days,
3192 hours and minutes, and durations less than a day will always be
3193 expressed in hours and minutes (even for durations less than an
3198 \(:days \"%dd\" :minutes \"%dm\")
3200 means durations longer than a day will be expressed in days and
3201 minutes, and durations less than a day will be expressed entirely
3202 in minutes (even for durations longer than an hour)."
3206 :package-version
'(Org .
"8.0")
3207 :type
'(choice (string :tag
"Format string")
3209 (group :inline t
(const :tag
"Years" :years
)
3210 (string :tag
"Format string"))
3212 (const :tag
"Always show years" :require-years
)
3214 (group :inline t
(const :tag
"Months" :months
)
3215 (string :tag
"Format string"))
3217 (const :tag
"Always show months" :require-months
)
3219 (group :inline t
(const :tag
"Weeks" :weeks
)
3220 (string :tag
"Format string"))
3222 (const :tag
"Always show weeks" :require-weeks
)
3224 (group :inline t
(const :tag
"Days" :days
)
3225 (string :tag
"Format string"))
3227 (const :tag
"Always show days" :require-days
)
3229 (group :inline t
(const :tag
"Hours" :hours
)
3230 (string :tag
"Format string"))
3232 (const :tag
"Always show hours" :require-hours
)
3234 (group :inline t
(const :tag
"Minutes" :minutes
)
3235 (string :tag
"Format string"))
3237 (const :tag
"Always show minutes" :require-minutes
)
3240 (defcustom org-time-clocksum-use-fractional nil
3241 "When non-nil, \\[org-clock-display] uses fractional times.
3242 See `org-time-clocksum-format' for more on time clock formats."
3248 (defcustom org-time-clocksum-use-effort-durations nil
3249 "When non-nil, \\[org-clock-display] uses effort durations.
3250 E.g. by default, one day is considered to be a 8 hours effort,
3251 so a task that has been clocked for 16 hours will be displayed
3252 as during 2 days in the clock display or in the clocktable.
3254 See `org-effort-durations' on how to set effort durations
3255 and `org-time-clocksum-format' for more on time clock formats."
3259 :package-version
'(Org .
"8.0")
3262 (defcustom org-time-clocksum-fractional-format
"%.2f"
3263 "The format string used when creating CLOCKSUM lines,
3264 or when Org mode generates a time duration, if
3265 `org-time-clocksum-use-fractional' is enabled.
3267 The value can be a single format string containing one
3268 %-sequence, which will be filled with the number of hours as
3271 Alternatively, the value can be a plist associating any of the
3272 keys :years, :months, :weeks, :days, :hours or :minutes with
3273 a format string. The time duration is formatted using the
3274 largest time unit which gives a non-zero integer part. If all
3275 specified formats have zero integer part, the smallest time unit
3278 :type
'(choice (string :tag
"Format string")
3279 (set (group :inline t
(const :tag
"Years" :years
)
3280 (string :tag
"Format string"))
3281 (group :inline t
(const :tag
"Months" :months
)
3282 (string :tag
"Format string"))
3283 (group :inline t
(const :tag
"Weeks" :weeks
)
3284 (string :tag
"Format string"))
3285 (group :inline t
(const :tag
"Days" :days
)
3286 (string :tag
"Format string"))
3287 (group :inline t
(const :tag
"Hours" :hours
)
3288 (string :tag
"Format string"))
3289 (group :inline t
(const :tag
"Minutes" :minutes
)
3290 (string :tag
"Format string")))))
3292 (defcustom org-deadline-warning-days
14
3293 "Number of days before expiration during which a deadline becomes active.
3294 This variable governs the display in sparse trees and in the agenda.
3295 When 0 or negative, it means use this number (the absolute value of it)
3296 even if a deadline has a different individual lead time specified.
3298 Custom commands can set this variable in the options section."
3300 :group
'org-agenda-daily
/weekly
3303 (defcustom org-scheduled-delay-days
0
3304 "Number of days before a scheduled item becomes active.
3305 This variable governs the display in sparse trees and in the agenda.
3306 The default value (i.e. 0) means: don't delay scheduled item.
3307 When negative, it means use this number (the absolute value of it)
3308 even if a scheduled item has a different individual delay time
3311 Custom commands can set this variable in the options section."
3313 :group
'org-agenda-daily
/weekly
3315 :package-version
'(Org .
"8.0")
3318 (defcustom org-read-date-prefer-future t
3319 "Non-nil means assume future for incomplete date input from user.
3320 This affects the following situations:
3321 1. The user gives a month but not a year.
3322 For example, if it is April and you enter \"feb 2\", this will be read
3323 as Feb 2, *next* year. \"May 5\", however, will be this year.
3324 2. The user gives a day, but no month.
3325 For example, if today is the 15th, and you enter \"3\", Org-mode will
3326 read this as the third of *next* month. However, if you enter \"17\",
3327 it will be considered as *this* month.
3329 If you set this variable to the symbol `time', then also the following
3332 3. If the user gives a time.
3333 If the time is before now, it will be interpreted as tomorrow.
3335 Currently none of this works for ISO week specifications.
3337 When this option is nil, the current day, month and year will always be
3340 See also `org-agenda-jump-prefer-future'."
3343 (const :tag
"Never" nil
)
3344 (const :tag
"Check month and day" t
)
3345 (const :tag
"Check month, day, and time" time
)))
3347 (defcustom org-agenda-jump-prefer-future
'org-read-date-prefer-future
3348 "Should the agenda jump command prefer the future for incomplete dates?
3349 The default is to do the same as configured in `org-read-date-prefer-future'.
3350 But you can also set a deviating value here.
3351 This may t or nil, or the symbol `org-read-date-prefer-future'."
3356 (const :tag
"Use org-read-date-prefer-future"
3357 org-read-date-prefer-future
)
3358 (const :tag
"Never" nil
)
3359 (const :tag
"Always" t
)))
3361 (defcustom org-read-date-force-compatible-dates t
3362 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3364 Depending on the system Emacs is running on, certain dates cannot
3365 be represented with the type used internally to represent time.
3366 Dates between 1970-1-1 and 2038-1-1 can always be represented
3367 correctly. Some systems allow for earlier dates, some for later,
3368 some for both. One way to find out it to insert any date into an
3369 Org buffer, putting the cursor on the year and hitting S-up and
3370 S-down to test the range.
3372 When this variable is set to t, the date/time prompt will not let
3373 you specify dates outside the 1970-2037 range, so it is certain that
3374 these dates will work in whatever version of Emacs you are
3375 running, and also that you can move a file from one Emacs implementation
3376 to another. WHenever Org is forcing the year for you, it will display
3379 When this variable is nil, Org will check if the date is
3380 representable in the specific Emacs implementation you are using.
3381 If not, it will force a year, usually the current year, and beep
3382 to remind you. Currently this setting is not recommended because
3383 the likelihood that you will open your Org files in an Emacs that
3384 has limited date range is not negligible.
3386 A workaround for this problem is to use diary sexp dates for time
3387 stamps outside of this range."
3392 (defcustom org-read-date-display-live t
3393 "Non-nil means display current interpretation of date prompt live.
3394 This display will be in an overlay, in the minibuffer."
3398 (defcustom org-read-date-popup-calendar t
3399 "Non-nil means pop up a calendar when prompting for a date.
3400 In the calendar, the date can be selected with mouse-1. However, the
3401 minibuffer will also be active, and you can simply enter the date as well.
3402 When nil, only the minibuffer will be available."
3405 (org-defvaralias 'org-popup-calendar-for-date-prompt
3406 'org-read-date-popup-calendar
)
3408 (make-obsolete-variable
3409 'org-read-date-minibuffer-setup-hook
3410 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3411 (defcustom org-read-date-minibuffer-setup-hook nil
3412 "Hook to be used to set up keys for the date/time interface.
3413 Add key definitions to `minibuffer-local-map', which will be a
3416 WARNING: This option is obsolete, you should use
3417 `org-read-date-minibuffer-local-map' to set up keys."
3421 (defcustom org-extend-today-until
0
3422 "The hour when your day really ends. Must be an integer.
3423 This has influence for the following applications:
3424 - When switching the agenda to \"today\". It it is still earlier than
3425 the time given here, the day recognized as TODAY is actually yesterday.
3426 - When a date is read from the user and it is still before the time given
3427 here, the current date and time will be assumed to be yesterday, 23:59.
3428 Also, timestamps inserted in capture templates follow this rule.
3430 IMPORTANT: This is a feature whose implementation is and likely will
3431 remain incomplete. Really, it is only here because past midnight seems to
3432 be the favorite working time of John Wiegley :-)"
3436 (defcustom org-use-effective-time nil
3437 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3438 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3439 \"effective time\" of any timestamps between midnight and 8am will be
3440 23:59 of the previous day."
3445 (defcustom org-use-last-clock-out-time-as-effective-time nil
3446 "When non-nil, use the last clock out time for `org-todo'.
3447 Note that this option has precedence over the combined use of
3448 `org-use-effective-time' and `org-extend-today-until'."
3451 :package-version
'(Org .
"8.0")
3454 (defcustom org-edit-timestamp-down-means-later nil
3455 "Non-nil means S-down will increase the time in a time stamp.
3456 When nil, S-up will increase."
3460 (defcustom org-calendar-follow-timestamp-change t
3461 "Non-nil means make the calendar window follow timestamp changes.
3462 When a timestamp is modified and the calendar window is visible, it will be
3463 moved to the new date."
3467 (defgroup org-tags nil
3468 "Options concerning tags in Org-mode."
3472 (defcustom org-tag-alist nil
3473 "List of tags allowed in Org-mode files.
3474 When this list is nil, Org-mode will base TAG input on what is already in the
3476 The value of this variable is an alist, the car of each entry must be a
3477 keyword as a string, the cdr may be a character that is used to select
3478 that tag through the fast-tag-selection interface.
3479 See the manual for details."
3483 (cons (string :tag
"Tag name")
3484 (character :tag
"Access char"))
3485 (list :tag
"Start radio group"
3487 (option (string :tag
"Group description")))
3488 (list :tag
"Group tags delimiter"
3490 (list :tag
"End radio group"
3492 (option (string :tag
"Group description")))
3493 (const :tag
"New line" (:newline
)))))
3495 (defcustom org-tag-persistent-alist nil
3496 "List of tags that will always appear in all Org-mode files.
3497 This is in addition to any in buffer settings or customizations
3499 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3500 The value of this variable is an alist, the car of each entry must be a
3501 keyword as a string, the cdr may be a character that is used to select
3502 that tag through the fast-tag-selection interface.
3503 See the manual for details.
3504 To disable these tags on a per-file basis, insert anywhere in the file:
3509 (cons (string :tag
"Tag name")
3510 (character :tag
"Access char"))
3511 (const :tag
"Start radio group" (:startgroup
))
3512 (const :tag
"Group tags delimiter" (:grouptags
))
3513 (const :tag
"End radio group" (:endgroup
))
3514 (const :tag
"New line" (:newline
)))))
3516 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3517 "If non-nil, always offer completion for all tags of all agenda files.
3518 Instead of customizing this variable directly, you might want to
3519 set it locally for capture buffers, because there no list of
3520 tags in that file can be created dynamically (there are none).
3522 (add-hook 'org-capture-mode-hook
3524 (set (make-local-variable
3525 'org-complete-tags-always-offer-all-agenda-tags)
3531 (defvar org-file-tags nil
3532 "List of tags that can be inherited by all entries in the file.
3533 The tags will be inherited if the variable `org-use-tag-inheritance'
3534 says they should be.
3535 This variable is populated from #+FILETAGS lines.")
3537 (defcustom org-use-fast-tag-selection
'auto
3538 "Non-nil means use fast tag selection scheme.
3539 This is a special interface to select and deselect tags with single keys.
3540 When nil, fast selection is never used.
3541 When the symbol `auto', fast selection is used if and only if selection
3542 characters for tags have been configured, either through the variable
3543 `org-tag-alist' or through a #+TAGS line in the buffer.
3544 When t, fast selection is always used and selection keys are assigned
3545 automatically if necessary."
3548 (const :tag
"Always" t
)
3549 (const :tag
"Never" nil
)
3550 (const :tag
"When selection characters are configured" auto
)))
3552 (defcustom org-fast-tag-selection-single-key nil
3553 "Non-nil means fast tag selection exits after first change.
3554 When nil, you have to press RET to exit it.
3555 During fast tag selection, you can toggle this flag with `C-c'.
3556 This variable can also have the value `expert'. In this case, the window
3557 displaying the tags menu is not even shown, until you press C-c again."
3560 (const :tag
"No" nil
)
3561 (const :tag
"Yes" t
)
3562 (const :tag
"Expert" expert
)))
3564 (defvar org-fast-tag-selection-include-todo nil
3565 "Non-nil means fast tags selection interface will also offer TODO states.
3566 This is an undocumented feature, you should not rely on it.")
3568 (defcustom org-tags-column
(if (featurep 'xemacs
) -
76 -
77)
3569 "The column to which tags should be indented in a headline.
3570 If this number is positive, it specifies the column. If it is negative,
3571 it means that the tags should be flushright to that column. For example,
3572 -80 works well for a normal 80 character screen.
3573 When 0, place tags directly after headline text, with only one space in
3578 (defcustom org-auto-align-tags t
3579 "Non-nil keeps tags aligned when modifying headlines.
3580 Some operations (i.e. demoting) change the length of a headline and
3581 therefore shift the tags around. With this option turned on, after
3582 each such operation the tags are again aligned to `org-tags-column'."
3586 (defcustom org-use-tag-inheritance t
3587 "Non-nil means tags in levels apply also for sublevels.
3588 When nil, only the tags directly given in a specific line apply there.
3589 This may also be a list of tags that should be inherited, or a regexp that
3590 matches tags that should be inherited. Additional control is possible
3591 with the variable `org-tags-exclude-from-inheritance' which gives an
3592 explicit list of tags to be excluded from inheritance, even if the value of
3593 `org-use-tag-inheritance' would select it for inheritance.
3595 If this option is t, a match early-on in a tree can lead to a large
3596 number of matches in the subtree when constructing the agenda or creating
3597 a sparse tree. If you only want to see the first match in a tree during
3598 a search, check out the variable `org-tags-match-list-sublevels'."
3601 (const :tag
"Not" nil
)
3602 (const :tag
"Always" t
)
3603 (repeat :tag
"Specific tags" (string :tag
"Tag"))
3604 (regexp :tag
"Tags matched by regexp")))
3606 (defcustom org-tags-exclude-from-inheritance nil
3607 "List of tags that should never be inherited.
3608 This is a way to exclude a few tags from inheritance. For way to do
3609 the opposite, to actively allow inheritance for selected tags,
3610 see the variable `org-use-tag-inheritance'."
3612 :type
'(repeat (string :tag
"Tag")))
3614 (defun org-tag-inherit-p (tag)
3615 "Check if TAG is one that should be inherited."
3617 ((member tag org-tags-exclude-from-inheritance
) nil
)
3618 ((eq org-use-tag-inheritance t
) t
)
3619 ((not org-use-tag-inheritance
) nil
)
3620 ((stringp org-use-tag-inheritance
)
3621 (string-match org-use-tag-inheritance tag
))
3622 ((listp org-use-tag-inheritance
)
3623 (member tag org-use-tag-inheritance
))
3624 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3626 (defcustom org-tags-match-list-sublevels t
3627 "Non-nil means list also sublevels of headlines matching a search.
3628 This variable applies to tags/property searches, and also to stuck
3629 projects because this search is based on a tags match as well.
3631 When set to the symbol `indented', sublevels are indented with
3634 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3635 the sublevels of a headline matching a tag search often also match
3636 the same search. Listing all of them can create very long lists.
3637 Setting this variable to nil causes subtrees of a match to be skipped.
3639 This variable is semi-obsolete and probably should always be true. It
3640 is better to limit inheritance to certain tags using the variables
3641 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3644 (const :tag
"No, don't list them" nil
)
3645 (const :tag
"Yes, do list them" t
)
3646 (const :tag
"List them, indented with leading dots" indented
)))
3648 (defcustom org-tags-sort-function nil
3649 "When set, tags are sorted using this function as a comparator."
3652 (const :tag
"No sorting" nil
)
3653 (const :tag
"Alphabetical" string
<)
3654 (const :tag
"Reverse alphabetical" string
>)
3655 (function :tag
"Custom function" nil
)))
3657 (defvar org-tags-history nil
3658 "History of minibuffer reads for tags.")
3659 (defvar org-last-tags-completion-table nil
3660 "The last used completion table for tags.")
3661 (defvar org-after-tags-change-hook nil
3662 "Hook that is run after the tags in a line have changed.")
3664 (defgroup org-properties nil
3665 "Options concerning properties in Org-mode."
3666 :tag
"Org Properties"
3669 (defcustom org-property-format
"%-10s %s"
3670 "How property key/value pairs should be formatted by `indent-line'.
3671 When `indent-line' hits a property definition, it will format the line
3672 according to this format, mainly to make sure that the values are
3673 lined-up with respect to each other."
3674 :group
'org-properties
3677 (defcustom org-properties-postprocess-alist nil
3678 "Alist of properties and functions to adjust inserted values.
3679 Elements of this alist must be of the form
3681 ([string] [function])
3683 where [string] must be a property name and [function] must be a
3684 lambda expression: this lambda expression must take one argument,
3685 the value to adjust, and return the new value as a string.
3687 For example, this element will allow the property \"Remaining\"
3688 to be updated wrt the relation between the \"Effort\" property
3689 and the clock summary:
3691 ((\"Remaining\" (lambda(value)
3692 (let ((clocksum (org-clock-sum-current-item))
3693 (effort (org-duration-string-to-minutes
3694 (org-entry-get (point) \"Effort\"))))
3695 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3696 :group
'org-properties
3698 :type
'(alist :key-type
(string :tag
"Property")
3699 :value-type
(function :tag
"Function")))
3701 (defcustom org-use-property-inheritance nil
3702 "Non-nil means properties apply also for sublevels.
3704 This setting is chiefly used during property searches. Turning it on can
3705 cause significant overhead when doing a search, which is why it is not
3708 When nil, only the properties directly given in the current entry count.
3709 When t, every property is inherited. The value may also be a list of
3710 properties that should have inheritance, or a regular expression matching
3711 properties that should be inherited.
3713 However, note that some special properties use inheritance under special
3714 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3715 and the properties ending in \"_ALL\" when they are used as descriptor
3716 for valid values of a property.
3718 Note for programmers:
3719 When querying an entry with `org-entry-get', you can control if inheritance
3720 should be used. By default, `org-entry-get' looks only at the local
3721 properties. You can request inheritance by setting the inherit argument
3722 to t (to force inheritance) or to `selective' (to respect the setting
3724 :group
'org-properties
3726 (const :tag
"Not" nil
)
3727 (const :tag
"Always" t
)
3728 (repeat :tag
"Specific properties" (string :tag
"Property"))
3729 (regexp :tag
"Properties matched by regexp")))
3731 (defun org-property-inherit-p (property)
3732 "Check if PROPERTY is one that should be inherited."
3734 ((eq org-use-property-inheritance t
) t
)
3735 ((not org-use-property-inheritance
) nil
)
3736 ((stringp org-use-property-inheritance
)
3737 (string-match org-use-property-inheritance property
))
3738 ((listp org-use-property-inheritance
)
3739 (member property org-use-property-inheritance
))
3740 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3742 (defcustom org-columns-default-format
"%25ITEM %TODO %3PRIORITY %TAGS"
3743 "The default column format, if no other format has been defined.
3744 This variable can be set on the per-file basis by inserting a line
3746 #+COLUMNS: %25ITEM ....."
3747 :group
'org-properties
3750 (defcustom org-columns-ellipses
".."
3751 "The ellipses to be used when a field in column view is truncated.
3752 When this is the empty string, as many characters as possible are shown,
3753 but then there will be no visual indication that the field has been truncated.
3754 When this is a string of length N, the last N characters of a truncated
3755 field are replaced by this string. If the column is narrower than the
3756 ellipses string, only part of the ellipses string will be shown."
3757 :group
'org-properties
3760 (defcustom org-columns-modify-value-for-display-function nil
3761 "Function that modifies values for display in column view.
3762 For example, it can be used to cut out a certain part from a time stamp.
3763 The function must take 2 arguments:
3765 column-title The title of the column (*not* the property name)
3766 value The value that should be modified.
3768 The function should return the value that should be displayed,
3769 or nil if the normal value should be used."
3770 :group
'org-properties
3771 :type
'(choice (const nil
) (function)))
3773 (defconst org-global-properties-fixed
3774 '(("VISIBILITY_ALL" .
"folded children content all")
3775 ("CLOCK_MODELINE_TOTAL_ALL" .
"current today repeat all auto"))
3776 "List of property/value pairs that can be inherited by any entry.
3778 These are fixed values, for the preset properties. The user variable
3779 that can be used to add to this list is `org-global-properties'.
3781 The entries in this list are cons cells where the car is a property
3782 name and cdr is a string with the value. If the value represents
3783 multiple items like an \"_ALL\" property, separate the items by
3786 (defcustom org-global-properties nil
3787 "List of property/value pairs that can be inherited by any entry.
3789 This list will be combined with the constant `org-global-properties-fixed'.
3791 The entries in this list are cons cells where the car is a property
3792 name and cdr is a string with the value.
3794 You can set buffer-local values for the same purpose in the variable
3795 `org-file-properties' this by adding lines like
3797 #+PROPERTY: NAME VALUE"
3798 :group
'org-properties
3800 (cons (string :tag
"Property")
3801 (string :tag
"Value"))))
3803 (defvar org-file-properties nil
3804 "List of property/value pairs that can be inherited by any entry.
3805 Valid for the current buffer.
3806 This variable is populated from #+PROPERTY lines.")
3807 (make-variable-buffer-local 'org-file-properties
)
3809 (defgroup org-agenda nil
3810 "Options concerning agenda views in Org-mode."
3814 (defvar org-category nil
3815 "Variable used by org files to set a category for agenda display.
3816 Such files should use a file variable to set it, for example
3818 # -*- mode: org; org-category: \"ELisp\"
3820 or contain a special line
3824 If the file does not specify a category, then file's base name
3826 (make-variable-buffer-local 'org-category
)
3827 (put 'org-category
'safe-local-variable
(lambda (x) (or (symbolp x
) (stringp x
))))
3829 (defcustom org-agenda-files nil
3830 "The files to be used for agenda display.
3831 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3832 \\[org-remove-file]. You can also use customize to edit the list.
3834 If an entry is a directory, all files in that directory that are matched by
3835 `org-agenda-file-regexp' will be part of the file list.
3837 If the value of the variable is not a list but a single file name, then
3838 the list of agenda files is actually stored and maintained in that file, one
3839 agenda file per line. In this file paths can be given relative to
3840 `org-directory'. Tilde expansion and environment variable substitution
3844 (repeat :tag
"List of files and directories" file
)
3845 (file :tag
"Store list in a file\n" :value
"~/.agenda_files")))
3847 (defcustom org-agenda-file-regexp
"\\`[^.].*\\.org\\'"
3848 "Regular expression to match files for `org-agenda-files'.
3849 If any element in the list in that variable contains a directory instead
3850 of a normal file, all files in that directory that are matched by this
3851 regular expression will be included."
3855 (defcustom org-agenda-text-search-extra-files nil
3856 "List of extra files to be searched by text search commands.
3857 These files will be searched in addition to the agenda files by the
3858 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3859 Note that these files will only be searched for text search commands,
3860 not for the other agenda views like todo lists, tag searches or the weekly
3861 agenda. This variable is intended to list notes and possibly archive files
3862 that should also be searched by these two commands.
3863 In fact, if the first element in the list is the symbol `agenda-archives',
3864 then all archive files of all agenda files will be added to the search
3867 :type
'(set :greedy t
3868 (const :tag
"Agenda Archives" agenda-archives
)
3869 (repeat :inline t
(file))))
3871 (org-defvaralias 'org-agenda-multi-occur-extra-files
3872 'org-agenda-text-search-extra-files
)
3874 (defcustom org-agenda-skip-unavailable-files nil
3875 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3876 A nil value means to remove them, after a query, from the list."
3880 (defcustom org-calendar-to-agenda-key
[?c
]
3881 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3882 The command `org-calendar-goto-agenda' will be bound to this key. The
3883 default is the character `c' because then `c' can be used to switch back and
3884 forth between agenda and calendar."
3888 (defcustom org-calendar-insert-diary-entry-key
[?i
]
3889 "The key to be installed in `calendar-mode-map' for adding diary entries.
3890 This option is irrelevant until `org-agenda-diary-file' has been configured
3891 to point to an Org-mode file. When that is the case, the command
3892 `org-agenda-diary-entry' will be bound to the key given here, by default
3893 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3894 if you want to continue doing this, you need to change this to a different
3899 (defcustom org-agenda-diary-file
'diary-file
3900 "File to which to add new entries with the `i' key in agenda and calendar.
3901 When this is the symbol `diary-file', the functionality in the Emacs
3902 calendar will be used to add entries to the `diary-file'. But when this
3903 points to a file, `org-agenda-diary-entry' will be used instead."
3906 (const :tag
"The standard Emacs diary file" diary-file
)
3907 (file :tag
"Special Org file diary entries")))
3909 (eval-after-load "calendar"
3911 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3912 'org-calendar-goto-agenda
)
3913 (add-hook 'calendar-mode-hook
3915 (unless (eq org-agenda-diary-file
'diary-file
)
3916 (define-key calendar-mode-map
3917 org-calendar-insert-diary-entry-key
3918 'org-agenda-diary-entry
))))))
3920 (defgroup org-latex nil
3921 "Options for embedding LaTeX code into Org-mode."
3925 (defcustom org-format-latex-options
3926 '(:foreground default
:background default
:scale
1.0
3927 :html-foreground
"Black" :html-background
"Transparent"
3928 :html-scale
1.0 :matchers
("begin" "$1" "$" "$$" "\\(" "\\["))
3929 "Options for creating images from LaTeX fragments.
3930 This is a property list with the following properties:
3931 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3932 `default' means use the foreground of the default face.
3933 `auto' means use the foreground from the text face.
3934 :background the background color, or \"Transparent\".
3935 `default' means use the background of the default face.
3936 `auto' means use the background from the text face.
3937 :scale a scaling factor for the size of the images, to get more pixels
3938 :html-foreground, :html-background, :html-scale
3939 the same numbers for HTML export.
3940 :matchers a list indicating which matchers should be used to
3941 find LaTeX fragments. Valid members of this list are:
3942 \"begin\" find environments
3943 \"$1\" find single characters surrounded by $.$
3944 \"$\" find math expressions surrounded by $...$
3945 \"$$\" find math expressions surrounded by $$....$$
3946 \"\\(\" find math expressions surrounded by \\(...\\)
3947 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3951 (defcustom org-format-latex-signal-error t
3952 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3953 When nil, just push out a message."
3958 (defcustom org-latex-to-mathml-jar-file nil
3959 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3960 Use this to specify additional executable file say a jar file.
3962 When using MathToWeb as the converter, specify the full-path to
3963 your mathtoweb.jar file."
3967 (const :tag
"None" nil
)
3968 (file :tag
"JAR file" :must-match t
)))
3970 (defcustom org-latex-to-mathml-convert-command nil
3971 "Command to convert LaTeX fragments to MathML.
3972 Replace format-specifiers in the command as noted below and use
3973 `shell-command' to convert LaTeX to MathML.
3974 %j: Executable file in fully expanded form as specified by
3975 `org-latex-to-mathml-jar-file'.
3976 %I: Input LaTeX file in fully expanded form
3977 %o: Output MathML file
3978 This command is used by `org-create-math-formula'.
3980 When using MathToWeb as the converter, set this to
3981 \"java -jar %j -unicode -force -df %o %I\"."
3985 (const :tag
"None" nil
)
3986 (string :tag
"\nShell command")))
3988 (defcustom org-latex-create-formula-image-program
'dvipng
3989 "Program to convert LaTeX fragments with.
3991 dvipng Process the LaTeX fragments to dvi file, then convert
3992 dvi files to png files using dvipng.
3993 This will also include processing of non-math environments.
3994 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3995 to convert pdf files to png files"
3999 (const :tag
"dvipng" dvipng
)
4000 (const :tag
"imagemagick" imagemagick
)))
4002 (defcustom org-latex-preview-ltxpng-directory
"ltxpng/"
4003 "Path to store latex preview images.
4004 A relative path here creates many directories relative to the
4005 processed org files paths. An absolute path puts all preview
4006 images at the same place."
4011 (defun org-format-latex-mathml-available-p ()
4012 "Return t if `org-latex-to-mathml-convert-command' is usable."
4014 (when (and (boundp 'org-latex-to-mathml-convert-command
)
4015 org-latex-to-mathml-convert-command
)
4016 (let ((executable (car (split-string
4017 org-latex-to-mathml-convert-command
))))
4018 (when (executable-find executable
)
4020 "%j" org-latex-to-mathml-convert-command
)
4021 (file-readable-p org-latex-to-mathml-jar-file
)
4024 (defcustom org-format-latex-header
"\\documentclass{article}
4025 \\usepackage[usenames]{color}
4028 \\pagestyle{empty} % do not remove
4029 % The settings below are copied from fullpage.sty
4030 \\setlength{\\textwidth}{\\paperwidth}
4031 \\addtolength{\\textwidth}{-3cm}
4032 \\setlength{\\oddsidemargin}{1.5cm}
4033 \\addtolength{\\oddsidemargin}{-2.54cm}
4034 \\setlength{\\evensidemargin}{\\oddsidemargin}
4035 \\setlength{\\textheight}{\\paperheight}
4036 \\addtolength{\\textheight}{-\\headheight}
4037 \\addtolength{\\textheight}{-\\headsep}
4038 \\addtolength{\\textheight}{-\\footskip}
4039 \\addtolength{\\textheight}{-3cm}
4040 \\setlength{\\topmargin}{1.5cm}
4041 \\addtolength{\\topmargin}{-2.54cm}"
4042 "The document header used for processing LaTeX fragments.
4043 It is imperative that this header make sure that no page number
4044 appears on the page. The package defined in the variables
4045 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4046 will either replace the placeholder \"[PACKAGES]\" in this
4047 header, or they will be appended."
4051 (defun org-set-packages-alist (var val
)
4052 "Set the packages alist and make sure it has 3 elements per entry."
4053 (set var
(mapcar (lambda (x)
4054 (if (and (consp x
) (= (length x
) 2))
4055 (list (car x
) (nth 1 x
) t
)
4059 (defun org-get-packages-alist (var)
4060 "Get the packages alist and make sure it has 3 elements per entry."
4062 (if (and (consp x
) (= (length x
) 2))
4063 (list (car x
) (nth 1 x
) t
)
4065 (default-value var
)))
4067 (defcustom org-latex-default-packages-alist
4068 '(("AUTO" "inputenc" t
)
4072 ("" "longtable" nil
)
4076 ("normalem" "ulem" t
)
4085 "Alist of default packages to be inserted in the header.
4087 Change this only if one of the packages here causes an
4088 incompatibility with another package you are using.
4090 The packages in this list are needed by one part or another of
4091 Org mode to function properly:
4093 - inputenc, fontenc: for basic font and character selection
4094 - fixltx2e: Important patches of LaTeX itself
4095 - graphicx: for including images
4096 - longtable: For multipage tables
4097 - float, wrapfig: for figure placement
4098 - rotating: for sideways figures and tables
4099 - ulem: for underline and strike-through
4100 - amsmath: for subscript and superscript and math environments
4101 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4102 for interpreting the entities in `org-entities'. You can skip
4103 some of these packages if you don't use any of their symbols.
4104 - capt-of: for captions outside of floats
4105 - hyperref: for cross references
4107 Therefore you should not modify this variable unless you know
4108 what you are doing. The one reason to change it anyway is that
4109 you might be loading some other package that conflicts with one
4110 of the default packages. Each element is either a cell or
4113 A cell is of the format:
4115 \( \"options\" \"package\" SNIPPET-FLAG).
4117 If SNIPPET-FLAG is non-nil, the package also needs to be included
4118 when compiling LaTeX snippets into images for inclusion into
4121 A string will be inserted as-is in the header of the document."
4123 :group
'org-export-latex
4124 :set
'org-set-packages-alist
4125 :get
'org-get-packages-alist
4129 (list :tag
"options/package pair"
4130 (string :tag
"options")
4131 (string :tag
"package")
4132 (boolean :tag
"Snippet"))
4133 (string :tag
"A line of LaTeX"))))
4135 (defcustom org-latex-packages-alist nil
4136 "Alist of packages to be inserted in every LaTeX header.
4138 These will be inserted after `org-latex-default-packages-alist'.
4139 Each element is either a cell or a string.
4141 A cell is of the format:
4143 \(\"options\" \"package\" SNIPPET-FLAG)
4145 SNIPPET-FLAG, when non-nil, indicates that this package is also
4146 needed when turning LaTeX snippets into images for inclusion into
4149 A string will be inserted as-is in the header of the document.
4151 Make sure that you only list packages here which:
4153 - you want in every file;
4154 - do not conflict with the setup in `org-format-latex-header';
4155 - do not conflict with the default packages in
4156 `org-latex-default-packages-alist'."
4158 :group
'org-export-latex
4159 :set
'org-set-packages-alist
4160 :get
'org-get-packages-alist
4163 (list :tag
"options/package pair"
4164 (string :tag
"options")
4165 (string :tag
"package")
4166 (boolean :tag
"Snippet"))
4167 (string :tag
"A line of LaTeX"))))
4169 (defgroup org-appearance nil
4170 "Settings for Org-mode appearance."
4171 :tag
"Org Appearance"
4174 (defcustom org-level-color-stars-only nil
4175 "Non-nil means fontify only the stars in each headline.
4176 When nil, the entire headline is fontified.
4177 Changing it requires restart of `font-lock-mode' to become effective
4178 also in regions already fontified."
4179 :group
'org-appearance
4182 (defcustom org-hide-leading-stars nil
4183 "Non-nil means hide the first N-1 stars in a headline.
4184 This works by using the face `org-hide' for these stars. This
4185 face is white for a light background, and black for a dark
4186 background. You may have to customize the face `org-hide' to
4188 Changing it requires restart of `font-lock-mode' to become effective
4189 also in regions already fontified.
4190 You may also set this on a per-file basis by adding one of the following
4191 lines to the buffer:
4193 #+STARTUP: hidestars
4194 #+STARTUP: showstars"
4195 :group
'org-appearance
4198 (defcustom org-hidden-keywords nil
4199 "List of symbols corresponding to keywords to be hidden the org buffer.
4200 For example, a value '(title) for this list will make the document's title
4201 appear in the buffer without the initial #+TITLE: keyword."
4202 :group
'org-appearance
4204 :type
'(set (const :tag
"#+AUTHOR" author
)
4205 (const :tag
"#+DATE" date
)
4206 (const :tag
"#+EMAIL" email
)
4207 (const :tag
"#+TITLE" title
)))
4209 (defcustom org-custom-properties nil
4210 "List of properties (as strings) with a special meaning.
4211 The default use of these custom properties is to let the user
4212 hide them with `org-toggle-custom-properties-visibility'."
4213 :group
'org-properties
4214 :group
'org-appearance
4216 :type
'(repeat (string :tag
"Property Name")))
4218 (defcustom org-fontify-done-headline nil
4219 "Non-nil means change the face of a headline if it is marked DONE.
4220 Normally, only the TODO/DONE keyword indicates the state of a headline.
4221 When this is non-nil, the headline after the keyword is set to the
4222 `org-headline-done' as an additional indication."
4223 :group
'org-appearance
4226 (defcustom org-fontify-emphasized-text t
4227 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4228 Changing this variable requires a restart of Emacs to take effect."
4229 :group
'org-appearance
4232 (defcustom org-fontify-whole-heading-line nil
4233 "Non-nil means fontify the whole line for headings.
4234 This is useful when setting a background color for the
4236 :group
'org-appearance
4239 (defcustom org-highlight-latex-and-related nil
4240 "Non-nil means highlight LaTeX related syntax in the buffer.
4241 When non nil, the value should be a list containing any of the
4243 `latex' Highlight LaTeX snippets and environments.
4244 `script' Highlight subscript and superscript.
4245 `entities' Highlight entities."
4246 :group
'org-appearance
4248 :package-version
'(Org .
"8.0")
4250 (const :tag
"No highlighting" nil
)
4251 (set :greedy t
:tag
"Highlight"
4252 (const :tag
"LaTeX snippets and environments" latex
)
4253 (const :tag
"Subscript and superscript" script
)
4254 (const :tag
"Entities" entities
))))
4256 (defcustom org-hide-emphasis-markers nil
4257 "Non-nil mean font-lock should hide the emphasis marker characters."
4258 :group
'org-appearance
4261 (defcustom org-hide-macro-markers nil
4262 "Non-nil mean font-lock should hide the brackets marking macro calls."
4263 :group
'org-appearance
4266 (defcustom org-pretty-entities nil
4267 "Non-nil means show entities as UTF8 characters.
4268 When nil, the \\name form remains in the buffer."
4269 :group
'org-appearance
4273 (defcustom org-pretty-entities-include-sub-superscripts t
4274 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4275 :group
'org-appearance
4279 (defvar org-emph-re nil
4280 "Regular expression for matching emphasis.
4281 After a match, the match groups contain these elements:
4282 0 The match of the full regular expression, including the characters
4283 before and after the proper match
4284 1 The character before the proper match, or empty at beginning of line
4285 2 The proper match, including the leading and trailing markers
4286 3 The leading marker like * or /, indicating the type of highlighting
4287 4 The text between the emphasis markers, not including the markers
4288 5 The character after the match, empty at the end of a line")
4289 (defvar org-verbatim-re nil
4290 "Regular expression for matching verbatim text.")
4291 (defvar org-emphasis-regexp-components
) ; defined just below
4292 (defvar org-emphasis-alist
) ; defined just below
4293 (defun org-set-emph-re (var val
)
4294 "Set variable and compute the emphasis regular expression."
4296 (when (and (boundp 'org-emphasis-alist
)
4297 (boundp 'org-emphasis-regexp-components
)
4298 org-emphasis-alist org-emphasis-regexp-components
)
4299 (let* ((e org-emphasis-regexp-components
)
4305 (body1 (concat body
"*?"))
4306 (markers (mapconcat 'car org-emphasis-alist
""))
4307 (vmarkers (mapconcat
4308 (lambda (x) (if (eq (nth 2 x
) 'verbatim
) (car x
) ""))
4309 org-emphasis-alist
"")))
4310 ;; make sure special characters appear at the right position in the class
4311 (if (string-match "\\^" markers
)
4312 (setq markers
(concat (replace-match "" t t markers
) "^")))
4313 (if (string-match "-" markers
)
4314 (setq markers
(concat (replace-match "" t t markers
) "-")))
4315 (if (string-match "\\^" vmarkers
)
4316 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "^")))
4317 (if (string-match "-" vmarkers
)
4318 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "-")))
4320 (setq body1
(concat body1
"\\(?:\n" body
"*?\\)\\{0,"
4321 (int-to-string nl
) "\\}")))
4324 (concat "\\([" pre
"]\\|^\\)"
4326 "\\([" markers
"]\\)"
4334 "\\([" post
"]\\|$\\)"))
4335 (setq org-verbatim-re
4336 (concat "\\([" pre
"]\\|^\\)"
4338 "\\([" vmarkers
"]\\)"
4346 "\\([" post
"]\\|$\\)")))))
4348 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4349 ;; set this option proved cumbersome. See this message/thread:
4350 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4351 (defvar org-emphasis-regexp-components
4352 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4353 "Components used to build the regular expression for emphasis.
4354 This is a list with five entries. Terminology: In an emphasis string
4355 like \" *strong word* \", we call the initial space PREMATCH, the final
4356 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4357 and \"trong wor\" is the body. The different components in this variable
4358 specify what is allowed/forbidden in each part:
4360 pre Chars allowed as prematch. Beginning of line will be allowed too.
4361 post Chars allowed as postmatch. End of line will be allowed too.
4362 border The chars *forbidden* as border characters.
4363 body-regexp A regexp like \".\" to match a body character. Don't use
4364 non-shy groups here, and don't allow newline here.
4365 newline The maximum number of newlines allowed in an emphasis exp.
4367 You need to reload Org or to restart Emacs after customizing this.")
4369 (defcustom org-emphasis-alist
4373 ("=" org-verbatim verbatim
)
4374 ("~" org-code verbatim
)
4375 ("+" ,(if (featurep 'xemacs
) 'org-table
'(:strike-through t
))))
4376 "Alist of characters and faces to emphasize text.
4377 Text starting and ending with a special character will be emphasized,
4378 for example *bold*, _underlined_ and /italic/. This variable sets the
4379 marker characters and the face to be used by font-lock for highlighting
4380 in Org-mode Emacs buffers.
4382 You need to reload Org or to restart Emacs after customizing this."
4383 :group
'org-appearance
4384 :set
'org-set-emph-re
4386 :package-version
'(Org .
"8.0")
4389 (string :tag
"Marker character")
4391 (face :tag
"Font-lock-face")
4392 (plist :tag
"Face property list"))
4393 (option (const verbatim
)))))
4395 (defvar org-protecting-blocks
4396 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4397 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4398 This is needed for font-lock setup.")
4400 ;;; Miscellaneous options
4402 (defgroup org-completion nil
4403 "Completion in Org-mode."
4404 :tag
"Org Completion"
4407 (defcustom org-completion-use-ido nil
4408 "Non-nil means use ido completion wherever possible.
4409 Note that `ido-mode' must be active for this variable to be relevant.
4410 If you decide to turn this variable on, you might well want to turn off
4411 `org-outline-path-complete-in-steps'.
4412 See also `org-completion-use-iswitchb'."
4413 :group
'org-completion
4416 (defcustom org-completion-use-iswitchb nil
4417 "Non-nil means use iswitchb completion wherever possible.
4418 Note that `iswitchb-mode' must be active for this variable to be relevant.
4419 If you decide to turn this variable on, you might well want to turn off
4420 `org-outline-path-complete-in-steps'.
4421 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4422 :group
'org-completion
4425 (defcustom org-completion-fallback-command
'hippie-expand
4426 "The expansion command called by \\[pcomplete] in normal context.
4427 Normal means, no org-mode-specific context."
4428 :group
'org-completion
4431 ;;; Functions and variables from their packages
4432 ;; Declared here to avoid compiler warnings
4435 (defvar outline-mode-menu-heading
)
4436 (defvar outline-mode-menu-show
)
4437 (defvar outline-mode-menu-hide
)
4438 (defvar zmacs-regions
) ; XEmacs regions
4441 (defvar mark-active
)
4444 (declare-function calendar-absolute-from-iso
"cal-iso" (date))
4445 (declare-function calendar-forward-day
"cal-move" (arg))
4446 (declare-function calendar-goto-date
"cal-move" (date))
4447 (declare-function calendar-goto-today
"cal-move" ())
4448 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
4449 (defvar calc-embedded-close-formula
)
4450 (defvar calc-embedded-open-formula
)
4451 (declare-function cdlatex-tab
"ext:cdlatex" ())
4452 (declare-function cdlatex-compute-tables
"ext:cdlatex" ())
4453 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
4454 (defvar font-lock-unfontify-region-function
)
4455 (declare-function iswitchb-read-buffer
"iswitchb"
4456 (prompt &optional default require-match start matches-set
))
4457 (defvar iswitchb-temp-buflist
)
4458 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
4459 (defvar org-agenda-tags-todo-honor-ignore-options
)
4460 (declare-function org-agenda-skip
"org-agenda" ())
4462 org-agenda-format-item
"org-agenda"
4463 (extra txt
&optional level category tags dotime noprefix remove-re habitp
))
4464 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
4465 (declare-function org-agenda-change-all-lines
"org-agenda"
4466 (newhead hdmarker
&optional fixface just-this
))
4467 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
4468 (declare-function org-agenda-maybe-redo
"org-agenda" ())
4469 (declare-function org-agenda-save-markers-for-cut-and-paste
"org-agenda"
4471 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
4472 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4473 "org-agenda" (&optional end
))
4474 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
4475 (declare-function org-inlinetask-in-task-p
"org-inlinetask" ())
4476 (declare-function org-inlinetask-goto-beginning
"org-inlinetask" ())
4477 (declare-function org-inlinetask-goto-end
"org-inlinetask" ())
4478 (declare-function org-indent-mode
"org-indent" (&optional arg
))
4479 (declare-function parse-time-string
"parse-time" (string))
4480 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
4481 (declare-function orgtbl-send-table
"org-table" (&optional maybe
))
4482 (defvar remember-data-file
)
4483 (defvar texmathp-why
)
4484 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
4485 (declare-function table--at-cell-p
"table" (position &optional object at-column
))
4486 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
4489 (defun turn-on-orgtbl ()
4490 "Unconditionally turn on `orgtbl-mode'."
4491 (require 'org-table
)
4494 (defun org-at-table-p (&optional table-type
)
4495 "Return t if the cursor is inside an org-type table.
4496 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4497 (if org-enable-table-editor
4499 (beginning-of-line 1)
4500 (looking-at (if table-type org-table-any-line-regexp
4501 org-table-line-regexp
)))
4503 (defsubst org-table-p
() (org-at-table-p))
4505 (defun org-at-table.el-p
()
4506 "Return t if and only if we are at a table.el table."
4507 (and (org-at-table-p 'any
)
4509 (goto-char (org-table-begin 'any
))
4510 (looking-at org-table1-hline-regexp
))))
4512 (defun org-table-recognize-table.el
()
4513 "If there is a table.el table nearby, recognize it and move into it."
4514 (if org-table-tab-recognizes-table.el
4515 (if (org-at-table.el-p
)
4517 (beginning-of-line 1)
4518 (if (looking-at org-table-dataline-regexp
)
4520 (if (looking-at org-table1-hline-regexp
)
4522 (beginning-of-line 2)
4523 (if (looking-at org-table-any-border-regexp
)
4524 (beginning-of-line -
1)))))
4525 (if (re-search-forward "|" (org-table-end t
) t
)
4528 (if (table--at-cell-p (point))
4530 (message "recognizing table.el table...")
4531 (table-recognize-table)
4532 (message "recognizing table.el table...done")))
4533 (error "This should not happen"))
4538 (defun org-at-table-hline-p ()
4539 "Return t if the cursor is inside a hline in a table."
4540 (if org-enable-table-editor
4542 (beginning-of-line 1)
4543 (looking-at org-table-hline-regexp
))
4546 (defun org-table-map-tables (function &optional quietly
)
4547 "Apply FUNCTION to the start of all tables in the buffer."
4551 (goto-char (point-min))
4552 (while (re-search-forward org-table-any-line-regexp nil t
)
4554 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4555 (beginning-of-line 1)
4556 (when (and (looking-at org-table-line-regexp
)
4557 ;; Exclude tables in src/example/verbatim/clocktable blocks
4558 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4559 (save-excursion (funcall function
))
4560 (or (looking-at org-table-line-regexp
)
4562 (re-search-forward org-table-any-border-regexp nil
1))))
4563 (unless quietly
(message "Mapping tables: done")))
4565 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock" (beg end
))
4566 (declare-function org-clock-update-mode-line
"org-clock" ())
4567 (declare-function org-resolve-clocks
"org-clock"
4568 (&optional also-non-dangling-p prompt last-valid
))
4570 (defun org-at-TBLFM-p (&optional pos
)
4571 "Return t when point (or POS) is in #+TBLFM line."
4574 (goto-char (or pos
(point)))
4575 (beginning-of-line 1)
4576 (looking-at org-TBLFM-regexp
)))
4578 (defvar org-clock-start-time
)
4579 (defvar org-clock-marker
(make-marker)
4580 "Marker recording the last clock-in.")
4581 (defvar org-clock-hd-marker
(make-marker)
4582 "Marker recording the last clock-in, but the headline position.")
4583 (defvar org-clock-heading
""
4584 "The heading of the current clock entry.")
4585 (defun org-clock-is-active ()
4586 "Return the buffer where the clock is currently running.
4587 Return nil if no clock is running."
4588 (marker-buffer org-clock-marker
))
4590 (defun org-check-running-clock ()
4591 "Check if the current buffer contains the running clock.
4592 If yes, offer to stop it and to save the buffer with the changes."
4593 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4594 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4597 (when (y-or-n-p "Save changed buffer?")
4600 (defun org-clocktable-try-shift (dir n
)
4601 "Check if this line starts a clock table, if yes, shift the time block."
4602 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4603 (org-clocktable-shift dir n
)))
4606 (defun org-clock-persistence-insinuate ()
4607 "Set up hooks for clock persistence."
4608 (require 'org-clock
)
4609 (add-hook 'org-mode-hook
'org-clock-load
)
4610 (add-hook 'kill-emacs-hook
'org-clock-save
))
4612 (defgroup org-archive nil
4613 "Options concerning archiving in Org-mode."
4615 :group
'org-structure
)
4617 (defcustom org-archive-location
"%s_archive::"
4618 "The location where subtrees should be archived.
4620 The value of this variable is a string, consisting of two parts,
4621 separated by a double-colon. The first part is a filename and
4622 the second part is a headline.
4624 When the filename is omitted, archiving happens in the same file.
4625 %s in the filename will be replaced by the current file
4626 name (without the directory part). Archiving to a different file
4627 is useful to keep archived entries from contributing to the
4630 The archived entries will be filed as subtrees of the specified
4631 headline. When the headline is omitted, the subtrees are simply
4632 filed away at the end of the file, as top-level entries. Also in
4633 the heading you can use %s to represent the file name, this can be
4634 useful when using the same archive for a number of different files.
4636 Here are a few examples:
4638 If the current file is Projects.org, archive in file
4639 Projects.org_archive, as top-level trees. This is the default.
4641 \"::* Archived Tasks\"
4642 Archive in the current file, under the top-level headline
4643 \"* Archived Tasks\".
4645 \"~/org/archive.org::\"
4646 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4648 \"~/org/archive.org::* From %s\"
4649 Archive in file ~/org/archive.org (absolute path), under headlines
4650 \"From FILENAME\" where file name is the current file name.
4652 \"~/org/datetree.org::datetree/* Finished Tasks\"
4653 The \"datetree/\" string is special, signifying to archive
4654 items to the datetree. Items are placed in either the CLOSED
4655 date of the item, or the current date if there is no CLOSED date.
4656 The heading will be a subentry to the current date. There doesn't
4657 need to be a heading, but there always needs to be a slash after
4658 datetree. For example, to store archived items directly in the
4659 datetree, use \"~/org/datetree.org::datetree/\".
4661 \"basement::** Finished Tasks\"
4662 Archive in file ./basement (relative path), as level 3 trees
4663 below the level 2 heading \"** Finished Tasks\".
4665 You may set this option on a per-file basis by adding to the buffer a
4668 #+ARCHIVE: basement::** Finished Tasks
4670 You may also define it locally for a subtree by setting an ARCHIVE property
4671 in the entry. If such a property is found in an entry, or anywhere up
4672 the hierarchy, it will be used."
4676 (defcustom org-agenda-skip-archived-trees t
4677 "Non-nil means the agenda will skip any items located in archived trees.
4678 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4679 variable is no longer recommended, you should leave it at the value t.
4680 Instead, use the key `v' to cycle the archives-mode in the agenda."
4682 :group
'org-agenda-skip
4685 (defcustom org-columns-skip-archived-trees t
4686 "Non-nil means ignore archived trees when creating column view."
4688 :group
'org-properties
4691 (defcustom org-cycle-open-archived-trees nil
4692 "Non-nil means `org-cycle' will open archived trees.
4693 An archived tree is a tree marked with the tag ARCHIVE.
4694 When nil, archived trees will stay folded. You can still open them with
4695 normal outline commands like `show-all', but not with the cycling commands."
4700 (defcustom org-sparse-tree-open-archived-trees nil
4701 "Non-nil means sparse tree construction shows matches in archived trees.
4702 When nil, matches in these trees are highlighted, but the trees are kept in
4705 :group
'org-sparse-trees
4708 (defcustom org-sparse-tree-default-date-type
'scheduled-or-deadline
4709 "The default date type when building a sparse tree.
4710 When this is nil, a date is a scheduled or a deadline timestamp.
4711 Otherwise, these types are allowed:
4714 active: only active timestamps (<...>)
4715 inactive: only inactive timestamps (<...)
4716 scheduled: only scheduled timestamps
4717 deadline: only deadline timestamps"
4718 :type
'(choice (const :tag
"Scheduled or deadline" scheduled-or-deadline
)
4719 (const :tag
"All timestamps" all
)
4720 (const :tag
"Only active timestamps" active
)
4721 (const :tag
"Only inactive timestamps" inactive
)
4722 (const :tag
"Only scheduled timestamps" scheduled
)
4723 (const :tag
"Only deadline timestamps" deadline
)
4724 (const :tag
"Only closed timestamps" closed
))
4726 :group
'org-sparse-trees
)
4728 (defun org-cycle-hide-archived-subtrees (state)
4729 "Re-hide all archived subtrees after a visibility state change."
4730 (when (and (not org-cycle-open-archived-trees
)
4731 (not (memq state
'(overview folded
))))
4733 (let* ((globalp (memq state
'(contents all
)))
4734 (beg (if globalp
(point-min) (point)))
4735 (end (if globalp
(point-max) (org-end-of-subtree t
))))
4736 (org-hide-archived-subtrees beg end
)
4738 (if (looking-at (concat ".*:" org-archive-tag
":"))
4739 (message "%s" (substitute-command-keys
4740 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4742 (defun org-force-cycle-archived ()
4743 "Cycle subtree even if it is archived."
4745 (setq this-command
'org-cycle
)
4746 (let ((org-cycle-open-archived-trees t
))
4747 (call-interactively 'org-cycle
)))
4749 (defun org-hide-archived-subtrees (beg end
)
4750 "Re-hide all archived subtrees after a visibility state change."
4752 (let* ((re (concat ":" org-archive-tag
":")))
4754 (while (re-search-forward re end t
)
4755 (when (org-at-heading-p)
4756 (org-flag-subtree t
)
4757 (org-end-of-subtree t
))))))
4759 (declare-function outline-end-of-heading
"outline" ())
4760 (declare-function outline-flag-region
"outline" (from to flag
))
4761 (defun org-flag-subtree (flag)
4763 (org-back-to-heading t
)
4764 (outline-end-of-heading)
4765 (outline-flag-region (point)
4766 (progn (org-end-of-subtree t
) (point))
4769 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
4771 ;; Declare Column View Code
4773 (declare-function org-columns-number-to-string
"org-colview" (n fmt
&optional printf
))
4774 (declare-function org-columns-get-format-and-top-level
"org-colview" ())
4775 (declare-function org-columns-compute
"org-colview" (property))
4779 (declare-function org-id-store-link
"org-id")
4780 (declare-function org-id-locations-load
"org-id")
4781 (declare-function org-id-locations-save
"org-id")
4782 (defvar org-id-track-globally
)
4784 ;;; Variables for pre-computed regular expressions, all buffer local
4786 (defvar org-todo-regexp nil
4787 "Matches any of the TODO state keywords.")
4788 (make-variable-buffer-local 'org-todo-regexp
)
4789 (defvar org-not-done-regexp nil
4790 "Matches any of the TODO state keywords except the last one.")
4791 (make-variable-buffer-local 'org-not-done-regexp
)
4792 (defvar org-not-done-heading-regexp nil
4793 "Matches a TODO headline that is not done.")
4794 (make-variable-buffer-local 'org-not-done-regexp
)
4795 (defvar org-todo-line-regexp nil
4796 "Matches a headline and puts TODO state into group 2 if present.")
4797 (make-variable-buffer-local 'org-todo-line-regexp
)
4798 (defvar org-complex-heading-regexp nil
4799 "Matches a headline and puts everything into groups:
4801 group 2: The todo keyword, maybe
4802 group 3: Priority cookie
4803 group 4: True headline
4805 (make-variable-buffer-local 'org-complex-heading-regexp
)
4806 (defvar org-complex-heading-regexp-format nil
4807 "Printf format to make regexp to match an exact headline.
4808 This regexp will match the headline of any node which has the
4809 exact headline text that is put into the format, but may have any
4810 TODO state, priority and tags.")
4811 (make-variable-buffer-local 'org-complex-heading-regexp-format
)
4812 (defvar org-todo-line-tags-regexp nil
4813 "Matches a headline and puts TODO state into group 2 if present.
4814 Also put tags into group 4 if tags are present.")
4815 (make-variable-buffer-local 'org-todo-line-tags-regexp
)
4817 (defconst org-plain-time-of-day-regexp
4820 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4823 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4825 "Regular expression to match a plain time or time range.
4826 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4827 groups carry important information:
4829 1 the first time, range or not
4830 8 the second time, if it is a range.")
4832 (defconst org-plain-time-extension-regexp
4835 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4836 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4837 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4838 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4839 groups carry important information:
4842 9 minutes of duration")
4844 (defconst org-stamp-time-of-day-regexp
4846 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4847 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4849 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4850 "Regular expression to match a timestamp time or time range.
4851 After a match, the following groups carry important information:
4853 1 date plus weekday, for back referencing to make sure both times are on the same day
4854 2 the first time, range or not
4855 4 the second time, if it is a range.")
4857 (defconst org-startup-options
4858 '(("fold" org-startup-folded t
)
4859 ("overview" org-startup-folded t
)
4860 ("nofold" org-startup-folded nil
)
4861 ("showall" org-startup-folded nil
)
4862 ("showeverything" org-startup-folded showeverything
)
4863 ("content" org-startup-folded content
)
4864 ("indent" org-startup-indented t
)
4865 ("noindent" org-startup-indented nil
)
4866 ("hidestars" org-hide-leading-stars t
)
4867 ("showstars" org-hide-leading-stars nil
)
4868 ("odd" org-odd-levels-only t
)
4869 ("oddeven" org-odd-levels-only nil
)
4870 ("align" org-startup-align-all-tables t
)
4871 ("noalign" org-startup-align-all-tables nil
)
4872 ("inlineimages" org-startup-with-inline-images t
)
4873 ("noinlineimages" org-startup-with-inline-images nil
)
4874 ("latexpreview" org-startup-with-latex-preview t
)
4875 ("nolatexpreview" org-startup-with-latex-preview nil
)
4876 ("customtime" org-display-custom-times t
)
4877 ("logdone" org-log-done time
)
4878 ("lognotedone" org-log-done note
)
4879 ("nologdone" org-log-done nil
)
4880 ("lognoteclock-out" org-log-note-clock-out t
)
4881 ("nolognoteclock-out" org-log-note-clock-out nil
)
4882 ("logrepeat" org-log-repeat state
)
4883 ("lognoterepeat" org-log-repeat note
)
4884 ("logdrawer" org-log-into-drawer t
)
4885 ("nologdrawer" org-log-into-drawer nil
)
4886 ("logstatesreversed" org-log-states-order-reversed t
)
4887 ("nologstatesreversed" org-log-states-order-reversed nil
)
4888 ("nologrepeat" org-log-repeat nil
)
4889 ("logreschedule" org-log-reschedule time
)
4890 ("lognotereschedule" org-log-reschedule note
)
4891 ("nologreschedule" org-log-reschedule nil
)
4892 ("logredeadline" org-log-redeadline time
)
4893 ("lognoteredeadline" org-log-redeadline note
)
4894 ("nologredeadline" org-log-redeadline nil
)
4895 ("logrefile" org-log-refile time
)
4896 ("lognoterefile" org-log-refile note
)
4897 ("nologrefile" org-log-refile nil
)
4898 ("fninline" org-footnote-define-inline t
)
4899 ("nofninline" org-footnote-define-inline nil
)
4900 ("fnlocal" org-footnote-section nil
)
4901 ("fnauto" org-footnote-auto-label t
)
4902 ("fnprompt" org-footnote-auto-label nil
)
4903 ("fnconfirm" org-footnote-auto-label confirm
)
4904 ("fnplain" org-footnote-auto-label plain
)
4905 ("fnadjust" org-footnote-auto-adjust t
)
4906 ("nofnadjust" org-footnote-auto-adjust nil
)
4907 ("constcgs" constants-unit-system cgs
)
4908 ("constSI" constants-unit-system SI
)
4909 ("noptag" org-tag-persistent-alist nil
)
4910 ("hideblocks" org-hide-block-startup t
)
4911 ("nohideblocks" org-hide-block-startup nil
)
4912 ("beamer" org-startup-with-beamer-mode t
)
4913 ("entitiespretty" org-pretty-entities t
)
4914 ("entitiesplain" org-pretty-entities nil
))
4915 "Variable associated with STARTUP options for org-mode.
4916 Each element is a list of three items: the startup options (as written
4917 in the #+STARTUP line), the corresponding variable, and the value to set
4918 this variable to if the option is found. An optional forth element PUSH
4919 means to push this value onto the list in the variable.")
4921 (defcustom org-group-tags t
4922 "When non-nil (the default), use group tags.
4923 This can be turned on/off through `org-toggle-tags-groups'."
4928 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
4930 (defun org-toggle-tags-groups ()
4931 "Toggle support for group tags.
4932 Support for group tags is controlled by the option
4933 `org-group-tags', which is non-nil by default."
4935 (setq org-group-tags
(not org-group-tags
))
4936 (cond ((and (derived-mode-p 'org-agenda-mode
)
4939 ((derived-mode-p 'org-mode
)
4940 (let ((org-inhibit-startup t
)) (org-mode))))
4941 (message "Groups tags support has been turned %s"
4942 (if org-group-tags
"on" "off")))
4944 (defun org-set-regexps-and-options (&optional tags-only
)
4945 "Precompute regular expressions used in the current buffer.
4946 When optional argument TAGS-ONLY is non-nil, only compute tags
4947 related expressions."
4948 (when (derived-mode-p 'org-mode
)
4949 (let ((alist (org--setup-collect-keywords
4950 (org-make-options-regexp
4951 (append '("FILETAGS" "TAGS" "SETUPFILE")
4952 (and (not tags-only
)
4953 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4954 "LINK" "PRIORITIES" "PROPERTY" "SEQ_TODO"
4955 "STARTUP" "TODO" "TYP_TODO")))))))
4956 (org--setup-process-tags
4957 (cdr (assq 'tags alist
)) (cdr (assq 'filetags alist
)))
4960 (org-set-local 'org-file-properties
(cdr (assq 'property alist
)))
4961 ;; Archive location.
4962 (let ((archive (cdr (assq 'archive alist
))))
4963 (when archive
(org-set-local 'org-archive-location archive
)))
4965 (let ((cat (org-string-nw-p (cdr (assq 'category alist
)))))
4967 (org-set-local 'org-category
(intern cat
))
4968 (org-set-local 'org-file-properties
4969 (org--update-property-plist
4970 "CATEGORY" cat org-file-properties
))))
4972 (let ((column (cdr (assq 'columns alist
))))
4973 (when column
(org-set-local 'org-columns-default-format column
)))
4975 (setq org-table-formula-constants-local
(cdr (assq 'constants alist
)))
4976 ;; Link abbreviations.
4977 (let ((links (cdr (assq 'link alist
))))
4978 (when links
(setq org-link-abbrev-alist-local
(nreverse links
))))
4980 (let ((priorities (cdr (assq 'priorities alist
))))
4982 (org-set-local 'org-highest-priority
(nth 0 priorities
))
4983 (org-set-local 'org-lowest-priority
(nth 1 priorities
))
4984 (org-set-local 'org-default-priority
(nth 2 priorities
))))
4986 (let ((startup (cdr (assq 'startup alist
))))
4987 (dolist (option startup
)
4988 (let ((entry (assoc-string option org-startup-options t
)))
4989 (let ((var (nth 1 entry
))
4990 (val (nth 2 entry
)))
4991 (if (not (nth 3 entry
)) (org-set-local var val
)
4992 (unless (listp (symbol-value var
))
4993 (org-set-local var nil
))
4994 (add-to-list var val
))))))
4996 (org-set-local 'org-todo-kwd-alist nil
)
4997 (org-set-local 'org-todo-key-alist nil
)
4998 (org-set-local 'org-todo-key-trigger nil
)
4999 (org-set-local 'org-todo-keywords-1 nil
)
5000 (org-set-local 'org-done-keywords nil
)
5001 (org-set-local 'org-todo-heads nil
)
5002 (org-set-local 'org-todo-sets nil
)
5003 (org-set-local 'org-todo-log-states nil
)
5004 (let ((todo-sequences
5006 (or (cdr (assq 'todo alist
))
5007 (let ((d (default-value 'org-todo-keywords
)))
5008 (if (not (stringp (car d
))) d
5009 ;; XXX: Backward compatibility code.
5010 (list (cons org-todo-interpretation d
))))))))
5011 (dolist (sequence todo-sequences
)
5012 (let* ((sequence (or (run-hook-with-args-until-success
5013 'org-todo-setup-filter-hook sequence
)
5015 (sequence-type (car sequence
))
5016 (keywords (cdr sequence
))
5017 (sep (member "|" keywords
))
5019 (dolist (k (remove "|" keywords
))
5020 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5022 (error "Invalid TODO keyword %s" k
))
5023 (let ((name (match-string 1 k
))
5024 (key (match-string 2 k
))
5025 (log (org-extract-log-state-settings k
)))
5027 (push (cons name
(and key
(string-to-char key
))) alist
)
5028 (when log
(push log org-todo-log-states
))))
5029 (let* ((names (nreverse names
))
5030 (done (if sep
(org-remove-keyword-keys (cdr sep
))
5033 (tail (list sequence-type head
(car done
) (org-last done
))))
5034 (add-to-list 'org-todo-heads head
'append
)
5035 (push names org-todo-sets
)
5036 (setq org-done-keywords
(append org-done-keywords done nil
))
5037 (setq org-todo-keywords-1
(append org-todo-keywords-1 names nil
))
5038 (setq org-todo-key-alist
5039 (append org-todo-key-alist
5041 (append '((:startgroup
))
5044 (dolist (k names
) (push (cons k tail
) org-todo-kwd-alist
))))))
5045 (setq org-todo-sets
(nreverse org-todo-sets
)
5046 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
5047 org-todo-key-trigger
(delq nil
(mapcar #'cdr org-todo-key-alist
))
5048 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
))
5049 ;; Compute the regular expressions and other local variables.
5050 ;; Using `org-outline-regexp-bol' would complicate them much,
5051 ;; because of the fixed white space at the end of that string.
5052 (if (not org-done-keywords
)
5053 (setq org-done-keywords
5054 (and org-todo-keywords-1
(last org-todo-keywords-1
))))
5055 (setq org-not-done-keywords
5056 (org-delete-all org-done-keywords
5057 (copy-sequence org-todo-keywords-1
))
5058 org-todo-regexp
(regexp-opt org-todo-keywords-1 t
)
5059 org-not-done-regexp
(regexp-opt org-not-done-keywords t
)
5060 org-not-done-heading-regexp
5061 (format org-heading-keyword-regexp-format org-not-done-regexp
)
5062 org-todo-line-regexp
5063 (format org-heading-keyword-maybe-regexp-format org-todo-regexp
)
5064 org-complex-heading-regexp
5065 (concat "^\\(\\*+\\)"
5066 "\\(?: +" org-todo-regexp
"\\)?"
5067 "\\(?: +\\(\\[#.\\]\\)\\)?"
5068 "\\(?: +\\(.*?\\)\\)??"
5069 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5071 org-complex-heading-regexp-format
5072 (concat "^\\(\\*+\\)"
5073 "\\(?: +" org-todo-regexp
"\\)?"
5074 "\\(?: +\\(\\[#.\\]\\)\\)?"
5076 ;; Stats cookies can be stuck to body.
5077 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5079 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5081 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5083 org-todo-line-tags-regexp
5084 (concat "^\\(\\*+\\)"
5085 "\\(?: +" org-todo-regexp
"\\)?"
5086 "\\(?: +\\(.*?\\)\\)??"
5087 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5089 (org-compute-latex-and-related-regexp)))))
5091 (defun org--setup-collect-keywords (regexp &optional files alist
)
5092 "Return setup keywords values as an alist.
5094 REGEXP matches a subset of setup keywords. FILES is a list of
5095 file names already visited. It is used to avoid circular setup
5096 files. ALIST, when non-nil, is the alist computed so far.
5098 Return value contains the following keys: `archive', `category',
5099 `columns', `constants', `filetags', `link', `priorities',
5100 `property', `startup', `tags' and `todo'."
5101 (org-with-wide-buffer
5102 (goto-char (point-min))
5103 (let ((case-fold-search t
))
5104 (while (re-search-forward regexp nil t
)
5105 (let ((element (org-element-at-point)))
5106 (when (eq (org-element-type element
) 'keyword
)
5107 (let ((key (org-element-property :key element
))
5108 (value (org-element-property :value element
)))
5110 ((equal key
"ARCHIVE")
5111 (when (org-string-nw-p value
)
5112 (push (cons 'archive value
) alist
)))
5113 ((equal key
"CATEGORY") (push (cons 'category value
) alist
))
5114 ((equal key
"COLUMNS") (push (cons 'columns value
) alist
))
5115 ((equal key
"CONSTANTS")
5116 (let* ((constants (assq 'constants alist
))
5117 (store (cdr constants
)))
5118 (dolist (pair (org-split-string value
))
5119 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5121 (let* ((name (match-string 1 pair
))
5122 (value (match-string 2 pair
))
5123 (old (assoc name store
)))
5124 (if old
(setcdr old value
)
5125 (push (cons name value
) store
)))))
5126 (if constants
(setcdr constants store
)
5127 (push (cons 'constants store
) alist
))))
5128 ((equal key
"FILETAGS")
5129 (when (org-string-nw-p value
)
5130 (let ((old (assq 'filetags alist
))
5132 (mapcar (lambda (x) (org-split-string x
":"))
5133 (org-split-string value
)))))
5134 (if old
(setcdr old
(nconc new
(cdr old
)))
5135 (push (cons 'filetags new
) alist
)))))
5137 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
5138 (let ((links (assq 'link alist
))
5139 (pair (cons (org-match-string-no-properties 1 value
)
5140 (org-match-string-no-properties 2 value
))))
5141 (if links
(push pair
(cdr links
))
5142 (push (list 'link pair
) alist
)))))
5143 ((equal key
"PRIORITIES")
5144 (push (cons 'priorities
5145 (let ((prio (org-split-string value
)))
5146 (if (< (length prio
) 3) '(?A ?C ?B
)
5147 (mapcar #'string-to-char prio
))))
5149 ((equal key
"PROPERTY")
5150 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value
)
5151 (let* ((property (assq 'property alist
))
5152 (value (org--update-property-plist
5153 (org-match-string-no-properties 1 value
)
5154 (org-match-string-no-properties 2 value
)
5156 (if property
(setcdr property value
)
5157 (push (cons 'property value
) alist
)))))
5158 ((equal key
"STARTUP")
5159 (let ((startup (assq 'startup alist
)))
5162 (nconc (cdr startup
) (org-split-string value
)))
5163 (push (cons 'startup
(org-split-string value
)) alist
))))
5165 (let ((tag-cell (assq 'tags alist
)))
5168 (nconc (cdr tag-cell
)
5170 (org-split-string value
)))
5171 (push (cons 'tags
(org-split-string value
)) alist
))))
5172 ((member key
'("TODO" "SEQ_TODO" "TYP_TODO"))
5173 (let ((todo (assq 'todo alist
))
5174 (value (cons (if (equal key
"TYP_TODO") 'type
'sequence
)
5175 (org-split-string value
))))
5176 (if todo
(push value
(cdr todo
))
5177 (push (list 'todo value
) alist
))))
5178 ((equal key
"SETUPFILE")
5179 (unless buffer-read-only
; Do not check in Gnus messages.
5180 (let ((f (expand-file-name (org-remove-double-quotes value
))))
5181 (when (and (org-string-nw-p f
)
5183 (not (member f files
)))
5185 (let ((org-inhibit-startup t
)) (org-mode))
5186 (insert-file-contents f
)
5188 (org--setup-collect-keywords
5189 regexp alist
(cons f files
)))))))))))))))
5192 (defun org--setup-process-tags (tags filetags
)
5193 "Precompute variables used for tags.
5194 TAGS is a list of tags and tag group symbols, as strings.
5195 FILETAGS is a list of tags, as strings."
5196 ;; Process the file tags.
5197 (org-set-local 'org-file-tags
5198 (mapcar #'org-add-prop-inherited filetags
))
5199 ;; Provide default tags if no local tags are found.
5200 (when (and (not tags
) org-tag-alist
)
5202 (mapcar (lambda (tag)
5208 (otherwise (concat (car tag
)
5209 (and (characterp (cdr tag
))
5210 (format "(%c)" (cdr tag
)))))))
5212 ;; Process the tags.
5213 (org-set-local 'org-tag-groups-alist nil
)
5214 (org-set-local 'org-tag-alist nil
)
5219 (push '(:startgroup
) org-tag-alist
)
5220 (setq group-flag t
))
5222 (push '(:endgroup
) org-tag-alist
)
5223 (setq group-flag nil
))
5225 (push '(:grouptags
) org-tag-alist
)
5226 (setq group-flag
'append
))
5227 ((equal e
"\\n") (push '(:newline
) org-tag-alist
))
5228 ((string-match (org-re "\\`\\([[:alnum:]_@#%]+\\)\\(?:(\\(.\\))\\)?\\'")
5230 (let ((tag (match-string 1 e
))
5231 (key (and (match-beginning 2)
5232 (string-to-char (match-string 2 e
)))))
5233 (cond ((eq group-flag
'append
)
5234 (setcar org-tag-groups-alist
5235 (append (car org-tag-groups-alist
) (list tag
))))
5236 (group-flag (push (list tag
) org-tag-groups-alist
)))
5237 (unless (assoc tag org-tag-alist
)
5238 (push (cons tag key
) org-tag-alist
)))))))
5239 (setq org-tag-alist
(nreverse org-tag-alist
)))
5241 (defun org-file-contents (file &optional noerror
)
5242 "Return the contents of FILE, as a string."
5243 (if (and file
(file-readable-p file
))
5245 (insert-file-contents file
)
5247 (funcall (if noerror
'message
'error
)
5248 "Cannot read file \"%s\"%s"
5250 (let ((from (buffer-file-name (buffer-base-buffer))))
5251 (if from
(concat " (referenced in file \"" from
"\")") "")))))
5253 (defun org-extract-log-state-settings (x)
5254 "Extract the log state setting from a TODO keyword string.
5255 This will extract info from a string like \"WAIT(w@/!)\"."
5256 (let (kw key log1 log2
)
5257 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
5258 (setq kw
(match-string 1 x
)
5259 key
(and (match-end 2) (match-string 2 x
))
5260 log1
(and (match-end 3) (match-string 3 x
))
5261 log2
(and (match-end 4) (match-string 4 x
)))
5264 (and log1
(if (equal log1
"!") 'time
'note
))
5265 (and log2
(if (equal log2
"!") 'time
'note
)))))))
5267 (defun org-remove-keyword-keys (list)
5268 "Remove a pair of parenthesis at the end of each string in LIST."
5270 (if (string-match "(.*)$" x
)
5271 (substring x
0 (match-beginning 0))
5275 (defun org-assign-fast-keys (alist)
5276 "Assign fast keys to a keyword-key alist.
5277 Respect keys that are already there."
5278 (let (new e
(alt ?
0))
5279 (while (setq e
(pop alist
))
5280 (if (or (memq (car e
) '(:newline
:grouptags
:endgroup
:startgroup
))
5281 (cdr e
)) ;; Key already assigned.
5283 (let ((clist (string-to-list (downcase (car e
))))
5284 (used (append new alist
)))
5285 (when (= (car clist
) ?
@)
5287 (while (and clist
(rassoc (car clist
) used
))
5290 (while (rassoc alt used
)
5292 (push (cons (car e
) (or (car clist
) alt
)) new
))))
5295 ;;; Some variables used in various places
5297 (defvar org-window-configuration nil
5298 "Used in various places to store a window configuration.")
5299 (defvar org-selected-window nil
5300 "Used in various places to store a window configuration.")
5301 (defvar org-finish-function nil
5302 "Function to be called when `C-c C-c' is used.
5303 This is for getting out of special buffers like capture.")
5306 ;; FIXME: Occasionally check by commenting these, to make sure
5307 ;; no other functions uses these, forgetting to let-bind them.
5308 (org-no-warnings (defvar entry
)) ;; unprefixed, from calendar.el
5309 (defvar org-last-state
)
5310 (org-no-warnings (defvar date
)) ;; unprefixed, from calendar.el
5312 ;; Defined somewhere in this file, but used before definition.
5313 (defvar org-entities
) ;; defined in org-entities.el
5314 (defvar org-struct-menu
)
5315 (defvar org-org-menu
)
5316 (defvar org-tbl-menu
)
5318 ;;;; Define the Org-mode
5320 ;; We use a before-change function to check if a table might need
5322 (defvar org-table-may-need-update t
5323 "Indicates that a table might need an update.
5324 This variable is set by `org-before-change-function'.
5325 `org-table-align' sets it back to nil.")
5326 (defun org-before-change-function (beg end
)
5327 "Every change indicates that a table might need an update."
5328 (setq org-table-may-need-update t
))
5329 (defvar org-mode-map
)
5330 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
5331 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
5332 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
5333 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
5334 (defvar org-table-buffer-is-an nil
)
5336 (defvar bidi-paragraph-direction
)
5337 (defvar buffer-face-mode-face
)
5340 (if (and (not (keymapp outline-mode-map
)) (featurep 'allout
))
5341 (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"))
5342 (require 'noutline
"noutline" 'noerror
) ;; stock XEmacs does not have it
5344 ;; Other stuff we need.
5345 (require 'time-date
)
5346 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
5350 ;; (require 'org-macs) moved higher up in the file before it is first used
5351 (require 'org-entities
)
5352 ;; (require 'org-compat) moved higher up in the file before it is first used
5353 (require 'org-faces
)
5355 (require 'org-pcomplete
)
5357 (require 'org-footnote
)
5358 (require 'org-macro
)
5364 (define-derived-mode org-mode outline-mode
"Org"
5365 "Outline-based notes management and organizer, alias
5366 \"Carsten's outline-mode for keeping track of everything.\"
5368 Org-mode develops organizational tasks around a NOTES file which
5369 contains information about projects as plain text. Org-mode is
5370 implemented on top of outline-mode, which is ideal to keep the content
5371 of large files well structured. It supports ToDo items, deadlines and
5372 time stamps, which magically appear in the diary listing of the Emacs
5373 calendar. Tables are easily created with a built-in table editor.
5374 Plain text URL-like links connect to websites, emails (VM), Usenet
5375 messages (Gnus), BBDB entries, and any files related to the project.
5376 For printing and sharing of notes, an Org-mode file (or a part of it)
5377 can be exported as a structured ASCII or HTML file.
5379 The following commands are available:
5383 ;; Get rid of Outline menus, they are not needed
5384 ;; Need to do this here because define-derived-mode sets up
5385 ;; the keymap so late. Still, it is a waste to call this each time
5386 ;; we switch another buffer into org-mode.
5387 (if (featurep 'xemacs
)
5388 (when (boundp 'outline-mode-menu-heading
)
5389 ;; Assume this is Greg's port, it uses easymenu
5390 (easy-menu-remove outline-mode-menu-heading
)
5391 (easy-menu-remove outline-mode-menu-show
)
5392 (easy-menu-remove outline-mode-menu-hide
))
5393 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
5394 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
5395 (define-key org-mode-map
[menu-bar show
] 'undefined
))
5397 (org-load-modules-maybe)
5398 (easy-menu-add org-org-menu
)
5399 (easy-menu-add org-tbl-menu
)
5400 (org-install-agenda-files-menu)
5401 (if org-descriptive-links
(add-to-invisibility-spec '(org-link)))
5402 (add-to-invisibility-spec '(org-cwidth))
5403 (add-to-invisibility-spec '(org-hide-block . t
))
5404 (when (featurep 'xemacs
)
5405 (org-set-local 'line-move-ignore-invisible t
))
5406 (org-set-local 'outline-regexp org-outline-regexp
)
5407 (org-set-local 'outline-level
'org-outline-level
)
5408 (setq bidi-paragraph-direction
'left-to-right
)
5409 (when (and org-ellipsis
5410 (fboundp 'set-display-table-slot
) (boundp 'buffer-display-table
)
5411 (fboundp 'make-glyph-code
))
5412 (unless org-display-table
5413 (setq org-display-table
(make-display-table)))
5414 (set-display-table-slot
5417 (lambda (c) (make-glyph-code c
(and (not (stringp org-ellipsis
))
5419 (if (stringp org-ellipsis
) org-ellipsis
"..."))))
5420 (setq buffer-display-table org-display-table
))
5421 (org-set-regexps-and-options)
5422 (org-set-font-lock-defaults)
5423 (when (and org-tag-faces
(not org-tags-special-faces-re
))
5424 ;; tag faces set outside customize.... force initialization.
5425 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
5427 (org-set-local 'calc-embedded-open-mode
"# ")
5428 ;; Modify a few syntax entries
5429 (modify-syntax-entry ?
@ "w")
5430 (modify-syntax-entry ?
\" "\"")
5431 (modify-syntax-entry ?
\\ "_")
5432 (modify-syntax-entry ?~
"_")
5433 (if org-startup-truncated
(setq truncate-lines t
))
5434 (when org-startup-indented
(require 'org-indent
) (org-indent-mode 1))
5435 (org-set-local 'font-lock-unfontify-region-function
5436 'org-unfontify-region
)
5437 ;; Activate before-change-function
5438 (org-set-local 'org-table-may-need-update t
)
5439 (org-add-hook 'before-change-functions
'org-before-change-function nil
5441 ;; Check for running clock before killing a buffer
5442 (org-add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
5443 ;; Initialize macros templates.
5444 (org-macro-initialize-templates)
5445 ;; Initialize radio targets.
5446 (org-update-radio-target-regexp)
5448 (org-set-local 'indent-line-function
'org-indent-line
)
5449 (org-set-local 'indent-region-function
'org-indent-region
)
5450 ;; Filling and auto-filling.
5453 (org-setup-comments-handling)
5454 ;; Initialize cache.
5455 (org-element-cache-reset)
5456 ;; Beginning/end of defun
5457 (org-set-local 'beginning-of-defun-function
'org-backward-element
)
5458 (org-set-local 'end-of-defun-function
5460 (if (not (org-at-heading-p))
5461 (org-forward-element)
5462 (org-forward-element)
5463 (forward-char -
1))))
5464 ;; Next error for sparse trees
5465 (org-set-local 'next-error-function
'org-occur-next-match
)
5466 ;; Make sure dependence stuff works reliably, even for users who set it
5468 (if org-enforce-todo-dependencies
5469 (add-hook 'org-blocker-hook
5470 'org-block-todo-from-children-or-siblings-or-parent
)
5471 (remove-hook 'org-blocker-hook
5472 'org-block-todo-from-children-or-siblings-or-parent
))
5473 (if org-enforce-todo-checkbox-dependencies
5474 (add-hook 'org-blocker-hook
5475 'org-block-todo-from-checkboxes
)
5476 (remove-hook 'org-blocker-hook
5477 'org-block-todo-from-checkboxes
))
5479 ;; Align options lines
5481 'align-mode-rules-list
5482 '((org-in-buffer-settings
5483 (regexp .
"^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5484 (modes .
'(org-mode)))))
5487 (org-set-local 'imenu-create-index-function
5488 'org-imenu-get-tree
)
5490 ;; Make isearch reveal context
5491 (if (or (featurep 'xemacs
)
5492 (not (boundp 'outline-isearch-open-invisible-function
)))
5493 ;; Emacs 21 and XEmacs make use of the hook
5494 (org-add-hook 'isearch-mode-end-hook
'org-isearch-end
'append
'local
)
5495 ;; Emacs 22 deals with this through a special variable
5496 (org-set-local 'outline-isearch-open-invisible-function
5497 (lambda (&rest ignore
) (org-show-context 'isearch
))))
5499 ;; Setup the pcomplete hooks
5500 (set (make-local-variable 'pcomplete-command-completion-function
)
5501 'org-pcomplete-initial
)
5502 (set (make-local-variable 'pcomplete-command-name-function
)
5503 'org-command-at-point
)
5504 (set (make-local-variable 'pcomplete-default-completion-function
)
5506 (set (make-local-variable 'pcomplete-parse-arguments-function
)
5507 'org-parse-arguments
)
5508 (set (make-local-variable 'pcomplete-termination-string
) "")
5509 (when (>= emacs-major-version
23)
5510 (set (make-local-variable 'buffer-face-mode-face
) 'org-default
))
5512 ;; If empty file that did not turn on org-mode automatically, make it to.
5513 (if (and org-insert-mode-line-in-empty-file
5514 (org-called-interactively-p 'any
)
5515 (= (point-min) (point-max)))
5516 (insert "# -*- mode: org -*-\n\n"))
5517 (unless org-inhibit-startup
5519 (and org-startup-with-beamer-mode
(org-beamer-mode))
5520 (when org-startup-align-all-tables
5521 (org-table-map-tables 'org-table-align
'quietly
))
5522 (when org-startup-with-inline-images
5523 (org-display-inline-images))
5524 (when org-startup-with-latex-preview
5525 (org-toggle-latex-fragment))
5526 (unless org-inhibit-startup-visibility-stuff
5527 (org-set-startup-visibility))
5528 (org-refresh-effort-properties)))
5529 ;; Try to set org-hide correctly
5530 (let ((foreground (org-find-invisible-foreground)))
5532 (set-face-foreground 'org-hide foreground
))))
5534 ;; Update `customize-package-emacs-version-alist'
5535 (add-to-list 'customize-package-emacs-version-alist
5536 '(Org ("6.21b" .
"23.1") ("6.33x" .
"23.2")
5537 ("7.8.11" .
"24.1") ("7.9.4" .
"24.3")
5538 ("8.2.6" .
"24.4")))
5540 (defvar org-mode-transpose-word-syntax-table
5541 (let ((st (make-syntax-table)))
5542 (mapc (lambda(c) (modify-syntax-entry
5543 (string-to-char (car c
)) "w p" st
))
5547 (when (fboundp 'abbrev-table-put
)
5548 (abbrev-table-put org-mode-abbrev-table
5549 :parents
(list text-mode-abbrev-table
)))
5551 (defun org-find-invisible-foreground ()
5552 (let ((candidates (remove
5555 (list (face-background 'default
)
5556 (face-background 'org-default
))
5559 (when (boundp alist
)
5560 (cdr (assoc 'background-color
(symbol-value alist
)))))
5561 '(default-frame-alist initial-frame-alist window-system-default-frame-alist
))
5562 (list (face-foreground 'org-hide
))))))
5563 (car (remove nil candidates
))))
5565 (defun org-current-time (&optional rounding-minutes past
)
5566 "Current time, possibly rounded to ROUNDING-MINUTES.
5567 When ROUNDING-MINUTES is not an integer, fall back on the car of
5568 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5569 the rounding returns a past time."
5570 (let ((r (or (and (integerp rounding-minutes
) rounding-minutes
)
5571 (car org-time-stamp-rounding-minutes
)))
5572 (time (decode-time)) res
)
5577 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
5579 (if (and past
(< (org-float-time (time-subtract (current-time) res
)) 0))
5580 (seconds-to-time (- (org-float-time res
) (* r
60)))
5584 "Return today date, considering `org-extend-today-until'."
5586 (time-subtract (current-time)
5587 (list 0 (* 3600 org-extend-today-until
) 0))))
5589 ;;;; Font-Lock stuff, including the activators
5591 (defvar org-mouse-map
(make-sparse-keymap))
5592 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
5593 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
5594 (when org-mouse-1-follows-link
5595 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
5596 (when org-tab-follows-link
5597 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
5598 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
5600 (require 'font-lock
)
5602 (defconst org-non-link-chars
"]\t\n\r<>")
5603 (defvar org-link-types
'("http" "https" "ftp" "mailto" "file" "file+emacs"
5604 "file+sys" "news" "shell" "elisp" "doi" "message"
5606 (defvar org-link-types-re nil
5607 "Matches a link that has a url-like prefix like \"http:\"")
5608 (defvar org-link-re-with-space nil
5609 "Matches a link with spaces, optional angular brackets around it.")
5610 (defvar org-link-re-with-space2 nil
5611 "Matches a link with spaces, optional angular brackets around it.")
5612 (defvar org-link-re-with-space3 nil
5613 "Matches a link with spaces, only for internal part in bracket links.")
5614 (defvar org-angle-link-re nil
5615 "Matches link with angular brackets, spaces are allowed.")
5616 (defvar org-plain-link-re nil
5617 "Matches plain link, without spaces.")
5618 (defvar org-bracket-link-regexp nil
5619 "Matches a link in double brackets.")
5620 (defvar org-bracket-link-analytic-regexp nil
5621 "Regular expression used to analyze links.
5622 Here is what the match groups contain after a match:
5628 (defvar org-bracket-link-analytic-regexp
++ nil
5629 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5630 (defvar org-any-link-re nil
5631 "Regular expression matching any link.")
5633 (defconst org-match-sexp-depth
3
5634 "Number of stacked braces for sub/superscript matching.")
5636 (defun org-create-multibrace-regexp (left right n
)
5637 "Create a regular expression which will match a balanced sexp.
5638 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5639 as single character strings.
5640 The regexp returned will match the entire expression including the
5641 delimiters. It will also define a single group which contains the
5642 match except for the outermost delimiters. The maximum depth of
5643 stacked delimiters is N. Escaping delimiters is not possible."
5644 (let* ((nothing (concat "[^" left right
"]*?"))
5647 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
5650 re
(concat re or next
)
5651 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
5652 (concat left
"\\(" re
"\\)" right
)))
5654 (defconst org-match-substring-regexp
5656 "\\(\\S-\\)\\([_^]\\)\\("
5657 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5659 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
5661 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5662 "The regular expression matching a sub- or superscript.")
5664 (defconst org-match-substring-with-braces-regexp
5666 "\\(\\S-\\)\\([_^]\\)"
5667 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)")
5668 "The regular expression matching a sub- or superscript, forcing braces.")
5670 (defun org-make-link-regexps ()
5671 "Update the link regular expressions.
5672 This should be called after the variable `org-link-types' has changed."
5673 (let ((types-re (regexp-opt org-link-types t
)))
5674 (setq org-link-types-re
5675 (concat "\\`" types-re
":")
5676 org-link-re-with-space
5677 (concat "<?" types-re
":"
5678 "\\([^" org-non-link-chars
" ]"
5679 "[^" org-non-link-chars
"]*"
5680 "[^" org-non-link-chars
" ]\\)>?")
5681 org-link-re-with-space2
5682 (concat "<?" types-re
":"
5683 "\\([^" org-non-link-chars
" ]"
5685 "[^" org-non-link-chars
" ]\\)>?")
5686 org-link-re-with-space3
5687 (concat "<?" types-re
":"
5688 "\\([^" org-non-link-chars
" ]"
5691 (concat "<" types-re
":"
5692 "\\([^" org-non-link-chars
" ]"
5693 "[^" org-non-link-chars
"]*"
5698 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5699 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5700 org-bracket-link-regexp
5701 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5702 org-bracket-link-analytic-regexp
5705 "\\(" types-re
":\\)?"
5708 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5710 org-bracket-link-analytic-regexp
++
5713 "\\(" (regexp-opt (cons "coderef" org-link-types
) t
) ":\\)?"
5716 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5719 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
5720 org-angle-link-re
"\\)\\|\\("
5721 org-plain-link-re
"\\)"))))
5723 (org-make-link-regexps)
5725 (defvar org-emph-face nil
)
5727 (defun org-do-emphasis-faces (limit)
5728 "Run through the buffer and emphasize strings."
5730 (while (and (not rtn
) (re-search-forward org-emph-re limit t
))
5731 (let* ((border (char-after (match-beginning 3)))
5732 (bre (regexp-quote (char-to-string border
))))
5733 (if (and (not (= border
(char-after (match-beginning 4))))
5734 (not (save-match-data
5735 (string-match (concat bre
".*" bre
)
5736 (replace-regexp-in-string
5738 (substring (match-string 2) 1 -
1))))))
5741 (setq a
(assoc (match-string 3) org-emphasis-alist
))
5742 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5746 (org-remove-flyspell-overlays-in
5747 (match-beginning 0) (match-end 0)))
5748 (add-text-properties (match-beginning 2) (match-end 2)
5749 '(font-lock-multiline t org-emphasis t
))
5750 (when org-hide-emphasis-markers
5751 (add-text-properties (match-end 4) (match-beginning 5)
5752 '(invisible org-link
))
5753 (add-text-properties (match-beginning 3) (match-end 3)
5754 '(invisible org-link
))))))
5755 (goto-char (1+ (match-beginning 0))))
5758 (defun org-emphasize (&optional char
)
5759 "Insert or change an emphasis, i.e. a font like bold or italic.
5760 If there is an active region, change that region to a new emphasis.
5761 If there is no region, just insert the marker characters and position
5762 the cursor between them.
5763 CHAR should be the marker character. If it is a space, it means to
5764 remove the emphasis of the selected region.
5765 If CHAR is not given (for example in an interactive call) it will be
5768 (let ((erc org-emphasis-regexp-components
)
5770 (string "") beg end move c s
)
5771 (if (org-region-active-p)
5772 (setq beg
(region-beginning) end
(region-end)
5773 string
(buffer-substring beg end
))
5777 (message "Emphasis marker or tag: [%s]"
5778 (mapconcat (lambda(e) (car e
)) org-emphasis-alist
""))
5779 (setq char
(read-char-exclusive)))
5780 (if (equal char ?\
)
5781 (setq s
"" move nil
)
5782 (unless (assoc (char-to-string char
) org-emphasis-alist
)
5783 (user-error "No such emphasis marker: \"%c\"" char
))
5784 (setq s
(char-to-string char
)))
5785 (while (and (> (length string
) 1)
5786 (equal (substring string
0 1) (substring string -
1))
5787 (assoc (substring string
0 1) org-emphasis-alist
))
5788 (setq string
(substring string
1 -
1)))
5789 (setq string
(concat s string s
))
5790 (if beg
(delete-region beg end
))
5792 (string-match (concat "[" (nth 0 erc
) "\n]")
5793 (char-to-string (char-before (point)))))
5796 (string-match (concat "[" (nth 1 erc
) "\n]")
5797 (char-to-string (char-after (point)))))
5798 (insert " ") (backward-char 1))
5800 (and move
(backward-char 1))))
5802 (defconst org-nonsticky-props
5803 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link
))
5805 (defsubst org-rear-nonsticky-at
(pos)
5806 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
5808 (defun org-activate-plain-links (limit)
5809 "Add link properties for plain links."
5811 (when (and (re-search-forward (concat org-plain-link-re
) limit t
)
5812 (not (member 'org-tag
5813 (get-text-property (1- (match-beginning 0)) 'face
)))
5814 (not (org-in-src-block-p)))
5815 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5816 (setq f
(get-text-property (match-beginning 0) 'face
))
5817 (setq hl
(org-match-string-no-properties 0))
5818 (if (or (eq f
'org-tag
)
5819 (and (listp f
) (memq 'org-tag f
)))
5821 (add-text-properties (match-beginning 0) (match-end 0)
5822 (list 'mouse-face
'highlight
5824 'htmlize-link
`(:uri
,hl
)
5825 'keymap org-mouse-map
))
5826 (org-rear-nonsticky-at (match-end 0)))
5829 (defun org-activate-code (limit)
5830 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t
)
5832 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5833 (remove-text-properties (match-beginning 0) (match-end 0)
5834 '(display t invisible t intangible t
))
5837 (defcustom org-src-fontify-natively t
5838 "When non-nil, fontify code in code blocks."
5841 :package-version
'(Org .
"8.3")
5842 :group
'org-appearance
5845 (defcustom org-allow-promoting-top-level-subtree nil
5846 "When non-nil, allow promoting a top level subtree.
5847 The leading star of the top level headline will be replaced
5851 :group
'org-appearance
)
5853 (defun org-fontify-meta-lines-and-blocks (limit)
5855 (org-fontify-meta-lines-and-blocks-1 limit
)
5856 (error (message "org-mode fontification error"))))
5858 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5859 "Fontify #+ lines and blocks."
5860 (let ((case-fold-search t
))
5861 (if (re-search-forward
5862 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5864 (let ((beg (match-beginning 0))
5865 (block-start (match-end 0))
5867 (lang (match-string 7))
5868 (beg1 (line-beginning-position 2))
5869 (dc1 (downcase (match-string 2)))
5870 (dc3 (downcase (match-string 3)))
5871 end end1 quoting block-type ovl
)
5873 ((member dc1
'("+html:" "+ascii:" "+latex:"))
5874 ;; a single line of backend-specific content
5875 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5876 (remove-text-properties (match-beginning 0) (match-end 0)
5877 '(display t invisible t intangible t
))
5878 (add-text-properties (match-beginning 1) (match-end 3)
5879 '(font-lock-fontified t face org-meta-line
))
5880 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5881 '(font-lock-fontified t face org-block
))
5882 ; for backend-specific code
5884 ((and (match-end 4) (equal dc3
"+begin"))
5886 (setq block-type
(downcase (match-string 5))
5887 quoting
(member block-type org-protecting-blocks
))
5888 (when (re-search-forward
5889 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5890 nil t
) ;; on purpose, we look further than LIMIT
5891 (setq end
(min (point-max) (match-end 0))
5892 end1
(min (point-max) (1- (match-beginning 0))))
5893 (setq block-end
(match-beginning 0))
5895 (org-remove-flyspell-overlays-in beg1 end1
)
5896 (remove-text-properties beg end
5897 '(display t invisible t intangible t
)))
5898 (add-text-properties
5899 beg end
'(font-lock-fontified t font-lock-multiline t
))
5900 (add-text-properties beg beg1
'(face org-meta-line
))
5901 (org-remove-flyspell-overlays-in beg beg1
)
5902 (add-text-properties ; For end_src
5903 end1
(min (point-max) (1+ end
)) '(face org-meta-line
))
5904 (org-remove-flyspell-overlays-in end1 end
)
5906 ((and lang
(not (string= lang
"")) org-src-fontify-natively
)
5907 (org-src-font-lock-fontify-block lang block-start block-end
)
5908 (add-text-properties beg1 block-end
'(src-block t
)))
5910 (add-text-properties beg1
(min (point-max) (1+ end1
))
5911 '(face org-block
))) ; end of source block
5912 ((not org-fontify-quote-and-verse-blocks
))
5913 ((string= block-type
"quote")
5914 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-quote
)))
5915 ((string= block-type
"verse")
5916 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-verse
))))
5917 (add-text-properties beg beg1
'(face org-block-begin-line
))
5918 (add-text-properties (min (point-max) (1+ end
)) (min (point-max) (1+ end1
))
5919 '(face org-block-end-line
))
5921 ((member dc1
'("+title:" "+author:" "+email:" "+date:"))
5922 (org-remove-flyspell-overlays-in
5924 (if (equal "+title:" dc1
) (match-end 2) (match-end 0)))
5925 (add-text-properties
5927 (if (member (intern (substring dc1
1 -
1)) org-hidden-keywords
)
5928 '(font-lock-fontified t invisible t
)
5929 '(font-lock-fontified t face org-document-info-keyword
)))
5930 (add-text-properties
5931 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5932 (if (string-equal dc1
"+title:")
5933 '(font-lock-fontified t face org-document-title
)
5934 '(font-lock-fontified t face org-document-info
))))
5935 ((or (equal dc1
"+results")
5936 (member dc1
'("+begin:" "+end:" "+caption:" "+label:"
5937 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5938 "+call:" "+header:" "+headers:" "+name:"))
5939 (and (match-end 4) (equal dc3
"+attr")))
5940 (org-remove-flyspell-overlays-in
5942 (if (equal "+caption:" dc1
) (match-end 2) (match-end 0)))
5943 (add-text-properties
5945 '(font-lock-fontified t face org-meta-line
))
5947 ((member dc3
'(" " ""))
5948 (org-remove-flyspell-overlays-in beg
(match-end 0))
5949 (add-text-properties
5951 '(font-lock-fontified t face font-lock-comment-face
)))
5952 (t ;; just any other in-buffer setting, but not indented
5953 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5954 (add-text-properties
5956 '(font-lock-fontified t face org-meta-line
))
5959 (defun org-fontify-drawers (limit)
5961 (when (re-search-forward org-drawer-regexp limit t
)
5962 (add-text-properties
5963 (match-beginning 0) (match-end 0)
5964 '(font-lock-fontified t face org-special-keyword
))
5965 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5968 (defun org-fontify-macros (limit)
5970 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t
)
5971 (add-text-properties
5972 (match-beginning 0) (match-end 0)
5973 '(font-lock-fontified t face org-macro
))
5974 (when org-hide-macro-markers
5975 (add-text-properties (match-end 2) (match-beginning 2)
5977 (add-text-properties (match-beginning 1) (match-end 1)
5979 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5982 (defun org-activate-angle-links (limit)
5983 "Add text properties for angle links."
5984 (if (and (re-search-forward org-angle-link-re limit t
)
5985 (not (org-in-src-block-p)))
5987 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5988 (add-text-properties (match-beginning 0) (match-end 0)
5989 (list 'mouse-face
'highlight
5990 'keymap org-mouse-map
))
5991 (org-rear-nonsticky-at (match-end 0))
5994 (defun org-activate-footnote-links (limit)
5995 "Add text properties for footnotes."
5996 (let ((fn (org-footnote-next-reference-or-definition limit
)))
5998 (let* ((beg (nth 1 fn
))
6001 (referencep (/= (line-beginning-position) beg
)))
6002 (when (and referencep
(nth 3 fn
))
6005 (search-forward (or label
"fn:"))
6006 (org-remove-flyspell-overlays-in beg
(match-end 0))))
6007 (add-text-properties beg end
6008 (list 'mouse-face
'highlight
6009 'keymap org-mouse-map
6011 (if referencep
"Footnote reference"
6012 "Footnote definition")
6013 'font-lock-fontified t
6014 'font-lock-multiline t
6015 'face
'org-footnote
))))))
6017 (defun org-activate-bracket-links (limit)
6018 "Add text properties for bracketed links."
6019 (if (and (re-search-forward org-bracket-link-regexp limit t
)
6020 (not (org-in-src-block-p)))
6021 (let* ((hl (org-match-string-no-properties 1))
6022 (help (concat "LINK: " (save-match-data (org-link-unescape hl
))))
6023 (ip (org-maybe-intangible
6024 (list 'invisible
'org-link
6025 'keymap org-mouse-map
'mouse-face
'highlight
6026 'font-lock-multiline t
'help-echo help
6027 'htmlize-link
`(:uri
,hl
))))
6028 (vp (list 'keymap org-mouse-map
'mouse-face
'highlight
6029 'font-lock-multiline t
'help-echo help
6030 'htmlize-link
`(:uri
,hl
))))
6031 ;; We need to remove the invisible property here. Table narrowing
6032 ;; may have made some of this invisible.
6033 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6034 (remove-text-properties (match-beginning 0) (match-end 0)
6038 (add-text-properties (match-beginning 0) (match-beginning 3) ip
)
6039 (org-rear-nonsticky-at (match-beginning 3))
6040 (add-text-properties (match-beginning 3) (match-end 3) vp
)
6041 (org-rear-nonsticky-at (match-end 3))
6042 (add-text-properties (match-end 3) (match-end 0) ip
)
6043 (org-rear-nonsticky-at (match-end 0)))
6044 (add-text-properties (match-beginning 0) (match-beginning 1) ip
)
6045 (org-rear-nonsticky-at (match-beginning 1))
6046 (add-text-properties (match-beginning 1) (match-end 1) vp
)
6047 (org-rear-nonsticky-at (match-end 1))
6048 (add-text-properties (match-end 1) (match-end 0) ip
)
6049 (org-rear-nonsticky-at (match-end 0)))
6052 (defun org-activate-dates (limit)
6053 "Add text properties for dates."
6054 (if (and (re-search-forward org-tsr-regexp-both limit t
)
6055 (not (equal (char-before (match-beginning 0)) 91)))
6057 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6058 (add-text-properties (match-beginning 0) (match-end 0)
6059 (list 'mouse-face
'highlight
6060 'keymap org-mouse-map
))
6061 (org-rear-nonsticky-at (match-end 0))
6062 (when org-display-custom-times
6064 (org-display-custom-time (match-beginning 3) (match-end 3)))
6065 (org-display-custom-time (match-beginning 1) (match-end 1)))
6068 (defvar org-target-link-regexp nil
6069 "Regular expression matching radio targets in plain text.")
6070 (make-variable-buffer-local 'org-target-link-regexp
)
6072 (defconst org-target-regexp
(let ((border "[^<>\n\r \t]"))
6073 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6074 border border border
))
6075 "Regular expression matching a link target.")
6077 (defconst org-radio-target-regexp
(format "<%s>" org-target-regexp
)
6078 "Regular expression matching a radio target.")
6080 (defconst org-any-target-regexp
6081 (format "%s\\|%s" org-radio-target-regexp org-target-regexp
)
6082 "Regular expression matching any target.")
6084 (defun org-activate-target-links (limit)
6085 "Add text properties for target matches."
6086 (when org-target-link-regexp
6087 (let ((case-fold-search t
))
6088 (if (re-search-forward org-target-link-regexp limit t
)
6090 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6091 (add-text-properties (match-beginning 1) (match-end 1)
6092 (list 'mouse-face
'highlight
6093 'keymap org-mouse-map
6094 'help-echo
"Radio target link"
6095 'org-linked-text t
))
6096 (org-rear-nonsticky-at (match-end 1))
6099 (defun org-update-radio-target-regexp ()
6100 "Find all radio targets in this file and update the regular expression.
6101 Also refresh fontification if needed."
6103 (let ((old-regexp org-target-link-regexp
)
6104 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6105 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6107 (org-with-wide-buffer
6108 (goto-char (point-min))
6110 (while (re-search-forward org-radio-target-regexp nil t
)
6111 ;; Make sure point is really within the object.
6113 (let ((obj (org-element-context)))
6114 (when (eq (org-element-type obj
) 'radio-target
)
6115 (add-to-list 'rtn
(org-element-property :value obj
)))))
6117 (setq org-target-link-regexp
6122 (replace-regexp-in-string
6123 " +" "\\s-+" (regexp-quote x
) t t
))
6127 (unless (equal old-regexp org-target-link-regexp
)
6129 (let ((regexp (cond ((not old-regexp
) org-target-link-regexp
)
6130 ((not org-target-link-regexp
) old-regexp
)
6135 (substring re
(length before-re
)
6136 (- (length after-re
))))
6137 (list old-regexp org-target-link-regexp
)
6140 (org-with-wide-buffer
6141 (goto-char (point-min))
6142 (while (re-search-forward regexp nil t
)
6143 (org-element-cache-refresh (match-beginning 1)))))
6144 ;; Re fontify buffer.
6145 (when (memq 'radio org-highlight-links
)
6146 (org-restart-font-lock)))))
6148 (defun org-hide-wide-columns (limit)
6150 (setq s
(text-property-any (point) (or limit
(point-max))
6153 (setq e
(next-single-property-change s
'org-cwidth
))
6154 (add-text-properties s e
(org-maybe-intangible '(invisible org-cwidth
)))
6158 (defvar org-latex-and-related-regexp nil
6159 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6161 (defun org-compute-latex-and-related-regexp ()
6162 "Compute regular expression for LaTeX, entities and sub/superscript.
6163 Result depends on variable `org-highlight-latex-and-related'."
6165 'org-latex-and-related-regexp
6167 (cond ((not (memq 'script org-highlight-latex-and-related
)) nil
)
6168 ((eq org-use-sub-superscripts
'{})
6169 (list org-match-substring-with-braces-regexp
))
6170 (org-use-sub-superscripts (list org-match-substring-regexp
))))
6172 (when (memq 'latex org-highlight-latex-and-related
)
6173 (let ((matchers (plist-get org-format-latex-options
:matchers
)))
6176 (and (member (car x
) matchers
) (nth 1 x
)))
6177 org-latex-regexps
)))))
6179 (when (memq 'entities org-highlight-latex-and-related
)
6180 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6181 (mapconcat 'identity
(append re-latex re-entities re-sub
) "\\|"))))
6183 (defun org-do-latex-and-related (limit)
6184 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6185 LIMIT bounds the search for syntax to highlight. Stop at first
6186 highlighted object, if any. Return t if some highlighting was
6187 done, nil otherwise."
6188 (when (org-string-nw-p org-latex-and-related-regexp
)
6190 (while (re-search-forward org-latex-and-related-regexp limit t
)
6191 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6193 '(org-code org-verbatim underline
))
6194 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6198 (font-lock-prepend-text-property
6199 (+ offset
(match-beginning 0)) (match-end 0)
6200 'face
'org-latex-and-related
)
6201 (add-text-properties (+ offset
(match-beginning 0)) (match-end 0)
6202 '(font-lock-multiline t
)))
6206 (defun org-restart-font-lock ()
6207 "Restart `font-lock-mode', to force refontification."
6208 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
6210 (font-lock-mode 1)))
6212 (defun org-activate-tags (limit)
6213 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t
)
6215 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6216 (add-text-properties (match-beginning 1) (match-end 1)
6217 (list 'mouse-face
'highlight
6218 'keymap org-mouse-map
))
6219 (org-rear-nonsticky-at (match-end 1))
6222 (defun org-outline-level ()
6223 "Compute the outline level of the heading at point.
6224 If this is called at a normal headline, the level is the number of stars.
6225 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6227 (if (not (ignore-errors (org-back-to-heading t
)))
6229 (looking-at org-outline-regexp
)
6230 (1- (- (match-end 0) (match-beginning 0))))))
6232 (defvar org-font-lock-keywords nil
)
6234 (defsubst org-re-property
(property &optional literal allow-null
)
6235 "Return a regexp matching a PROPERTY line.
6237 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6238 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6239 non-nil, match properties even without a value.
6241 Match group 3 is set to the value when it exists. If there is no
6242 value and ALLOW-NULL is non-nil, it is set to the empty string."
6245 (format "\\(?1::\\(?2:%s\\):\\)"
6246 (if literal property
(regexp-quote property
)))
6248 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6249 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6251 (defconst org-property-re
6252 (org-re-property "\\S-+" 'literal t
)
6253 "Regular expression matching a property line.
6254 There are four matching groups:
6255 1: :PROPKEY: including the leading and trailing colon,
6256 2: PROPKEY without the leading and trailing colon,
6257 3: PROPVAL without leading or trailing spaces,
6258 4: the indentation of the current line,
6259 5: trailing whitespace.")
6261 (defvar org-font-lock-hook nil
6262 "Functions to be called for special font lock stuff.")
6264 (defvar org-font-lock-set-keywords-hook nil
6265 "Functions that can manipulate `org-font-lock-extra-keywords'.
6266 This is called after `org-font-lock-extra-keywords' is defined, but before
6267 it is installed to be used by font lock. This can be useful if something
6268 needs to be inserted at a specific position in the font-lock sequence.")
6270 (defun org-font-lock-hook (limit)
6271 "Run `org-font-lock-hook' within LIMIT."
6272 (run-hook-with-args 'org-font-lock-hook limit
))
6274 (defun org-set-font-lock-defaults ()
6275 "Set font lock defaults for the current buffer."
6276 (let* ((em org-fontify-emphasized-text
)
6277 (lk org-highlight-links
)
6278 (org-font-lock-extra-keywords
6281 '(org-font-lock-hook)
6283 `(,(if org-fontify-whole-heading-line
6284 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6285 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6286 (1 (org-get-level-face 1))
6287 (2 (org-get-level-face 2))
6288 (3 (org-get-level-face 3)))
6290 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6293 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
6294 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
6295 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
6296 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t
))
6298 '(org-fontify-drawers)
6300 (list org-property-re
6301 '(1 'org-special-keyword t
)
6302 '(3 'org-property-value t
))
6304 (if (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
6305 (if (memq 'angle lk
) '(org-activate-angle-links (0 'org-link t
)))
6306 (if (memq 'plain lk
) '(org-activate-plain-links (0 'org-link t
)))
6307 (if (memq 'bracket lk
) '(org-activate-bracket-links (0 'org-link t
)))
6308 (if (memq 'radio lk
) '(org-activate-target-links (1 'org-link t
)))
6309 (if (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
6310 (if (memq 'footnote lk
) '(org-activate-footnote-links))
6312 (list org-any-target-regexp
'(0 'org-target t
))
6314 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
6316 '(org-fontify-macros)
6317 '(org-hide-wide-columns (0 nil append
))
6319 (list (format org-heading-keyword-regexp-format
6321 '(2 (org-get-todo-face 2) t
))
6323 (if org-fontify-done-headline
6324 (list (format org-heading-keyword-regexp-format
6327 (mapconcat 'regexp-quote org-done-keywords
"\\|")
6329 '(2 'org-headline-done t
))
6332 '(org-font-lock-add-priority-faces)
6334 '(org-font-lock-add-tag-faces)
6336 (if (and org-group-tags org-tag-groups-alist
)
6337 (list (concat org-outline-regexp-bol
".+\\(:"
6338 (regexp-opt (mapcar 'car org-tag-groups-alist
))
6340 '(1 'org-tag-group prepend
)))
6342 (list (concat "\\<" org-comment-string
) '(0 'org-special-keyword t
))
6343 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
6344 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
6345 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
6346 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
6349 (if (featurep 'xemacs
)
6350 '(org-do-emphasis-faces (0 nil append
))
6351 '(org-do-emphasis-faces)))
6353 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6354 1 'org-checkbox prepend
)
6355 (if (cdr (assq 'checkbox org-list-automatic-rules
))
6356 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6357 (0 (org-get-checkbox-statistics-face) t
)))
6358 ;; Description list items
6359 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6360 1 'org-list-dt prepend
)
6361 ;; ARCHIVEd headings
6363 org-outline-regexp-bol
6364 "\\(.*:" org-archive-tag
":.*\\)")
6365 '(1 'org-archived prepend
))
6367 '(org-do-latex-and-related)
6368 '(org-fontify-entities)
6369 '(org-raise-scripts)
6371 '(org-activate-code (1 'org-code t
))
6374 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6377 '(9 'org-special-keyword t
))
6378 ;; Blocks and meta lines
6379 '(org-fontify-meta-lines-and-blocks))))
6380 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
6381 (run-hooks 'org-font-lock-set-keywords-hook
)
6382 ;; Now set the full font-lock-keywords
6383 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords
)
6384 (org-set-local 'font-lock-defaults
6385 '(org-font-lock-keywords t nil nil backward-paragraph
))
6386 (kill-local-variable 'font-lock-keywords
) nil
))
6388 (defun org-toggle-pretty-entities ()
6389 "Toggle the composition display of entities as UTF8 characters."
6391 (org-set-local 'org-pretty-entities
(not org-pretty-entities
))
6392 (org-restart-font-lock)
6393 (if org-pretty-entities
6394 (message "Entities are now displayed as UTF8 characters")
6397 (org-decompose-region (point-min) (point-max))
6398 (message "Entities are now displayed as plain text"))))
6400 (defvar org-custom-properties-overlays nil
6401 "List of overlays used for custom properties.")
6402 (make-variable-buffer-local 'org-custom-properties-overlays
)
6404 (defun org-toggle-custom-properties-visibility ()
6405 "Display or hide properties in `org-custom-properties'."
6407 (if org-custom-properties-overlays
6408 (progn (mapc 'delete-overlay org-custom-properties-overlays
)
6409 (setq org-custom-properties-overlays nil
))
6410 (unless (not org-custom-properties
)
6414 (goto-char (point-min))
6415 (while (re-search-forward org-property-re nil t
)
6417 (when (equal p
(substring (match-string 1) 1 -
1))
6418 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6419 (overlay-put o
'invisible t
)
6420 (overlay-put o
'org-custom-property t
)
6421 (push o org-custom-properties-overlays
))))
6422 org-custom-properties
)))))))
6424 (defun org-fontify-entities (limit)
6425 "Find an entity to fontify."
6427 (when org-pretty-entities
6429 (while (re-search-forward
6430 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6432 (if (and (not (org-at-comment-p))
6433 (setq ee
(org-entity-get (match-string 1)))
6434 (= (length (nth 6 ee
)) 1))
6436 ((end (if (equal (match-string 2) "{}")
6439 (add-text-properties
6440 (match-beginning 0) end
6441 (list 'font-lock-fontified t
))
6442 (compose-region (match-beginning 0) end
6448 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
6449 "Fontify string S like in Org-mode."
6452 (let ((org-odd-levels-only odd-levels
))
6460 (defun org-get-level-face (n)
6461 "Get the right face for match N in font-lock matching of headlines."
6462 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
6463 (if org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
6464 (if org-cycle-level-faces
6465 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
6466 (setq org-f
(nth (1- (min org-l org-n-level-faces
)) org-level-faces
)))
6468 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
6470 (t (if org-level-color-stars-only nil org-f
))))
6473 (defun org-get-todo-face (kwd)
6474 "Get the right face for a TODO keyword KWD.
6475 If KWD is a number, get the corresponding match group."
6476 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
6477 (or (org-face-from-face-or-color
6478 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
6479 (and (member kwd org-done-keywords
) 'org-done
)
6482 (defun org-face-from-face-or-color (context inherit face-or-color
)
6483 "Create a face list that inherits INHERIT, but sets the foreground color.
6484 When FACE-OR-COLOR is not a string, just return it."
6485 (if (stringp face-or-color
)
6486 (list :inherit inherit
6487 (cdr (assoc context org-faces-easy-properties
))
6491 (defun org-font-lock-add-tag-faces (limit)
6492 "Add the special tag faces."
6493 (when (and org-tag-faces org-tags-special-faces-re
)
6494 (while (re-search-forward org-tags-special-faces-re limit t
)
6495 (add-text-properties (match-beginning 1) (match-end 1)
6496 (list 'face
(org-get-tag-face 1)
6497 'font-lock-fontified t
))
6498 (backward-char 1))))
6500 (defun org-font-lock-add-priority-faces (limit)
6501 "Add the special priority faces."
6502 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t
)
6503 (when (save-match-data (org-at-heading-p))
6504 (add-text-properties
6505 (match-beginning 0) (match-end 0)
6506 (list 'face
(or (org-face-from-face-or-color
6507 'priority
'org-priority
6508 (cdr (assoc (char-after (match-beginning 1))
6509 org-priority-faces
)))
6511 'font-lock-fontified t
)))))
6513 (defun org-get-tag-face (kwd)
6514 "Get the right face for a TODO keyword KWD.
6515 If KWD is a number, get the corresponding match group."
6516 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
6517 (or (org-face-from-face-or-color
6518 'tag
'org-tag
(cdr (assoc kwd org-tag-faces
)))
6521 (defun org-unfontify-region (beg end
&optional maybe_loudly
)
6522 "Remove fontification and activation overlays from links."
6523 (font-lock-default-unfontify-region beg end
)
6524 (let* ((buffer-undo-list t
)
6525 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
6526 (inhibit-modification-hooks t
)
6527 deactivate-mark buffer-file-name buffer-file-truename
)
6528 (org-decompose-region beg end
)
6529 (remove-text-properties beg end
6530 '(mouse-face t keymap t org-linked-text t
6531 invisible t intangible t
6533 (org-remove-font-lock-display-properties beg end
)))
6535 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
6536 ((raise 0.3) (height 0.7))
6539 "Display properties for showing superscripts and subscripts.")
6541 (defun org-remove-font-lock-display-properties (beg end
)
6542 "Remove specific display properties that have been added by font lock.
6543 The will remove the raise properties that are used to show superscripts
6547 (setq next
(next-single-property-change beg
'display nil end
)
6548 prop
(get-text-property beg
'display
))
6549 (if (member prop org-script-display
)
6550 (put-text-property beg next
'display nil
))
6553 (defun org-raise-scripts (limit)
6554 "Add raise properties to sub/superscripts."
6555 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
)
6556 (if (re-search-forward
6557 (if (eq org-use-sub-superscripts t
)
6558 org-match-substring-regexp
6559 org-match-substring-with-braces-regexp
)
6561 (let* ((pos (point)) table-p comment-p
6562 (mpos (match-beginning 3))
6563 (emph-p (get-text-property mpos
'org-emphasis
))
6564 (link-p (get-text-property mpos
'mouse-face
))
6565 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
6566 (goto-char (point-at-bol))
6567 (setq table-p
(org-looking-at-p org-table-dataline-regexp
)
6568 comment-p
(org-looking-at-p "^[ \t]*#[ +]"))
6571 (if (member (char-after) '(?_ ?^
)) (goto-char (1- pos
)))
6572 (if (or comment-p emph-p link-p keyw-p
)
6574 (put-text-property (match-beginning 3) (match-end 0)
6576 (if (equal (char-after (match-beginning 2)) ?^
)
6577 (nth (if table-p
3 1) org-script-display
)
6578 (nth (if table-p
2 0) org-script-display
)))
6579 (add-text-properties (match-beginning 2) (match-end 2)
6581 'org-dwidth t
'org-dwidth-n
1))
6582 (if (and (eq (char-after (match-beginning 3)) ?
{)
6583 (eq (char-before (match-end 3)) ?
}))
6585 (add-text-properties
6586 (match-beginning 3) (1+ (match-beginning 3))
6587 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))
6588 (add-text-properties
6589 (1- (match-end 3)) (match-end 3)
6590 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))))
6593 ;;;; Visibility cycling, including org-goto and indirect buffer
6597 (defvar org-cycle-global-status nil
)
6598 (make-variable-buffer-local 'org-cycle-global-status
)
6599 (put 'org-cycle-global-status
'org-state t
)
6600 (defvar org-cycle-subtree-status nil
)
6601 (make-variable-buffer-local 'org-cycle-subtree-status
)
6602 (put 'org-cycle-subtree-status
'org-state t
)
6604 (defvar org-inlinetask-min-level
)
6606 (defun org-unlogged-message (&rest args
)
6607 "Display a message, but avoid logging it in the *Messages* buffer."
6608 (let ((message-log-max nil
))
6609 (apply 'message args
)))
6612 (defun org-cycle (&optional arg
)
6613 "TAB-action and visibility cycling for Org-mode.
6615 This is the command invoked in Org-mode by the TAB key. Its main purpose
6616 is outline visibility cycling, but it also invokes other actions
6617 in special contexts.
6619 - When this function is called with a prefix argument, rotate the entire
6620 buffer through 3 states (global cycling)
6621 1. OVERVIEW: Show only top-level headlines.
6622 2. CONTENTS: Show all headlines of all levels, but no body text.
6623 3. SHOW ALL: Show everything.
6624 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6625 determined by the variable `org-startup-folded', and by any VISIBILITY
6626 properties in the buffer.
6627 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6628 including any drawers.
6630 - When inside a table, re-align the table and move to the next field.
6632 - When point is at the beginning of a headline, rotate the subtree started
6633 by this line through 3 different states (local cycling)
6634 1. FOLDED: Only the main headline is shown.
6635 2. CHILDREN: The main headline and the direct children are shown.
6636 From this state, you can move to one of the children
6637 and zoom in further.
6638 3. SUBTREE: Show the entire subtree, including body text.
6639 If there is no subtree, switch directly from CHILDREN to FOLDED.
6641 - When point is at the beginning of an empty headline and the variable
6642 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6643 of the headline by demoting and promoting it to likely levels. This
6644 speeds up creation document structure by pressing TAB once or several
6645 times right after creating a new headline.
6647 - When there is a numeric prefix, go up to a heading with level ARG, do
6648 a `show-subtree' and return to the previous cursor position. If ARG
6649 is negative, go up that many levels.
6651 - When point is not at the beginning of a headline, execute the global
6652 binding for TAB, which is re-indenting the line. See the option
6653 `org-cycle-emulate-tab' for details.
6655 - Special case: if point is at the beginning of the buffer and there is
6656 no headline in line 1, this function will act as if called with prefix arg
6657 (C-u TAB, same as S-TAB) also when called without prefix arg.
6658 But only if also the variable `org-cycle-global-at-bob' is t."
6660 (org-load-modules-maybe)
6661 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
6662 (and org-cycle-level-after-item
/entry-creation
6663 (or (org-cycle-level)
6664 (org-cycle-item-indentation))))
6666 (or org-cycle-max-level
6667 (and (boundp 'org-inlinetask-min-level
)
6668 org-inlinetask-min-level
6669 (1- org-inlinetask-min-level
))))
6670 (nstars (and limit-level
6671 (if org-odd-levels-only
6672 (and limit-level
(1- (* limit-level
2)))
6675 (if (not (derived-mode-p 'org-mode
))
6677 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ "))))
6678 (bob-special (and org-cycle-global-at-bob
(not arg
) (bobp)
6679 (not (looking-at org-outline-regexp
))))
6682 (delq 'org-optimize-window-after-visibility-change
6683 (copy-sequence org-cycle-hook
))
6687 (if (or bob-special
(equal arg
'(4)))
6688 ;; special case: use global cycling
6694 (setq last-command
'dummy
)
6695 (org-set-startup-visibility)
6696 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6700 (org-unlogged-message "Entire buffer visible, including drawers"))
6702 ;; Try cdlatex TAB completion
6703 ((org-try-cdlatex-tab))
6705 ;; Table: enter it or move to the next field.
6706 ((org-at-table-p 'any
)
6707 (if (org-at-table.el-p
)
6708 (message "Use C-c ' to edit table.el tables")
6709 (if arg
(org-table-edit-field t
)
6710 (org-table-justify-field-maybe)
6711 (call-interactively 'org-table-next-field
))))
6713 ((run-hook-with-args-until-success
6714 'org-tab-after-check-for-table-hook
))
6716 ;; Global cycling: delegate to `org-cycle-internal-global'.
6717 ((eq arg t
) (org-cycle-internal-global))
6719 ;; Drawers: delegate to `org-flag-drawer'.
6721 (beginning-of-line 1)
6722 (looking-at org-drawer-regexp
))
6723 (org-flag-drawer ; toggle block visibility
6724 (not (get-char-property (match-end 0) 'invisible
))))
6726 ;; Show-subtree, ARG levels up from here.
6729 (org-back-to-heading)
6730 (outline-up-heading (if (< arg
0) (- arg
)
6731 (- (funcall outline-level
) arg
)))
6732 (org-show-subtree)))
6734 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6735 ((and (featurep 'org-inlinetask
)
6736 (org-inlinetask-at-task-p)
6737 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6738 (org-inlinetask-toggle-visibility))
6740 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6741 ((and (or (and org-cycle-include-plain-lists
(org-at-item-p))
6742 (save-excursion (beginning-of-line 1)
6743 (looking-at org-outline-regexp
)))
6744 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6745 (org-cycle-internal-local))
6747 ;; From there: TAB emulation and template completion.
6748 (buffer-read-only (org-back-to-heading))
6750 ((run-hook-with-args-until-success
6751 'org-tab-after-check-for-cycling-hook
))
6753 ((org-try-structure-completion))
6755 ((run-hook-with-args-until-success
6756 'org-tab-before-tab-emulation-hook
))
6758 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
6760 (not (looking-at org-outline-regexp
))))
6761 (call-interactively (global-key-binding "\t")))
6763 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
6764 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6765 (or (and (eq org-cycle-emulate-tab
'white
)
6766 (= (match-end 0) (point-at-eol)))
6767 (and (eq org-cycle-emulate-tab
'whitestart
)
6768 (>= (match-end 0) pos
))))
6770 (eq org-cycle-emulate-tab t
))
6771 (call-interactively (global-key-binding "\t")))
6774 (org-back-to-heading)
6777 (defun org-cycle-internal-global ()
6778 "Do the global cycling action."
6779 ;; Hack to avoid display of messages for .org attachments in Gnus
6780 (let ((ga (string-match "\\*fontification" (buffer-name))))
6782 ((and (eq last-command this-command
)
6783 (eq org-cycle-global-status
'overview
))
6784 ;; We just created the overview - now do table of contents
6785 ;; This can be slow in very large buffers, so indicate action
6786 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
6787 (unless ga
(org-unlogged-message "CONTENTS..."))
6789 (unless ga
(org-unlogged-message "CONTENTS...done"))
6790 (setq org-cycle-global-status
'contents
)
6791 (run-hook-with-args 'org-cycle-hook
'contents
))
6793 ((and (eq last-command this-command
)
6794 (eq org-cycle-global-status
'contents
))
6795 ;; We just showed the table of contents - now show everything
6796 (run-hook-with-args 'org-pre-cycle-hook
'all
)
6798 (unless ga
(org-unlogged-message "SHOW ALL"))
6799 (setq org-cycle-global-status
'all
)
6800 (run-hook-with-args 'org-cycle-hook
'all
))
6803 ;; Default action: go to overview
6804 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
6806 (unless ga
(org-unlogged-message "OVERVIEW"))
6807 (setq org-cycle-global-status
'overview
)
6808 (run-hook-with-args 'org-cycle-hook
'overview
)))))
6810 (defvar org-called-with-limited-levels nil
6811 "Non-nil when `org-with-limited-levels' is currently active.")
6813 (defun org-cycle-internal-local ()
6814 "Do the local cycling action."
6815 (let ((goal-column 0) eoh eol eos has-children children-skipped struct
)
6816 ;; First, determine end of headline (EOH), end of subtree or item
6817 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6822 (setq struct
(org-list-struct))
6823 (setq eoh
(point-at-eol))
6824 (setq eos
(org-list-get-item-end-before-blank (point) struct
))
6825 (setq has-children
(org-list-has-child-p (point) struct
)))
6826 (org-back-to-heading)
6827 (setq eoh
(save-excursion (outline-end-of-heading) (point)))
6828 (setq eos
(save-excursion (org-end-of-subtree t t
)
6829 (when (bolp) (backward-char)) (point)))
6832 (let ((level (funcall outline-level
)))
6833 (outline-next-heading)
6834 (and (org-at-heading-p t
)
6835 (> (funcall outline-level
) level
))))
6837 (org-list-search-forward (org-item-beginning-re) eos t
)))))
6838 ;; Determine end invisible part of buffer (EOL)
6839 (beginning-of-line 2)
6840 ;; XEmacs doesn't have `next-single-char-property-change'
6841 (if (featurep 'xemacs
)
6842 (while (and (not (eobp)) ;; this is like `next-line'
6843 (get-char-property (1- (point)) 'invisible
))
6844 (beginning-of-line 2))
6845 (while (and (not (eobp)) ;; this is like `next-line'
6846 (get-char-property (1- (point)) 'invisible
))
6847 (goto-char (next-single-char-property-change (point) 'invisible
))
6848 (and (eolp) (beginning-of-line 2))))
6850 ;; Find out what to do next and set `this-command'
6853 ;; Nothing is hidden behind this heading
6854 (unless (org-before-first-heading-p)
6855 (run-hook-with-args 'org-pre-cycle-hook
'empty
))
6856 (org-unlogged-message "EMPTY ENTRY")
6857 (setq org-cycle-subtree-status nil
)
6860 (outline-next-heading)
6861 (if (outline-invisible-p) (org-flag-heading nil
))))
6862 ((and (or (>= eol eos
)
6863 (not (string-match "\\S-" (buffer-substring eol eos
))))
6865 (not (setq children-skipped
6866 org-cycle-skip-children-state-if-no-children
))))
6867 ;; Entire subtree is hidden in one line: children view
6868 (unless (org-before-first-heading-p)
6869 (run-hook-with-args 'org-pre-cycle-hook
'children
))
6871 (org-list-set-item-visibility (point-at-bol) struct
'children
)
6873 (org-with-limited-levels (show-children))
6874 ;; FIXME: This slows down the func way too much.
6875 ;; How keep drawers hidden in subtree anyway?
6876 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6877 ;; (org-cycle-hide-drawers 'subtree))
6879 ;; Fold every list in subtree to top-level items.
6880 (when (eq org-cycle-include-plain-lists
'integrate
)
6882 (org-back-to-heading)
6883 (while (org-list-search-forward (org-item-beginning-re) eos t
)
6884 (beginning-of-line 1)
6885 (let* ((struct (org-list-struct))
6886 (prevs (org-list-prevs-alist struct
))
6887 (end (org-list-get-bottom-point struct
)))
6888 (mapc (lambda (e) (org-list-set-item-visibility e struct
'folded
))
6889 (org-list-get-all-items (point) struct prevs
))
6890 (goto-char (if (< end eos
) end eos
)))))))
6891 (org-unlogged-message "CHILDREN")
6894 (outline-next-heading)
6895 (if (outline-invisible-p) (org-flag-heading nil
)))
6896 (setq org-cycle-subtree-status
'children
)
6897 (unless (org-before-first-heading-p)
6898 (run-hook-with-args 'org-cycle-hook
'children
)))
6899 ((or children-skipped
6900 (and (eq last-command this-command
)
6901 (eq org-cycle-subtree-status
'children
)))
6902 ;; We just showed the children, or no children are there,
6903 ;; now show everything.
6904 (unless (org-before-first-heading-p)
6905 (run-hook-with-args 'org-pre-cycle-hook
'subtree
))
6906 (outline-flag-region eoh eos nil
)
6907 (org-unlogged-message
6908 (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
6909 (setq org-cycle-subtree-status
'subtree
)
6910 (unless (org-before-first-heading-p)
6911 (run-hook-with-args 'org-cycle-hook
'subtree
)))
6913 ;; Default action: hide the subtree.
6914 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
6915 (outline-flag-region eoh eos t
)
6916 (org-unlogged-message "FOLDED")
6917 (setq org-cycle-subtree-status
'folded
)
6918 (unless (org-before-first-heading-p)
6919 (run-hook-with-args 'org-cycle-hook
'folded
))))))
6922 (defun org-global-cycle (&optional arg
)
6923 "Cycle the global visibility. For details see `org-cycle'.
6924 With \\[universal-argument] prefix arg, switch to startup visibility.
6925 With a numeric prefix, show all headlines up to that level."
6927 (let ((org-cycle-include-plain-lists
6928 (if (derived-mode-p 'org-mode
) org-cycle-include-plain-lists nil
)))
6932 (hide-sublevels arg
)
6933 (setq org-cycle-global-status
'contents
))
6935 (org-set-startup-visibility)
6936 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6938 (org-cycle '(4))))))
6940 (defun org-set-startup-visibility ()
6941 "Set the visibility required by startup options and properties."
6943 ((eq org-startup-folded t
)
6945 ((eq org-startup-folded
'content
)
6947 ((or (eq org-startup-folded
'showeverything
)
6948 (eq org-startup-folded nil
))
6950 (unless (eq org-startup-folded
'showeverything
)
6951 (if org-hide-block-startup
(org-hide-block-all))
6952 (org-set-visibility-according-to-property 'no-cleanup
)
6953 (org-cycle-hide-archived-subtrees 'all
)
6954 (org-cycle-hide-drawers 'all
)
6955 (org-cycle-show-empty-lines t
)))
6957 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
6958 "Switch subtree visibilities according to :VISIBILITY: property."
6960 (let (org-show-entry-below state
)
6962 (goto-char (point-min))
6963 (while (re-search-forward
6964 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6966 (setq state
(match-string 1))
6968 (org-back-to-heading t
)
6972 ((equal state
'("fold" "folded"))
6974 ((equal state
"children")
6975 (org-show-hidden-entry)
6977 ((equal state
"content")
6980 (org-narrow-to-subtree)
6982 ((member state
'("all" "showall"))
6985 (org-cycle-hide-archived-subtrees 'all
)
6986 (org-cycle-hide-drawers 'all
)
6987 (org-cycle-show-empty-lines 'all
)))))
6989 ;; This function uses outline-regexp instead of the more fundamental
6990 ;; org-outline-regexp so that org-cycle-global works outside of Org
6991 ;; buffers, where outline-regexp is needed.
6992 (defun org-overview ()
6993 "Switch to overview mode, showing only top-level headlines.
6994 This shows all headlines with a level equal or greater than the level
6995 of the first headline in the buffer. This is important, because if the
6996 first headline is not level one, then (hide-sublevels 1) gives confusing
7002 (goto-char (point-min))
7003 (if (re-search-forward (concat "^" outline-regexp
) nil t
)
7005 (goto-char (match-beginning 0))
7006 (funcall outline-level
))))))
7007 (and level
(hide-sublevels level
)))))
7009 (defun org-content (&optional arg
)
7010 "Show all headlines in the buffer, like a table of contents.
7011 With numerical argument N, show content up to level N."
7015 ;; Visit all headings and show their offspring
7016 (and (integerp arg
) (org-overview))
7017 (goto-char (point-max))
7019 (while (and (progn (condition-case nil
7020 (outline-previous-visible-heading 1)
7021 (error (goto-char (point-min))))
7023 (looking-at org-outline-regexp
))
7025 (show-children (1- arg
))
7027 (if (bobp) (throw 'exit nil
))))))
7029 (defun org-optimize-window-after-visibility-change (state)
7030 "Adjust the window after a change in outline visibility.
7031 This function is the default value of the hook `org-cycle-hook'."
7032 (when (get-buffer-window (current-buffer))
7034 ((eq state
'content
) nil
)
7035 ((eq state
'all
) nil
)
7036 ((eq state
'folded
) nil
)
7037 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
7038 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
7040 (defun org-remove-empty-overlays-at (pos)
7041 "Remove outline overlays that do not contain non-white stuff."
7044 (and (eq 'outline
(overlay-get o
'invisible
))
7045 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
7047 (delete-overlay o
)))
7050 (defun org-clean-visibility-after-subtree-move ()
7051 "Fix visibility issues after moving a subtree."
7052 ;; First, find a reasonable region to look at:
7053 ;; Start two siblings above, end three below
7054 (let* ((beg (save-excursion
7055 (and (org-get-last-sibling)
7056 (org-get-last-sibling))
7058 (end (save-excursion
7059 (and (org-get-next-sibling)
7060 (org-get-next-sibling)
7061 (org-get-next-sibling))
7062 (if (org-at-heading-p)
7065 (level (looking-at "\\*+"))
7066 (re (if level
(concat "^" (regexp-quote (match-string 0)) " "))))
7069 (narrow-to-region beg end
)
7071 ;; Properly fold already folded siblings
7072 (goto-char (point-min))
7073 (while (re-search-forward re nil t
)
7074 (if (and (not (outline-invisible-p))
7076 (goto-char (point-at-eol)) (outline-invisible-p)))
7078 (org-cycle-show-empty-lines 'overview
)
7079 (org-cycle-hide-drawers 'overview
)))))
7081 (defun org-cycle-show-empty-lines (state)
7082 "Show empty lines above all visible headlines.
7083 The region to be covered depends on STATE when called through
7084 `org-cycle-hook'. Lisp program can use t for STATE to get the
7085 entire buffer covered. Note that an empty line is only shown if there
7086 are at least `org-cycle-separator-lines' empty lines before the headline."
7087 (when (not (= org-cycle-separator-lines
0))
7089 (let* ((n (abs org-cycle-separator-lines
))
7091 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
7092 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7093 (t (let ((ns (number-to-string (- n
2))))
7094 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
7095 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7098 ((memq state
'(overview contents t
))
7099 (setq beg
(point-min) end
(point-max)))
7100 ((memq state
'(children folded
))
7101 (setq beg
(point) end
(progn (org-end-of-subtree t t
)
7102 (beginning-of-line 2)
7106 (while (re-search-forward re end t
)
7107 (unless (get-char-property (match-end 1) 'invisible
)
7108 (setq e
(match-end 1))
7109 (if (< org-cycle-separator-lines
0)
7110 (setq b
(save-excursion
7111 (goto-char (match-beginning 0))
7112 (org-back-over-empty-lines)
7114 (goto-char (max (point-min) (1- (point))))
7118 (setq b
(match-beginning 1)))
7119 (outline-flag-region b e nil
)))))))
7120 ;; Never hide empty lines at the end of the file.
7122 (goto-char (point-max))
7123 (outline-previous-heading)
7124 (outline-end-of-heading)
7125 (if (and (looking-at "[ \t\n]+")
7126 (= (match-end 0) (point-max)))
7127 (outline-flag-region (point) (match-end 0) nil
))))
7129 (defun org-show-empty-lines-in-parent ()
7130 "Move to the parent and re-show empty lines before visible headlines."
7132 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
7133 (org-cycle-show-empty-lines context
))))
7135 (defun org-files-list ()
7136 "Return `org-agenda-files' list, plus all open org-mode files.
7137 This is useful for operations that need to scan all of a user's
7138 open and agenda-wise Org files."
7139 (let ((files (mapcar 'expand-file-name
(org-agenda-files))))
7140 (dolist (buf (buffer-list))
7141 (with-current-buffer buf
7142 (if (and (derived-mode-p 'org-mode
) (buffer-file-name))
7143 (let ((file (expand-file-name (buffer-file-name))))
7144 (unless (member file files
)
7145 (push file files
))))))
7148 (defsubst org-entry-beginning-position
()
7149 "Return the beginning position of the current entry."
7150 (save-excursion (outline-back-to-heading t
) (point)))
7152 (defsubst org-entry-end-position
()
7153 "Return the end position of the current entry."
7154 (save-excursion (outline-next-heading) (point)))
7156 (defun org-cycle-hide-drawers (state &optional exceptions
)
7157 "Re-hide all drawers after a visibility state change.
7158 When non-nil, optional argument EXCEPTIONS is a list of strings
7159 specifying which drawers should not be hidden."
7160 (when (and (derived-mode-p 'org-mode
)
7161 (not (memq state
'(overview folded contents
))))
7163 (let* ((globalp (memq state
'(contents all
)))
7164 (beg (if globalp
(point-min) (point)))
7165 (end (if globalp
(point-max)
7166 (if (eq state
'children
)
7167 (save-excursion (outline-next-heading) (point))
7168 (org-end-of-subtree t
)))))
7170 (while (re-search-forward org-drawer-regexp
(max end
(point)) t
)
7171 (unless (member-ignore-case (match-string 1) exceptions
)
7172 (let ((drawer (org-element-at-point)))
7173 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7174 (org-flag-drawer t drawer
)
7175 ;; Make sure to skip drawer entirely or we might flag
7176 ;; it another time when matching its ending line with
7177 ;; `org-drawer-regexp'.
7178 (goto-char (org-element-property :end drawer
))))))))))
7180 (defun org-cycle-hide-inline-tasks (state)
7181 "Re-hide inline tasks when switching to 'contents or 'children
7185 (when (org-bound-and-true-p org-inlinetask-min-level
)
7186 (hide-sublevels (1- org-inlinetask-min-level
))))
7188 (when (featurep 'org-inlinetask
)
7190 (while (and (outline-next-heading)
7191 (org-inlinetask-at-task-p))
7192 (org-inlinetask-toggle-visibility)
7193 (org-inlinetask-goto-end)))))))
7195 (defun org-flag-drawer (flag &optional element
)
7196 "When FLAG is non-nil, hide the drawer we are at.
7197 Otherwise make it visible. When optional argument ELEMENT is
7198 a parsed drawer, as returned by `org-element-at-point', hide or
7199 show that drawer instead."
7200 (when (save-excursion
7202 (org-looking-at-p org-drawer-regexp
))
7203 (let ((drawer (or element
(org-element-at-point))))
7204 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7205 (let ((post (org-element-property :post-affiliated drawer
)))
7207 (outline-flag-region
7208 (progn (goto-char post
) (line-end-position))
7209 (progn (goto-char (org-element-property :end drawer
))
7210 (skip-chars-backward " \r\t\n")
7211 (line-end-position))
7213 ;; When the drawer is hidden away, make sure point lies in
7214 ;; a visible part of the buffer.
7215 (when (and flag
(> (line-beginning-position) post
))
7216 (goto-char post
)))))))
7218 (defun org-subtree-end-visible-p ()
7219 "Is the end of the current subtree visible?"
7220 (pos-visible-in-window-p
7221 (save-excursion (org-end-of-subtree t
) (point))))
7223 (defun org-first-headline-recenter ()
7224 "Move cursor to the first headline and recenter the headline."
7225 (goto-char (point-min))
7226 (when (re-search-forward (concat "^\\(" org-outline-regexp
"\\)") nil t
)
7227 (set-window-start (selected-window) (point-at-bol))))
7229 ;;; Saving and restoring visibility
7231 (defun org-outline-overlay-data (&optional use-markers
)
7232 "Return a list of the locations of all outline overlays.
7233 These are overlays with the `invisible' property value `outline'.
7234 The return value is a list of cons cells, with start and stop
7235 positions for each overlay.
7236 If USE-MARKERS is set, return the positions as markers."
7243 (when (eq (overlay-get o
'invisible
) 'outline
)
7244 (setq beg
(overlay-start o
)
7245 end
(overlay-end o
))
7246 (and beg end
(> end beg
)
7248 (cons (copy-marker beg
)
7249 (copy-marker end t
))
7251 (overlays-in (point-min) (point-max))))))))
7253 (defun org-set-outline-overlay-data (data)
7254 "Create visibility overlays for all positions in DATA.
7255 DATA should have been made by `org-outline-overlay-data'."
7262 (outline-flag-region (car c
) (cdr c
) t
))
7265 ;;; Folding of blocks
7267 (defvar org-hide-block-overlays nil
7268 "Overlays hiding blocks.")
7269 (make-variable-buffer-local 'org-hide-block-overlays
)
7271 (defun org-block-map (function &optional start end
)
7272 "Call FUNCTION at the head of all source blocks in the current buffer.
7273 Optional arguments START and END can be used to limit the range."
7274 (let ((start (or start
(point-min)))
7275 (end (or end
(point-max))))
7278 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
7281 (goto-char (match-beginning 0))
7282 (funcall function
)))))))
7284 (defun org-hide-block-toggle-all ()
7285 "Toggle the visibility of all blocks in the current buffer."
7286 (org-block-map 'org-hide-block-toggle
))
7288 (defun org-hide-block-all ()
7289 "Fold all blocks in the current buffer."
7291 (org-show-block-all)
7292 (org-block-map 'org-hide-block-toggle-maybe
))
7294 (defun org-show-block-all ()
7295 "Unfold all blocks in the current buffer."
7297 (mapc 'delete-overlay org-hide-block-overlays
)
7298 (setq org-hide-block-overlays nil
))
7300 (defun org-hide-block-toggle-maybe ()
7301 "Toggle visibility of block at point.
7302 Unlike to `org-hide-block-toggle', this function does not throw
7303 an error. Return a non-nil value when toggling is successful."
7305 (ignore-errors (org-hide-block-toggle)))
7307 (defun org-hide-block-toggle (&optional force
)
7308 "Toggle the visibility of the current block.
7309 When optional argument FORCE is `off', make block visible. If it
7310 is non-nil, hide it unconditionally. Throw an error when not at
7311 a block. Return a non-nil value when toggling is successful."
7313 (let ((element (org-element-at-point)))
7314 (unless (memq (org-element-type element
)
7315 '(center-block comment-block dynamic-block example-block
7316 export-block quote-block special-block
7317 src-block verse-block
))
7318 (user-error "Not at a block"))
7319 (let* ((start (save-excursion
7320 (goto-char (org-element-property :post-affiliated element
))
7321 (line-end-position)))
7322 (end (save-excursion
7323 (goto-char (org-element-property :end element
))
7324 (skip-chars-backward " \r\t\n")
7325 (line-end-position)))
7326 (overlays (overlays-at start
)))
7328 ;; Do nothing when not before or at the block opening line or
7329 ;; at the block closing line.
7330 ((let ((eol (line-end-position))) (and (> eol start
) (/= eol end
))) nil
)
7331 ((and (not (eq force
'off
))
7332 (not (memq t
(mapcar
7334 (eq (overlay-get o
'invisible
) 'org-hide-block
))
7336 (let ((ov (make-overlay start end
)))
7337 (overlay-put ov
'invisible
'org-hide-block
)
7338 ;; Make the block accessible to `isearch'.
7340 ov
'isearch-open-invisible
7342 (when (memq ov org-hide-block-overlays
)
7343 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7344 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7345 (delete-overlay ov
))))
7346 (push ov org-hide-block-overlays
)
7347 ;; When the block is hidden away, make sure point is left in
7348 ;; a visible part of the buffer.
7349 (when (> (line-beginning-position) start
)
7351 (beginning-of-line))
7352 ;; Signal successful toggling.
7354 ((or (not force
) (eq force
'off
))
7355 (dolist (ov overlays t
)
7356 (when (memq ov org-hide-block-overlays
)
7357 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7358 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7359 (delete-overlay ov
))))))))
7361 ;; org-tab-after-check-for-cycling-hook
7362 (add-hook 'org-tab-first-hook
'org-hide-block-toggle-maybe
)
7363 ;; Remove overlays when changing major mode
7364 (add-hook 'org-mode-hook
7365 (lambda () (org-add-hook 'change-major-mode-hook
7366 'org-show-block-all
'append
'local
)))
7370 (defvar org-goto-window-configuration nil
)
7371 (defvar org-goto-marker nil
)
7372 (defvar org-goto-map
)
7373 (defun org-goto-map ()
7374 "Set the keymap `org-goto'."
7376 (let ((map (make-sparse-keymap)))
7377 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7378 mouse-drag-region universal-argument org-occur
))
7380 (while (setq cmd
(pop cmds
))
7381 (substitute-key-definition cmd cmd map global-map
)))
7382 (suppress-keymap map
)
7383 (org-defkey map
"\C-m" 'org-goto-ret
)
7384 (org-defkey map
[(return)] 'org-goto-ret
)
7385 (org-defkey map
[(left)] 'org-goto-left
)
7386 (org-defkey map
[(right)] 'org-goto-right
)
7387 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
7388 (org-defkey map
"\C-i" 'org-cycle
)
7389 (org-defkey map
[(tab)] 'org-cycle
)
7390 (org-defkey map
[(down)] 'outline-next-visible-heading
)
7391 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
7392 (if org-goto-auto-isearch
7393 (if (fboundp 'define-key-after
)
7394 (define-key-after map
[t] 'org-goto-local-auto-isearch)
7396 (org-defkey map "q" 'org-goto-quit)
7397 (org-defkey map "n" 'outline-next-visible-heading)
7398 (org-defkey map "p" 'outline-previous-visible-heading)
7399 (org-defkey map "f" 'outline-forward-same-level)
7400 (org-defkey map "b" 'outline-backward-same-level)
7401 (org-defkey map "u" 'outline-up-heading))
7402 (org-defkey map "/" 'org-occur)
7403 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7404 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7405 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7406 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7407 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7410 (defconst org-goto-help
7411 "Browse buffer copy, to find location or copy text.%s
7412 RET=jump to location C-g=quit and return to previous location
7413 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7415 (defvar org-goto-start-pos) ; dynamically scoped parameter
7417 (defun org-goto (&optional alternative-interface)
7418 "Look up a different location in the current file, keeping current visibility.
7420 When you want look-up or go to a different location in a
7421 document, the fastest way is often to fold the entire buffer and
7422 then dive into the tree. This method has the disadvantage, that
7423 the previous location will be folded, which may not be what you
7426 This command works around this by showing a copy of the current
7427 buffer in an indirect buffer, in overview mode. You can dive
7428 into the tree in that copy, use org-occur and incremental search
7429 to find a location. When pressing RET or `Q', the command
7430 returns to the original buffer in which the visibility is still
7431 unchanged. After RET it will also jump to the location selected
7432 in the indirect buffer and expose the headline hierarchy above.
7434 With a prefix argument, use the alternative interface: e.g. if
7435 `org-goto-interface' is 'outline use 'outline-path-completion."
7438 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7439 (org-refile-use-outline-path t)
7440 (org-refile-target-verify-function nil)
7442 (if (not alternative-interface)
7444 (if (eq org-goto-interface 'outline)
7445 'outline-path-completion
7447 (org-goto-start-pos (point))
7449 (if (eq interface 'outline)
7450 (car (org-get-location (current-buffer) org-goto-help))
7451 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7452 (org-refile-check-position pa)
7456 (org-mark-ring-push org-goto-start-pos)
7457 (goto-char selected-point)
7458 (if (or (outline-invisible-p) (org-invisible-p2))
7459 (org-show-context 'org-goto)))
7462 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7463 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7464 (defvar org-goto-local-auto-isearch-map) ; defined below
7466 (defun org-get-location (buf help)
7467 "Let the user select a location in the Org-mode buffer BUF.
7468 This function uses a recursive edit. It returns the selected position
7471 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7472 (isearch-hide-immediately nil)
7473 (isearch-search-fun-function
7474 (lambda () 'org-goto-local-search-headings))
7475 (org-goto-selected-point org-goto-exit-command))
7477 (save-window-excursion
7478 (delete-other-windows)
7479 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7480 (org-pop-to-buffer-same-window
7482 (make-indirect-buffer (current-buffer) "*org-goto*")
7483 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7484 (with-output-to-temp-buffer "*Org Help*"
7485 (princ (format help (if org-goto-auto-isearch
7486 " Just type for auto-isearch."
7487 " n/p/f/b/u to navigate, q to quit."))))
7488 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7489 (setq buffer-read-only nil)
7490 (let ((org-startup-truncated t)
7491 (org-startup-folded nil)
7492 (org-startup-align-all-tables nil))
7495 (setq buffer-read-only t)
7496 (if (and (boundp 'org-goto-start-pos)
7497 (integer-or-marker-p org-goto-start-pos))
7498 (let ((org-show-hierarchy-above t)
7499 (org-show-siblings t)
7500 (org-show-following-heading t))
7501 (goto-char org-goto-start-pos)
7502 (and (outline-invisible-p) (org-show-context)))
7503 (goto-char (point-min)))
7504 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7505 (message "Select location and press RET")
7506 (use-local-map org-goto-map)
7508 (kill-buffer "*org-goto*")
7509 (cons org-goto-selected-point org-goto-exit-command))))
7511 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7512 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7513 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7514 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7516 (defun org-goto-local-search-headings (string bound noerror)
7517 "Search and make sure that any matches are in headlines."
7519 (while (if isearch-forward
7520 (search-forward string bound noerror)
7521 (search-backward string bound noerror))
7522 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7523 (and (member :headline context)
7524 (not (member :tags context))))
7525 (throw 'return (point))))))
7527 (defun org-goto-local-auto-isearch ()
7530 (goto-char (point-min))
7531 (let ((keys (this-command-keys)))
7532 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7534 (isearch-process-search-char (string-to-char keys)))))
7536 (defun org-goto-ret (&optional arg)
7537 "Finish `org-goto' by going to the new location."
7539 (setq org-goto-selected-point (point)
7540 org-goto-exit-command 'return)
7543 (defun org-goto-left ()
7544 "Finish `org-goto' by going to the new location."
7546 (if (org-at-heading-p)
7548 (beginning-of-line 1)
7549 (setq org-goto-selected-point (point)
7550 org-goto-exit-command 'left)
7552 (user-error "Not on a heading")))
7554 (defun org-goto-right ()
7555 "Finish `org-goto' by going to the new location."
7557 (if (org-at-heading-p)
7559 (setq org-goto-selected-point (point)
7560 org-goto-exit-command 'right)
7562 (user-error "Not on a heading")))
7564 (defun org-goto-quit ()
7565 "Finish `org-goto' without cursor motion."
7567 (setq org-goto-selected-point nil)
7568 (setq org-goto-exit-command 'quit)
7571 ;;; Indirect buffer display of subtrees
7573 (defvar org-indirect-dedicated-frame nil
7574 "This is the frame being used for indirect tree display.")
7575 (defvar org-last-indirect-buffer nil)
7577 (defun org-tree-to-indirect-buffer (&optional arg)
7578 "Create indirect buffer and narrow it to current subtree.
7579 With a numerical prefix ARG, go up to this level and then take that tree.
7580 If ARG is negative, go up that many levels.
7582 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7583 indirect buffer previously made with this command, to avoid proliferation of
7584 indirect buffers. However, when you call the command with a \
7585 \\[universal-argument] prefix, or
7586 when `org-indirect-buffer-display' is `new-frame', the last buffer
7587 is kept so that you can work with several indirect buffers at the same time.
7588 If `org-indirect-buffer-display' is `dedicated-frame', the \
7589 \\[universal-argument] prefix also
7590 requests that a new frame be made for the new buffer, so that the dedicated
7591 frame is not changed."
7593 (let ((cbuf (current-buffer))
7594 (cwin (selected-window))
7596 beg end level heading ibuf)
7598 (org-back-to-heading t)
7600 (setq level (org-outline-level))
7601 (if (< arg 0) (setq arg (+ level arg)))
7602 (while (> (setq level (org-outline-level)) arg)
7603 (org-up-heading-safe)))
7605 heading (org-get-heading))
7606 (org-end-of-subtree t t)
7607 (if (org-at-heading-p) (backward-char 1))
7609 (if (and (buffer-live-p org-last-indirect-buffer)
7610 (not (eq org-indirect-buffer-display 'new-frame))
7612 (kill-buffer org-last-indirect-buffer))
7613 (setq ibuf (org-get-indirect-buffer cbuf heading)
7614 org-last-indirect-buffer ibuf)
7616 ((or (eq org-indirect-buffer-display 'new-frame)
7617 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7618 (select-frame (make-frame))
7619 (delete-other-windows)
7620 (org-pop-to-buffer-same-window ibuf)
7621 (org-set-frame-title heading))
7622 ((eq org-indirect-buffer-display 'dedicated-frame)
7624 (select-frame (or (and org-indirect-dedicated-frame
7625 (frame-live-p org-indirect-dedicated-frame)
7626 org-indirect-dedicated-frame)
7627 (setq org-indirect-dedicated-frame (make-frame)))))
7628 (delete-other-windows)
7629 (org-pop-to-buffer-same-window ibuf)
7630 (org-set-frame-title (concat "Indirect: " heading)))
7631 ((eq org-indirect-buffer-display 'current-window)
7632 (org-pop-to-buffer-same-window ibuf))
7633 ((eq org-indirect-buffer-display 'other-window)
7634 (pop-to-buffer ibuf))
7635 (t (error "Invalid value")))
7636 (if (featurep 'xemacs)
7637 (save-excursion (org-mode) (turn-on-font-lock)))
7638 (narrow-to-region beg end)
7641 (run-hook-with-args 'org-cycle-hook 'all)
7642 (and (window-live-p cwin) (select-window cwin))))
7644 (defun org-get-indirect-buffer (&optional buffer heading)
7645 (setq buffer (or buffer (current-buffer)))
7646 (let ((n 1) (base (buffer-name buffer)) bname)
7647 (while (buffer-live-p
7651 (if heading (concat heading "-" (number-to-string n))
7652 (number-to-string n))))))
7655 (make-indirect-buffer buffer bname 'clone)
7656 (error (make-indirect-buffer buffer bname)))))
7658 (defun org-set-frame-title (title)
7659 "Set the title of the current frame to the string TITLE."
7660 ;; FIXME: how to name a single frame in XEmacs???
7661 (unless (featurep 'xemacs)
7662 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7664 ;;;; Structure editing
7666 ;;; Inserting headlines
7668 (defun org-previous-line-empty-p (&optional next)
7669 "Is the previous line a blank line?
7670 When NEXT is non-nil, check the next line instead."
7673 (or (beginning-of-line (if next 2 0)) t)
7675 (looking-at "[ \t]*$")))))
7677 (defun org-insert-heading (&optional arg invisible-ok)
7678 "Insert a new heading or an item with the same depth at point.
7680 If point is at the beginning of a heading or a list item, insert
7681 a new heading or a new item above the current one. If point is
7682 at the beginning of a normal line, turn the line into a heading.
7684 If point is in the middle of a headline or a list item, split the
7685 headline or the item and create a new headline/item with the text
7686 in the current line after point \(see `org-M-RET-may-split-line'
7687 on how to modify this behavior).
7689 With one universal prefix argument, set the user option
7690 `org-insert-heading-respect-content' to t for the duration of
7691 the command. This modifies the behavior described above in this
7692 ways: on list items and at the beginning of normal lines, force
7693 the insertion of a heading after the current subtree.
7695 With two universal prefix arguments, insert the heading at the
7696 end of the grandparent subtree. For example, if point is within
7697 a 2nd-level heading, then it will insert a 2nd-level heading at
7698 the end of the 1st-level parent heading.
7700 If point is at the beginning of a headline, insert a sibling
7701 before the current headline. If point is not at the beginning,
7702 split the line and create a new headline with the text in the
7703 current line after point \(see `org-M-RET-may-split-line' on how
7704 to modify this behavior).
7706 If point is at the beginning of a normal line, turn this line
7709 When INVISIBLE-OK is set, stop at invisible headlines when going
7710 back. This is important for non-interactive uses of the
7713 (if (org-called-interactively-p 'any) (org-reveal))
7714 (let ((itemp (org-in-item-p))
7715 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7716 (respect-content (or org-insert-heading-respect-content
7718 (initial-content "")
7719 (adjust-empty-lines t))
7723 ((or (= (buffer-size) 0)
7724 (and (not (save-excursion
7725 (and (ignore-errors (org-back-to-heading invisible-ok))
7726 (org-at-heading-p))))
7727 (or arg (not itemp))))
7728 ;; At beginning of buffer or so high up that only a heading
7730 (cond ((and (bolp) (not respect-content)) (insert "* "))
7731 ((not respect-content)
7732 (unless may-split (end-of-line))
7734 ((re-search-forward org-outline-regexp-bol nil t)
7738 (t (goto-char (point-max))
7740 (run-hooks 'org-insert-heading-hook))
7742 ((and itemp (not (member arg '((4) (16)))))
7747 ;; Maybe move at the end of the subtree
7748 (when (equal arg '(16))
7749 (org-up-heading-safe)
7750 (org-end-of-subtree t))
7755 (on-heading (org-at-heading-p))
7756 (empty-line-p (if on-heading
7757 (org-previous-line-empty-p)
7758 ;; We will decide later
7760 ;; Get a level string to fall back on
7762 (if (org-before-first-heading-p) "*"
7764 (org-back-to-heading t)
7765 (if (org-previous-line-empty-p) (setq empty-line-p t))
7766 (looking-at org-outline-regexp)
7767 (make-string (1- (length (match-string 0))) ?*))))
7772 (org-back-to-heading invisible-ok)
7773 (when (and (not on-heading)
7774 (featurep 'org-inlinetask)
7775 (integerp org-inlinetask-min-level)
7776 (>= (length (match-string 0))
7777 org-inlinetask-min-level))
7778 ;; Find a heading level before the inline task
7779 (while (and (setq level (org-up-heading-safe))
7780 (>= level org-inlinetask-min-level)))
7781 (if (org-at-heading-p)
7782 (org-back-to-heading invisible-ok)
7783 (error "This should not happen")))
7784 (unless (and (save-excursion
7786 (org-backward-heading-same-level
7788 (= (point) (match-beginning 0)))
7789 (not (org-previous-line-empty-p t)))
7790 (setq empty-line-p (or empty-line-p
7791 (org-previous-line-empty-p))))
7793 (error (or fix-level "* ")))))
7794 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7795 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7796 pos hide-previous previous-pos)
7798 ;; If we insert after content, move there and clean up whitespace
7799 (when (and respect-content
7800 (not (org-looking-at-p org-outline-regexp-bol)))
7801 (if (not (org-before-first-heading-p))
7802 (org-end-of-subtree nil t)
7803 (re-search-forward org-outline-regexp-bol)
7804 (beginning-of-line 0))
7805 (skip-chars-backward " \r\n")
7806 (and (not (looking-back "^\\*+"))
7807 (looking-at "[ \t]+") (replace-match ""))
7808 (unless (eobp) (forward-char 1))
7809 (when (looking-at "^\\*")
7810 (unless (bobp) (backward-char 1))
7813 ;; If we are splitting, grab the text that should be moved to the new headline
7815 (if (org-on-heading-p)
7816 ;; This is a heading, we split intelligently (keeping tags)
7817 (let ((pos (point)))
7818 (goto-char (point-at-bol))
7819 (unless (looking-at org-complex-heading-regexp)
7820 (error "This should not happen"))
7821 (when (and (match-beginning 4)
7822 (> pos (match-beginning 4))
7823 (< pos (match-end 4)))
7824 (setq initial-content (buffer-substring pos (match-end 4)))
7826 (delete-region (point) (match-end 4))
7827 (if (looking-at "[ \t]*$")
7829 (insert (make-string (length initial-content) ?\ )))
7830 (setq initial-content (org-trim initial-content)))
7833 (setq initial-content
7834 (org-trim (buffer-substring (point) (point-at-eol))))
7835 (delete-region (point) (point-at-eol))))
7837 ;; If we are at the beginning of the line, insert before it. Else after
7839 ((and (bolp) (looking-at "[ \t]*$")))
7840 ((and (bolp) (not (looking-at "[ \t]*$")))
7843 (goto-char (point-at-eol))
7846 ;; Insert the new heading
7849 (insert initial-content)
7850 (when adjust-empty-lines
7852 (and blank (not (org-previous-line-empty-p))))
7853 (org-N-empty-lines-before-current (if blank 1 0))))
7854 (run-hooks 'org-insert-heading-hook)))))))
7856 (defun org-N-empty-lines-before-current (N)
7857 "Make the number of empty lines before current exactly N.
7858 So this will delete or add empty lines."
7862 (skip-chars-backward " \r\t\n")
7863 (unless (bolp) (forward-line))
7864 (delete-region (point) p))
7865 (when (> N 0) (insert (make-string N ?\n)))))
7867 (defun org-get-heading (&optional no-tags no-todo)
7868 "Return the heading of the current entry, without the stars.
7869 When NO-TAGS is non-nil, don't include tags.
7870 When NO-TODO is non-nil, don't include TODO keywords."
7872 (org-back-to-heading t)
7874 ((and no-tags no-todo)
7875 (looking-at org-complex-heading-regexp)
7878 (looking-at (concat org-outline-regexp
7880 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7883 (looking-at org-todo-line-regexp)
7885 (t (looking-at org-heading-regexp)
7886 (match-string 2)))))
7888 (defvar orgstruct-mode) ; defined below
7890 (defun org-heading-components ()
7891 "Return the components of the current heading.
7892 This is a list with the following elements:
7893 - the level as an integer
7894 - the reduced level, different if `org-odd-levels-only' is set.
7895 - the TODO keyword, or nil
7896 - the priority character, like ?A, or nil if no priority is given
7897 - the headline text itself, or the tags string if no headline text
7898 - the tags string, or nil."
7900 (org-back-to-heading t)
7901 (if (let (case-fold-search)
7905 org-complex-heading-regexp)))
7907 (list (length (match-string 1))
7908 (org-reduced-level (length (match-string 1)))
7913 (list (length (match-string 1))
7914 (org-reduced-level (length (match-string 1)))
7915 (org-match-string-no-properties 2)
7916 (and (match-end 3) (aref (match-string 3) 2))
7917 (org-match-string-no-properties 4)
7918 (org-match-string-no-properties 5))))))
7920 (defun org-get-entry ()
7921 "Get the entry text, after heading, entire subtree."
7923 (org-back-to-heading t)
7924 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7926 (defun org-insert-heading-after-current ()
7927 "Insert a new heading with same level as current, after current subtree."
7929 (org-back-to-heading)
7930 (org-insert-heading)
7931 (org-move-subtree-down)
7934 (defun org-insert-heading-respect-content (&optional invisible-ok)
7935 "Insert heading with `org-insert-heading-respect-content' set to t."
7937 (org-insert-heading '(4) invisible-ok))
7939 (defun org-insert-todo-heading-respect-content (&optional force-state)
7940 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7942 (org-insert-todo-heading force-state '(4)))
7944 (defun org-insert-todo-heading (arg &optional force-heading)
7945 "Insert a new heading with the same level and TODO state as current heading.
7946 If the heading has no TODO state, or if the state is DONE, use the first
7947 state (TODO by default). Also with one prefix arg, force first state. With
7948 two prefix args, force inserting at the end of the parent subtree."
7950 (when (or force-heading (not (org-insert-item 'checkbox)))
7951 (org-insert-heading (or (and (equal arg '(16)) '(16))
7954 (org-back-to-heading)
7955 (outline-previous-heading)
7956 (looking-at org-todo-line-regexp))
7959 (if (or (equal arg '(4))
7960 (not (match-beginning 2))
7961 (member (match-string 2) org-done-keywords))
7962 (car org-todo-keywords-1)
7966 (run-hook-with-args-until-success
7967 'org-todo-get-default-hook new-mark-x nil)
7969 (beginning-of-line 1)
7970 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7971 (if org-treat-insert-todo-heading-as-state-change
7973 (insert new-mark " "))))
7974 (when org-provide-todo-statistics
7975 (org-update-parent-todo-statistics))))
7977 (defun org-insert-subheading (arg)
7978 "Insert a new subheading and demote it.
7979 Works for outline headings and for plain lists alike."
7981 (org-insert-heading arg)
7983 ((org-at-heading-p) (org-do-demote))
7984 ((org-at-item-p) (org-indent-item))))
7986 (defun org-insert-todo-subheading (arg)
7987 "Insert a new subheading with TODO keyword or checkbox and demote it.
7988 Works for outline headings and for plain lists alike."
7990 (org-insert-todo-heading arg)
7992 ((org-at-heading-p) (org-do-demote))
7993 ((org-at-item-p) (org-indent-item))))
7995 ;;; Promotion and Demotion
7997 (defvar org-after-demote-entry-hook nil
7998 "Hook run after an entry has been demoted.
7999 The cursor will be at the beginning of the entry.
8000 When a subtree is being demoted, the hook will be called for each node.")
8002 (defvar org-after-promote-entry-hook nil
8003 "Hook run after an entry has been promoted.
8004 The cursor will be at the beginning of the entry.
8005 When a subtree is being promoted, the hook will be called for each node.")
8007 (defun org-promote-subtree ()
8008 "Promote the entire subtree.
8009 See also `org-promote'."
8012 (org-with-limited-levels (org-map-tree 'org-promote)))
8013 (org-fix-position-after-promote))
8015 (defun org-demote-subtree ()
8016 "Demote the entire subtree. See `org-demote'.
8017 See also `org-promote'."
8020 (org-with-limited-levels (org-map-tree 'org-demote)))
8021 (org-fix-position-after-promote))
8024 (defun org-do-promote ()
8025 "Promote the current heading higher up the tree.
8026 If the region is active in `transient-mark-mode', promote all headings
8030 (if (org-region-active-p)
8031 (org-map-region 'org-promote (region-beginning) (region-end))
8033 (org-fix-position-after-promote))
8035 (defun org-do-demote ()
8036 "Demote the current heading lower down the tree.
8037 If the region is active in `transient-mark-mode', demote all headings
8041 (if (org-region-active-p)
8042 (org-map-region 'org-demote (region-beginning) (region-end))
8044 (org-fix-position-after-promote))
8046 (defun org-fix-position-after-promote ()
8047 "Make sure that after pro/demotion cursor position is right."
8048 (let ((pos (point)))
8049 (when (save-excursion
8050 (beginning-of-line 1)
8051 (looking-at org-todo-line-regexp)
8052 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8053 (cond ((eobp) (insert " "))
8054 ((eolp) (insert " "))
8055 ((equal (char-after) ?\ ) (forward-char 1))))))
8057 (defun org-current-level ()
8058 "Return the level of the current entry, or nil if before the first headline.
8059 The level is the number of stars at the beginning of the headline."
8061 (org-with-limited-levels
8062 (if (ignore-errors (org-back-to-heading t))
8063 (funcall outline-level)))))
8065 (defun org-get-previous-line-level ()
8066 "Return the outline depth of the last headline before the current line.
8067 Returns 0 for the first headline in the buffer, and nil if before the
8069 (and (org-current-level)
8070 (or (and (/= (line-beginning-position) (point-min))
8071 (save-excursion (beginning-of-line 0) (org-current-level)))
8074 (defun org-reduced-level (l)
8075 "Compute the effective level of a heading.
8076 This takes into account the setting of `org-odd-levels-only'."
8079 (org-odd-levels-only (1+ (floor (/ l 2))))
8082 (defun org-level-increment ()
8083 "Return the number of stars that will be added or removed at a
8084 time to headlines when structure editing, based on the value of
8085 `org-odd-levels-only'."
8086 (if org-odd-levels-only 2 1))
8088 (defun org-get-valid-level (level &optional change)
8089 "Rectify a level change under the influence of `org-odd-levels-only'
8090 LEVEL is a current level, CHANGE is by how much the level should be
8091 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8092 even level numbers will become the next higher odd number."
8093 (if org-odd-levels-only
8094 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8095 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8096 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8097 (max 1 (+ level (or change 0)))))
8099 (if (boundp 'define-obsolete-function-alias)
8100 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8101 (define-obsolete-function-alias 'org-get-legal-level
8102 'org-get-valid-level)
8103 (define-obsolete-function-alias 'org-get-legal-level
8104 'org-get-valid-level "23.1")))
8106 (defun org-promote ()
8107 "Promote the current heading higher up the tree.
8108 If the region is active in `transient-mark-mode', promote all headings
8110 (org-back-to-heading t)
8111 (let* ((level (save-match-data (funcall outline-level)))
8112 (after-change-functions (remove 'flyspell-after-change-function
8113 after-change-functions))
8114 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8115 (diff (abs (- level (length up-head) -1))))
8116 (cond ((and (= level 1) org-called-with-limited-levels
8117 org-allow-promoting-top-level-subtree)
8118 (replace-match "# " nil t))
8120 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8121 (t (replace-match up-head nil t)))
8122 ;; Fixup tag positioning
8124 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8125 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8126 (run-hooks 'org-after-promote-entry-hook)))
8128 (defun org-demote ()
8129 "Demote the current heading lower down the tree.
8130 If the region is active in `transient-mark-mode', demote all headings
8132 (org-back-to-heading t)
8133 (let* ((level (save-match-data (funcall outline-level)))
8134 (after-change-functions (remove 'flyspell-after-change-function
8135 after-change-functions))
8136 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8137 (diff (abs (- level (length down-head) -1))))
8138 (replace-match down-head nil t)
8139 ;; Fixup tag positioning
8140 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8141 (if org-adapt-indentation (org-fixup-indentation diff))
8142 (run-hooks 'org-after-demote-entry-hook)))
8144 (defun org-cycle-level ()
8145 "Cycle the level of an empty headline through possible states.
8146 This goes first to child, then to parent, level, then up the hierarchy.
8147 After top level, it switches back to sibling level."
8149 (let ((org-adapt-indentation nil))
8150 (when (org-point-at-end-of-empty-headline)
8151 (setq this-command 'org-cycle-level) ; Only needed for caching
8152 (let ((cur-level (org-current-level))
8153 (prev-level (org-get-previous-line-level)))
8155 ;; If first headline in file, promote to top-level.
8157 (loop repeat (/ (- cur-level 1) (org-level-increment))
8158 do (org-do-promote)))
8159 ;; If same level as prev, demote one.
8160 ((= prev-level cur-level)
8162 ;; If parent is top-level, promote to top level if not already.
8164 (loop repeat (/ (- cur-level 1) (org-level-increment))
8165 do (org-do-promote)))
8166 ;; If top-level, return to prev-level.
8168 (loop repeat (/ (- prev-level 1) (org-level-increment))
8169 do (org-do-demote)))
8170 ;; If less than prev-level, promote one.
8171 ((< cur-level prev-level)
8173 ;; If deeper than prev-level, promote until higher than
8175 ((> cur-level prev-level)
8176 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8177 do (org-do-promote))))
8180 (defun org-map-tree (fun)
8181 "Call FUN for every heading underneath the current one."
8182 (org-back-to-heading)
8183 (let ((level (funcall outline-level)))
8187 (outline-next-heading)
8188 (> (funcall outline-level) level))
8192 (defun org-map-region (fun beg end)
8193 "Call FUN for every heading between BEG and END."
8194 (let ((org-ignore-region t))
8196 (setq end (copy-marker end))
8198 (if (and (re-search-forward org-outline-regexp-bol nil t)
8202 (outline-next-heading)
8207 (defvar org-property-end-re) ; silence byte-compiler
8208 (defun org-fixup-indentation (diff)
8209 "Change the indentation in the current entry by DIFF.
8210 However, if any line in the current entry has no indentation, or if it
8211 would end up with no indentation after the change, nothing at all is done."
8213 (let ((end (save-excursion (outline-next-heading)
8215 (prohibit (if (> diff 0)
8217 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8219 (unless (save-excursion (end-of-line 1)
8220 (re-search-forward prohibit end t))
8221 (while (and (< (point) end)
8222 (re-search-forward "^[ \t]+" end t))
8223 (goto-char (match-end 0))
8224 (setq col (current-column))
8225 (if (< diff 0) (replace-match ""))
8226 (org-indent-to-column (+ diff col))))
8227 (move-marker end nil))))
8229 (defun org-convert-to-odd-levels ()
8230 "Convert an org-mode file with all levels allowed to one with odd levels.
8231 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8234 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8235 (let ((outline-level 'org-outline-level)
8236 (org-odd-levels-only nil) n)
8238 (goto-char (point-min))
8239 (while (re-search-forward "^\\*\\*+ " nil t)
8240 (setq n (- (length (match-string 0)) 2))
8241 (while (>= (setq n (1- n)) 0)
8243 (end-of-line 1))))))
8245 (defun org-convert-to-oddeven-levels ()
8246 "Convert an org-mode file with only odd levels to one with odd/even levels.
8247 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8248 file contains a section with an even level, conversion would
8249 destroy the structure of the file. An error is signaled in this
8252 (goto-char (point-min))
8253 ;; First check if there are no even levels
8254 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8255 (org-show-context t)
8256 (error "Not all levels are odd in this file. Conversion not possible"))
8257 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8258 (let ((outline-regexp org-outline-regexp)
8259 (outline-level 'org-outline-level)
8260 (org-odd-levels-only nil) n)
8262 (goto-char (point-min))
8263 (while (re-search-forward "^\\*\\*+ " nil t)
8264 (setq n (/ (1- (length (match-string 0))) 2))
8265 (while (>= (setq n (1- n)) 0)
8267 (end-of-line 1))))))
8269 (defun org-tr-level (n)
8270 "Make N odd if required."
8271 (if org-odd-levels-only (1+ (/ n 2)) n))
8273 ;;; Vertical tree motion, cutting and pasting of subtrees
8275 (defun org-move-subtree-up (&optional arg)
8276 "Move the current subtree up past ARG headlines of the same level."
8278 (org-move-subtree-down (- (prefix-numeric-value arg))))
8280 (defun org-move-subtree-down (&optional arg)
8281 "Move the current subtree down past ARG headlines of the same level."
8283 (setq arg (prefix-numeric-value arg))
8284 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8285 'org-get-last-sibling))
8286 (ins-point (make-marker))
8288 (col (current-column))
8289 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8291 (org-back-to-heading)
8294 (setq ne-beg (org-back-over-empty-lines))
8297 (save-excursion (outline-end-of-heading)
8298 (setq folded (outline-invisible-p)))
8299 (progn (org-end-of-subtree nil t)
8300 (unless (eobp) (backward-char))))
8301 (outline-next-heading)
8302 (setq ne-end (org-back-over-empty-lines))
8305 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8306 ;; include less whitespace
8309 (forward-line (- ne-beg ne-end))
8310 (setq beg (point))))
8311 ;; Find insertion point, with error handling
8313 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8314 (progn (goto-char beg0)
8315 (user-error "Cannot move past superior level or buffer limit")))
8316 (setq cnt (1- cnt)))
8318 ;; Moving forward - still need to move over subtree
8319 (progn (org-end-of-subtree t t)
8321 (org-back-over-empty-lines)
8322 (or (bolp) (newline)))))
8323 (setq ne-ins (org-back-over-empty-lines))
8324 (move-marker ins-point (point))
8325 (setq txt (buffer-substring beg end))
8326 (org-save-markers-in-region beg end)
8327 (delete-region beg end)
8328 (org-remove-empty-overlays-at beg)
8329 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8330 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8331 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8332 (let ((bbb (point)))
8333 (insert-before-markers txt)
8334 (org-reinstall-markers-in-region bbb)
8335 (move-marker ins-point bbb))
8336 (or (bolp) (insert "\n"))
8337 (setq ins-end (point))
8338 (goto-char ins-point)
8339 (org-skip-whitespace)
8340 (when (and (< arg 0)
8341 (org-first-sibling-p)
8343 ;; Move whitespace back to beginning
8346 (let ((kill-whole-line t))
8347 (kill-line (- ne-ins ne-beg)) (point)))
8348 (insert (make-string (- ne-ins ne-beg) ?\n)))
8349 (move-marker ins-point nil)
8354 (org-cycle-hide-drawers 'children))
8355 (org-clean-visibility-after-subtree-move)
8356 ;; move back to the initial column we were at
8357 (move-to-column col)))
8359 (defvar org-subtree-clip ""
8360 "Clipboard for cut and paste of subtrees.
8361 This is actually only a copy of the kill, because we use the normal kill
8362 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8364 (defvar org-subtree-clip-folded nil
8365 "Was the last copied subtree folded?
8366 This is used to fold the tree back after pasting.")
8368 (defun org-cut-subtree (&optional n)
8369 "Cut the current subtree into the clipboard.
8370 With prefix arg N, cut this many sequential subtrees.
8371 This is a short-hand for marking the subtree and then cutting it."
8373 (org-copy-subtree n 'cut))
8375 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8376 "Copy the current subtree it in the clipboard.
8377 With prefix arg N, copy this many sequential subtrees.
8378 This is a short-hand for marking the subtree and then copying it.
8379 If CUT is non-nil, actually cut the subtree.
8380 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8381 of some markers in the region, even if CUT is non-nil. This is
8382 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8384 (let (beg end folded (beg0 (point)))
8385 (if (org-called-interactively-p 'any)
8386 (org-back-to-heading nil) ; take what looks like a subtree
8387 (org-back-to-heading t)) ; take what is really there
8389 (skip-chars-forward " \t\r\n")
8392 (outline-next-heading)
8393 (save-excursion (outline-end-of-heading)
8394 (setq folded (outline-invisible-p)))
8395 (ignore-errors (org-forward-heading-same-level (1- n) t))
8396 (org-end-of-subtree t t)))
8400 (setq org-subtree-clip-folded folded)
8401 (when (or cut force-store-markers)
8402 (org-save-markers-in-region beg end))
8403 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8404 (setq org-subtree-clip (current-kill 0))
8405 (message "%s: Subtree(s) with %d characters"
8406 (if cut "Cut" "Copied")
8407 (length org-subtree-clip)))))
8409 (defun org-paste-subtree (&optional level tree for-yank remove)
8410 "Paste the clipboard as a subtree, with modification of headline level.
8411 The entire subtree is promoted or demoted in order to match a new headline
8414 If the cursor is at the beginning of a headline, the same level as
8415 that headline is used to paste the tree.
8417 If not, the new level is derived from the *visible* headings
8418 before and after the insertion point, and taken to be the inferior headline
8419 level of the two. So if the previous visible heading is level 3 and the
8420 next is level 4 (or vice versa), level 4 will be used for insertion.
8421 This makes sure that the subtree remains an independent subtree and does
8422 not swallow low level entries.
8424 You can also force a different level, either by using a numeric prefix
8425 argument, or by inserting the heading marker by hand. For example, if the
8426 cursor is after \"*****\", then the tree will be shifted to level 5.
8428 If optional TREE is given, use this text instead of the kill ring.
8430 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8431 move back over whitespace before inserting, and move point to the end of
8432 the inserted text when done.
8434 When REMOVE is non-nil, remove the subtree from the clipboard."
8436 (setq tree (or tree (and kill-ring (current-kill 0))))
8437 (unless (org-kill-is-subtree-p tree)
8439 (substitute-command-keys
8440 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8441 (org-with-limited-levels
8442 (let* ((visp (not (outline-invisible-p)))
8444 (^re_ "\\(\\*+\\)[ \t]*")
8445 (old-level (if (string-match org-outline-regexp-bol txt)
8446 (- (match-end 0) (match-beginning 0) 1)
8448 (force-level (cond (level (prefix-numeric-value level))
8449 ((and (looking-at "[ \t]*$")
8451 "^\\*+$" (buffer-substring
8452 (point-at-bol) (point))))
8453 (- (match-end 0) (match-beginning 0)))
8455 (looking-at org-outline-regexp))
8456 (- (match-end 0) (point) 1))))
8457 (previous-level (save-excursion
8460 (outline-previous-visible-heading 1)
8461 (if (looking-at ^re_)
8462 (- (match-end 0) (match-beginning 0) 1)
8465 (next-level (save-excursion
8468 (or (looking-at org-outline-regexp)
8469 (outline-next-visible-heading 1))
8470 (if (looking-at ^re_)
8471 (- (match-end 0) (match-beginning 0) 1)
8474 (new-level (or force-level (max previous-level next-level)))
8475 (shift (if (or (= old-level -1)
8477 (= old-level new-level))
8479 (- new-level old-level)))
8480 (delta (if (> shift 0) -1 1))
8481 (func (if (> shift 0) 'org-demote 'org-promote))
8482 (org-odd-levels-only nil)
8484 ;; Remove the forced level indicator
8486 (delete-region (point-at-bol) (point)))
8488 (beginning-of-line (if (bolp) 1 2))
8490 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8491 (insert-before-markers txt)
8492 (unless (string-match "\n\\'" txt) (insert "\n"))
8493 (setq newend (point))
8494 (org-reinstall-markers-in-region beg)
8497 (skip-chars-forward " \t\n\r")
8499 (if (and (outline-invisible-p) visp)
8500 (save-excursion (outline-show-heading)))
8501 ;; Shift if necessary
8504 (narrow-to-region beg end)
8505 (while (not (= shift 0))
8506 (org-map-region func (point-min) (point-max))
8507 (setq shift (+ delta shift)))
8508 (goto-char (point-min))
8509 (setq newend (point-max))))
8510 (when (or (org-called-interactively-p 'interactive) for-yank)
8511 (message "Clipboard pasted as level %d subtree" new-level))
8512 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8514 (eq org-subtree-clip (current-kill 0))
8515 org-subtree-clip-folded)
8516 ;; The tree was folded before it was killed/copied
8518 (and for-yank (goto-char newend))
8519 (and remove (setq kill-ring (cdr kill-ring))))))
8521 (defun org-kill-is-subtree-p (&optional txt)
8522 "Check if the current kill is an outline subtree, or a set of trees.
8523 Returns nil if kill does not start with a headline, or if the first
8524 headline level is not the largest headline level in the tree.
8525 So this will actually accept several entries of equal levels as well,
8526 which is OK for `org-paste-subtree'.
8527 If optional TXT is given, check this string instead of the current kill."
8528 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8529 (re (org-get-limited-outline-regexp))
8530 (^re (concat "^" re))
8531 (start-level (and kill
8533 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8535 (- (match-end 2) (match-beginning 2) 1)))
8536 (start (1+ (or (match-beginning 2) -1))))
8537 (if (not start-level)
8539 nil) ;; does not even start with a heading
8541 (while (setq start (string-match ^re kill (1+ start)))
8542 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8546 (defvar org-markers-to-move nil
8547 "Markers that should be moved with a cut-and-paste operation.
8548 Those markers are stored together with their positions relative to
8549 the start of the region.")
8551 (defun org-save-markers-in-region (beg end)
8552 "Check markers in region.
8553 If these markers are between BEG and END, record their position relative
8554 to BEG, so that after moving the block of text, we can put the markers back
8556 This function gets called just before an entry or tree gets cut from the
8557 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8558 called immediately, to move the markers with the entries."
8559 (setq org-markers-to-move nil)
8560 (when (featurep 'org-clock)
8561 (org-clock-save-markers-for-cut-and-paste beg end))
8562 (when (featurep 'org-agenda)
8563 (org-agenda-save-markers-for-cut-and-paste beg end)))
8565 (defun org-check-and-save-marker (marker beg end)
8566 "Check if MARKER is between BEG and END.
8567 If yes, remember the marker and the distance to BEG."
8568 (when (and (marker-buffer marker)
8569 (equal (marker-buffer marker) (current-buffer)))
8570 (if (and (>= marker beg) (< marker end))
8571 (push (cons marker (- marker beg)) org-markers-to-move))))
8573 (defun org-reinstall-markers-in-region (beg)
8574 "Move all remembered markers to their position relative to BEG."
8576 (move-marker (car x) (+ beg (cdr x))))
8577 org-markers-to-move)
8578 (setq org-markers-to-move nil))
8580 (defun org-narrow-to-subtree ()
8581 "Narrow buffer to the current subtree."
8585 (org-with-limited-levels
8587 (progn (org-back-to-heading t) (point))
8588 (progn (org-end-of-subtree t t)
8589 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8592 (defun org-narrow-to-block ()
8593 "Narrow buffer to the current block."
8595 (let* ((case-fold-search t)
8596 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8597 "^[ \t]*#\\+end_.*")))
8599 (narrow-to-region (car blockp) (cdr blockp))
8600 (user-error "Not in a block"))))
8602 (defun org-clone-subtree-with-time-shift (n &optional shift)
8603 "Clone the task (subtree) at point N times.
8604 The clones will be inserted as siblings.
8606 In interactive use, the user will be prompted for the number of
8607 clones to be produced. If the entry has a timestamp, the user
8608 will also be prompted for a time shift, which may be a repeater
8609 as used in time stamps, for example `+3d'. To disable this,
8610 you can call the function with a universal prefix argument.
8612 When a valid repeater is given and the entry contains any time
8613 stamps, the clones will become a sequence in time, with time
8614 stamps in the subtree shifted for each clone produced. If SHIFT
8615 is nil or the empty string, time stamps will be left alone. The
8616 ID property of the original subtree is removed.
8618 If the original subtree did contain time stamps with a repeater,
8619 the following will happen:
8620 - the repeater will be removed in each clone
8621 - an additional clone will be produced, with the current, unshifted
8622 date(s) in the entry.
8623 - the original entry will be placed *after* all the clones, with
8625 - the start days in the repeater in the original entry will be shifted
8626 to past the last clone.
8627 In this way you can spell out a number of instances of a repeating task,
8628 and still retain the repeater to cover future instances of the task."
8629 (interactive "nNumber of clones to produce: ")
8632 (if (and (not (equal current-prefix-arg '(4)))
8634 (re-search-forward org-ts-regexp-both
8636 (org-end-of-subtree t)
8638 (read-from-minibuffer
8639 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8640 ""))) ;; No time shift
8642 (drawer-re org-drawer-regexp)
8643 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8644 beg end template task idprop
8645 shift-n shift-what doshift nmin nmax)
8646 (if (not (and (integerp n) (> n 0)))
8647 (user-error "Invalid number of replications %s" n))
8648 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8649 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8651 (user-error "Invalid shift specification %s" shift))
8653 (setq shift-n (string-to-number (match-string 1 shift))
8654 shift-what (cdr (assoc (match-string 2 shift)
8655 '(("d" . day) ("w" . week)
8656 ("m" . month) ("y" . year))))))
8657 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8658 (setq nmin 1 nmax n)
8659 (org-back-to-heading t)
8661 (setq idprop (org-entry-get nil "ID"))
8662 (org-end-of-subtree t t)
8663 (or (bolp) (insert "\n"))
8665 (setq template (buffer-substring beg end))
8667 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8668 (delete-region beg end)
8670 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8672 (loop for n from nmin to nmax do
8677 (goto-char (point-min))
8679 (and idprop (if org-clone-delete-id
8680 (org-entry-delete nil "ID")
8681 (org-id-get-create t)))
8683 (while (re-search-forward org-clock-re nil t)
8685 (goto-char (point-min))
8686 (while (re-search-forward drawer-re nil t)
8687 (org-remove-empty-drawer-at (point))))
8688 (goto-char (point-min))
8690 (while (re-search-forward org-ts-regexp-both nil t)
8691 (org-timestamp-change (* n shift-n) shift-what))
8692 (unless (= n n-no-remove)
8693 (goto-char (point-min))
8694 (while (re-search-forward org-ts-regexp nil t)
8696 (goto-char (match-beginning 0))
8697 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8698 (delete-region (match-beginning 1) (match-end 1)))))))
8699 (setq task (buffer-string)))
8705 (defun org-sort (with-case)
8706 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8707 Optional argument WITH-CASE means sort case-sensitively."
8710 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8711 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8713 (org-call-with-arg 'org-sort-entries with-case))))
8715 (defun org-sort-remove-invisible (s)
8716 "Remove invisible links from string S."
8717 (remove-text-properties 0 (length s) org-rm-props s)
8718 (while (string-match org-bracket-link-regexp s)
8719 (setq s (replace-match (if (match-end 2)
8721 (match-string 1 s)) t t s)))
8722 (let ((st (format " %s " s)))
8723 (while (string-match org-emph-re st)
8724 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8725 (setq s (substring st 1 -1)))
8728 (defvar org-priority-regexp) ; defined later in the file
8730 (defvar org-after-sorting-entries-or-items-hook nil
8731 "Hook that is run after a bunch of entries or items have been sorted.
8732 When children are sorted, the cursor is in the parent line when this
8733 hook gets called. When a region or a plain list is sorted, the cursor
8734 will be in the first entry of the sorted region/list.")
8736 (defun org-sort-entries
8737 (&optional with-case sorting-type getkey-func compare-func property)
8738 "Sort entries on a certain level of an outline tree.
8739 If there is an active region, the entries in the region are sorted.
8740 Else, if the cursor is before the first entry, sort the top-level items.
8741 Else, the children of the entry at point are sorted.
8743 Sorting can be alphabetically, numerically, by date/time as given by
8744 a time stamp, by a property, by priority order, or by a custom function.
8746 The command prompts for the sorting type unless it has been given to the
8747 function through the SORTING-TYPE argument, which needs to be a character,
8748 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8749 the precise meaning of each character:
8751 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8752 c By creation time, which is assumed to be the first inactive time stamp
8753 at the beginning of a line.
8754 d By deadline date/time.
8756 n Numerically, by converting the beginning of the entry/item to a number.
8757 o By order of TODO keywords.
8758 p By priority according to the cookie.
8759 r By the value of a property.
8760 s By scheduled date/time.
8761 t By date/time, either the first active time stamp in the entry, or, if
8762 none exist, by the first inactive one.
8764 Capital letters will reverse the sort order.
8766 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8767 called with point at the beginning of the record. It must return either
8768 a string or a number that should serve as the sorting key for that record.
8770 Comparing entries ignores case by default. However, with an optional argument
8771 WITH-CASE, the sorting considers case as well.
8773 Sorting is done against the visible part of the headlines, it ignores hidden
8776 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8778 (let ((case-func (if with-case 'identity 'downcase))
8780 ;; The clock marker is lost when using `sort-subr', let's
8781 ;; store the clocking string.
8782 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8784 (goto-char org-clock-marker)
8785 (looking-back "^.*") (match-string-no-properties 0))))
8786 start beg end stars re re2
8788 ;; Find beginning and end of region to sort
8790 ((org-region-active-p)
8791 ;; we will sort the region
8792 (setq end (region-end)
8794 (goto-char (region-beginning))
8795 (if (not (org-at-heading-p)) (outline-next-heading))
8796 (setq start (point)))
8797 ((or (org-at-heading-p)
8798 (ignore-errors (progn (org-back-to-heading) t)))
8799 ;; we will sort the children of the current headline
8800 (org-back-to-heading)
8802 end (progn (org-end-of-subtree t t)
8803 (or (bolp) (insert "\n"))
8804 (when (>= (org-back-over-empty-lines) 1)
8810 (outline-next-heading))
8812 ;; we will sort the top-level entries in this file
8813 (goto-char (point-min))
8814 (or (org-at-heading-p) (outline-next-heading))
8815 (setq start (point))
8816 (goto-char (point-max))
8817 (beginning-of-line 1)
8818 (when (looking-at ".*?\\S-")
8819 ;; File ends in a non-white line
8822 (setq end (point-max))
8823 (setq what "top-level")
8828 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8830 (looking-at "\\(\\*+\\)")
8831 (setq stars (match-string 1)
8832 re (concat "^" (regexp-quote stars) " +")
8833 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8834 txt (buffer-substring beg end))
8835 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8836 (if (and (not (equal stars "*")) (string-match re2 txt))
8837 (user-error "Region to sort contains a level above the first entry"))
8839 (unless sorting-type
8841 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8842 [t]ime
[s]cheduled [d]eadline [c]reated cloc[k]ing
8843 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8845 (setq sorting-type (read-char-exclusive))
8848 (and (= (downcase sorting-type) ?f)
8850 (org-icompleting-read "Sort using function: "
8851 obarray 'fboundp t nil nil))
8852 (setq getkey-func (intern getkey-func))))
8854 (and (= (downcase sorting-type) ?r)
8857 (org-icompleting-read "Property: "
8858 (mapcar 'list (org-buffer-property-keys t))
8861 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8862 (message "Sorting entries...")
8865 (narrow-to-region start end)
8866 (let ((dcst (downcase sorting-type))
8867 (case-fold-search nil)
8868 (now (current-time)))
8870 (/= dcst sorting-type)
8871 ;; This function moves to the beginning character of the "record" to
8874 (if (re-search-forward re nil t)
8875 (goto-char (match-beginning 0))
8876 (goto-char (point-max))))
8877 ;; This function moves to the last character of the "record" being
8882 (outline-forward-same-level 1)
8884 (goto-char (point-max))))))
8885 ;; This function returns the value that gets sorted against.
8889 (if (looking-at org-complex-heading-regexp)
8890 (string-to-number (org-sort-remove-invisible (match-string 4)))
8893 (if (looking-at org-complex-heading-regexp)
8894 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8897 (or (get-text-property (point) :org-clock-minutes) 0))
8899 (let ((end (save-excursion (outline-next-heading) (point))))
8900 (if (or (re-search-forward org-ts-regexp end t)
8901 (re-search-forward org-ts-regexp-both end t))
8902 (org-time-string-to-seconds (match-string 0))
8903 (org-float-time now))))
8905 (let ((end (save-excursion (outline-next-heading) (point))))
8906 (if (re-search-forward
8907 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8909 (org-time-string-to-seconds (match-string 0))
8910 (org-float-time now))))
8912 (let ((end (save-excursion (outline-next-heading) (point))))
8913 (if (re-search-forward org-scheduled-time-regexp end t)
8914 (org-time-string-to-seconds (match-string 1))
8915 (org-float-time now))))
8917 (let ((end (save-excursion (outline-next-heading) (point))))
8918 (if (re-search-forward org-deadline-time-regexp end t)
8919 (org-time-string-to-seconds (match-string 1))
8920 (org-float-time now))))
8922 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8923 (string-to-char (match-string 2))
8924 org-default-priority))
8926 (or (org-entry-get nil property) ""))
8928 (if (looking-at org-complex-heading-regexp)
8929 (let* ((m (match-string 2))
8930 (s (if (member m org-done-keywords) '- '+)))
8931 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8935 (setq tmp (funcall getkey-func))
8936 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8938 (error "Invalid key function `%s'" getkey-func)))
8939 (t (error "Invalid sorting type `%c'" sorting-type))))
8942 ((= dcst ?a) 'string<)
8943 ((= dcst ?f) compare-func)
8944 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8945 (run-hooks 'org-after-sorting-entries-or-items-hook)
8946 ;; Reset the clock marker if needed
8950 (search-forward cmstr nil t)
8951 (move-marker org-clock-marker (point))))
8952 (message "Sorting entries...done")))
8954 (defun org-do-sort (table what &optional with-case sorting-type)
8955 "Sort TABLE of WHAT according to SORTING-TYPE.
8956 The user will be prompted for the SORTING-TYPE if the call to this
8957 function does not specify it.
8958 WHAT is only for the prompt, to indicate what is being sorted.
8959 The sorting key will be extracted from the car of the elements of
8961 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8962 (unless sorting-type
8964 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8966 (setq sorting-type (read-char-exclusive)))
8967 (let ((dcst (downcase sorting-type))
8968 extractfun comparefun)
8969 ;; Define the appropriate functions
8972 (setq extractfun 'string-to-number
8973 comparefun (if (= dcst sorting-type) '< '>)))
8975 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8976 (lambda(x) (downcase (org-sort-remove-invisible x))))
8977 comparefun (if (= dcst sorting-type)
8979 (lambda (a b) (and (not (string< a b))
8980 (not (string= a b)))))))
8984 (cond ((or (string-match org-ts-regexp x)
8985 (string-match org-ts-regexp-both x))
8987 (org-time-string-to-time (match-string 0 x))))
8988 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
8989 (org-hh:mm-string-to-minutes x))
8991 comparefun (if (= dcst sorting-type) '< '>)))
8992 (t (error "Invalid sorting type `%c'" sorting-type)))
8994 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8996 (lambda (a b) (funcall comparefun (car a) (car b))))))
8999 ;;; The orgstruct minor mode
9001 ;; Define a minor mode which can be used in other modes in order to
9002 ;; integrate the org-mode structure editing commands.
9004 ;; This is really a hack, because the org-mode structure commands use
9005 ;; keys which normally belong to the major mode. Here is how it
9006 ;; works: The minor mode defines all the keys necessary to operate the
9007 ;; structure commands, but wraps the commands into a function which
9008 ;; tests if the cursor is currently at a headline or a plain list
9009 ;; item. If that is the case, the structure command is used,
9010 ;; temporarily setting many Org-mode variables like regular
9011 ;; expressions for filling etc. However, when any of those keys is
9012 ;; used at a different location, function uses `key-binding' to look
9013 ;; up if the key has an associated command in another currently active
9014 ;; keymap (minor modes, major mode, global), and executes that
9015 ;; command. There might be problems if any of the keys is otherwise
9016 ;; used as a prefix key.
9018 (defcustom orgstruct-heading-prefix-regexp ""
9019 "Regexp that matches the custom prefix of Org headlines in
9020 orgstruct(++)-mode."
9023 :package-version '(Org . "8.3")
9025 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9027 (defcustom orgstruct-setup-hook nil
9028 "Hook run after orgstruct-mode-map is filled."
9031 :package-version '(Org . "8.0")
9034 (defvar orgstruct-initialized nil)
9036 (defvar org-local-vars nil
9037 "List of local variables, for use by `orgstruct-mode'.")
9040 (define-minor-mode orgstruct-mode
9041 "Toggle the minor mode `orgstruct-mode'.
9042 This mode is for using Org-mode structure commands in other
9043 modes. The following keys behave as if Org-mode were active, if
9044 the cursor is on a headline, or on a plain list item (both as
9045 defined by Org-mode)."
9046 nil " OrgStruct" (make-sparse-keymap)
9047 (funcall (if orgstruct-mode
9048 'add-to-invisibility-spec
9049 'remove-from-invisibility-spec)
9051 (when orgstruct-mode
9052 (org-load-modules-maybe)
9053 (unless orgstruct-initialized
9055 (setq orgstruct-initialized t))))
9058 (defun turn-on-orgstruct ()
9059 "Unconditionally turn on `orgstruct-mode'."
9062 (defvar org-fb-vars nil)
9063 (make-variable-buffer-local 'org-fb-vars)
9064 (defun orgstruct++-mode (&optional arg)
9065 "Toggle `orgstruct-mode', the enhanced version of it.
9066 In addition to setting orgstruct-mode, this also exports all
9067 indentation and autofilling variables from org-mode into the
9068 buffer. It will also recognize item context in multiline items."
9070 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9072 (progn (orgstruct-mode -1)
9074 (org-set-local (car v)
9075 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9078 (setq org-fb-vars nil)
9079 (unless org-local-vars
9080 (setq org-local-vars (org-get-local-variables)))
9085 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9086 (symbol-name (car x)))
9087 (setq var (car x) val (nth 1 x))
9088 (push (list var `(quote ,(eval var))) org-fb-vars)
9089 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9091 (org-set-local 'orgstruct-is-++ t))))
9093 (defvar orgstruct-is-++ nil
9094 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9095 (make-variable-buffer-local 'orgstruct-is-++)
9098 (defun turn-on-orgstruct++ ()
9099 "Unconditionally turn on `orgstruct++-mode'."
9100 (orgstruct++-mode 1))
9102 (defun orgstruct-error ()
9103 "Error when there is no default binding for a structure key."
9105 (funcall (if (fboundp 'user-error)
9108 "This key has no function outside structure elements"))
9110 (defun orgstruct-setup ()
9111 "Setup orgstruct keymap."
9112 (dolist (cell '((org-demote . t)
9116 (org-shiftmetaleft . t)
9117 (org-shiftmetaright . t)
9118 org-backward-element
9119 org-backward-heading-same-level
9124 org-forward-heading-same-level
9126 org-insert-heading-respect-content
9127 org-kill-note-or-show-branches
9132 org-narrow-to-subtree
9147 outline-next-visible-heading
9148 outline-previous-visible-heading
9152 (let ((f (or (car-safe cell) cell))
9153 (disable-when-heading-prefix (cdr-safe cell)))
9155 (let ((new-bindings))
9156 (dolist (binding (nconc (where-is-internal f org-mode-map)
9157 (where-is-internal f outline-mode-map)))
9158 (push binding new-bindings)
9159 ;; TODO use local-function-key-map
9160 (dolist (rep '(("<tab>" . "TAB")
9161 ("<return>" . "RET")
9162 ("<escape>" . "ESC")
9163 ("<delete>" . "DEL")))
9164 (setq binding (read-kbd-macro
9165 (let ((case-fold-search))
9166 (replace-regexp-in-string
9167 (regexp-quote (cdr rep))
9169 (key-description binding)))))
9170 (pushnew binding new-bindings :test 'equal)))
9171 (dolist (binding new-bindings)
9172 (let ((key (lookup-key orgstruct-mode-map binding)))
9173 (when (or (not key) (numberp key))
9175 (org-defkey orgstruct-mode-map
9177 (orgstruct-make-binding
9178 f binding disable-when-heading-prefix))))))))))
9179 (run-hooks 'orgstruct-setup-hook))
9181 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9182 "Create a function for binding in the structure minor mode.
9183 FUN is the command to call inside a table. KEY is the key that
9184 should be checked in for a command to execute outside of tables.
9185 Non-nil `disable-when-heading-prefix' means to disable the command
9186 if `orgstruct-heading-prefix-regexp' is not empty."
9187 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9190 (while (fboundp (intern nname))
9191 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9192 (setq name (intern nname)))
9194 (let ((bindings '((org-heading-regexp
9196 orgstruct-heading-prefix-regexp
9197 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9199 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9200 (org-outline-regexp-bol
9201 (concat "^" org-outline-regexp))
9202 (outline-regexp org-outline-regexp)
9203 (outline-heading-end-regexp "\n")
9204 (outline-level 'org-outline-level)
9205 (outline-heading-alist))))
9207 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9208 "Outside of structure, run the binding of `"
9209 (key-description key) "'."
9210 (when disable-when-heading-prefix
9212 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9213 "back to the default binding due to limitations of Org's implementation of\n"
9214 "`" (symbol-name fun) "'.")))
9217 ,(and disable-when-heading-prefix
9218 '(not (string= orgstruct-heading-prefix-regexp ""))))
9223 (org-context-p 'headline 'item
9225 '(org-insert-heading
9226 org-insert-heading-respect-content
9228 '(when orgstruct-is-++
9231 (let* ((orgstruct-mode)
9238 ("<\\([^>]*\\)tab>" . "\\1TAB")
9239 ("<\\([^>]*\\)return>" . "\\1RET")
9240 ("<\\([^>]*\\)escape>" . "\\1ESC")
9241 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9244 (setq key (read-kbd-macro
9245 (let ((case-fold-search))
9246 (replace-regexp-in-string
9249 (key-description key))))))
9250 (when (key-binding key)
9251 (throw 'exit (key-binding key))))))))
9252 (if (keymapp binding)
9253 (org-set-transient-map binding)
9254 (let ((func (or binding
9256 'orgstruct-error))))
9258 (call-interactively func)))))
9259 (org-run-like-in-org-mode
9263 (call-interactively ',fun)))))))))
9266 (defun org-contextualize-keys (alist contexts)
9267 "Return valid elements in ALIST depending on CONTEXTS.
9269 `org-agenda-custom-commands' or `org-capture-templates' are the
9270 values used for ALIST, and `org-agenda-custom-commands-contexts'
9271 or `org-capture-templates-contexts' are the associated contexts
9274 ;; normalize contexts
9276 (lambda(c) (cond ((listp (cadr c))
9277 (list (car c) (car c) (cadr c)))
9278 ((string= "" (cadr c))
9279 (list (car c) (car c) (caddr c)))
9282 ;; loop over all commands or templates
9283 (while (setq c (pop a))
9286 ((not (assoc (car c) contexts))
9288 ((and (assoc (car c) contexts)
9289 (setq vrules (org-contextualize-validate-key
9292 (when (not (equal (car vr) (cadr vr)))
9293 (setq repl vr))) vrules)
9294 (if (not repl) (push c r)
9295 (push (cadr repl) s)
9298 (cdr (or (assoc (cadr repl) alist)
9299 (error "Undefined key `%s' as contextual replacement for `%s'"
9300 (cadr repl) (car c)))))
9302 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9307 (let ((tpl (car x)))
9311 (equal y tpl)) s))) x)))
9314 (defun org-contextualize-validate-key (key contexts)
9315 "Check CONTEXTS for agenda or capture KEY."
9317 (while (setq r (pop contexts))
9321 (and (equal key (car r))
9322 (if (functionp rr) (funcall rr)
9323 (or (and (eq (car rr) 'in-file)
9325 (string-match (cdr rr) (buffer-file-name)))
9326 (and (eq (car rr) 'in-mode)
9327 (string-match (cdr rr) (symbol-name major-mode)))
9328 (and (eq (car rr) 'in-buffer)
9329 (string-match (cdr rr) (buffer-name)))
9330 (when (and (eq (car rr) 'not-in-file)
9332 (not (string-match (cdr rr) (buffer-file-name))))
9333 (when (eq (car rr) 'not-in-mode)
9334 (not (string-match (cdr rr) (symbol-name major-mode))))
9335 (when (eq (car rr) 'not-in-buffer)
9336 (not (string-match (cdr rr) (buffer-name)))))))
9339 (delete-dups (delq nil res))))
9341 (defun org-context-p (&rest contexts)
9342 "Check if local context is any of CONTEXTS.
9343 Possible values in the list of contexts are `table', `headline', and `item'."
9344 (let ((pos (point)))
9345 (goto-char (point-at-bol))
9346 (prog1 (or (and (memq 'table contexts)
9347 (looking-at "[ \t]*|"))
9348 (and (memq 'headline contexts)
9349 (looking-at org-outline-regexp))
9350 (and (memq 'item contexts)
9351 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9352 (and (memq 'item-body contexts)
9356 (defun org-get-local-variables ()
9357 "Return a list of all local variables in an Org mode buffer."
9359 (with-current-buffer (get-buffer-create "*Org tmp*")
9362 (setq varlist (buffer-local-variables)))
9363 (kill-buffer "*Org tmp*")
9370 (list (car x) (cdr x))))
9371 (if (and (not (get (car x) 'org-state))
9373 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9374 (symbol-name (car x))))
9378 (defun org-clone-local-variables (from-buffer &optional regexp)
9379 "Clone local variables from FROM-BUFFER.
9380 Optional argument REGEXP selects variables to clone."
9383 (and (symbolp (car pair))
9385 (string-match regexp (symbol-name (car pair))))
9386 (set (make-local-variable (car pair))
9388 (buffer-local-variables from-buffer)))
9391 (defun org-run-like-in-org-mode (cmd)
9392 "Run a command, pretending that the current buffer is in Org-mode.
9393 This will temporarily bind local variables that are typically bound in
9394 Org-mode to the values they have in Org-mode, and then interactively
9396 (org-load-modules-maybe)
9397 (unless org-local-vars
9398 (setq org-local-vars (org-get-local-variables)))
9400 (dolist (var org-local-vars)
9401 (when (or (not (boundp (car var)))
9402 (eq (symbol-value (car var))
9403 (default-value (car var))))
9404 (push (list (car var) `(quote ,(cadr var))) binds)))
9406 (call-interactively (quote ,cmd))))))
9408 (defun org-get-category (&optional pos force-refresh)
9409 "Get the category applying to position POS."
9411 (if force-refresh (org-refresh-category-properties))
9412 (let ((pos (or pos (point))))
9413 (or (get-text-property pos 'org-category)
9414 (progn (org-refresh-category-properties)
9415 (get-text-property pos 'org-category))))))
9417 ;;; Refresh properties
9419 (defun org-refresh-properties (dprop tprop)
9420 "Refresh buffer text properties.
9421 DPROP is the drawer property and TPROP is either the
9422 corresponding text property to set, or an alist with each element
9423 being a text property (as a symbol) and a function to apply to
9424 the value of the drawer property."
9425 (let ((case-fold-search t)
9426 (inhibit-read-only t))
9427 (org-with-silent-modifications
9431 (goto-char (point-min))
9432 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9433 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9435 (defun org-refresh-property (tprop p)
9436 "Refresh the buffer text property TPROP from the drawer property P.
9437 The refresh happens only for the current tree (not subtree)."
9439 (org-back-to-heading t)
9440 ;; tprop is a text property symbol
9443 (point) (or (outline-next-heading) (point-max)) tprop p)
9444 ;; tprop is an alist with (properties . function) elements
9448 (point-at-bol) (or (outline-next-heading) (point-max))
9450 (funcall (cdr al) p))))
9453 (defun org-refresh-category-properties ()
9454 "Refresh category text properties in the buffer."
9455 (let ((case-fold-search t)
9456 (inhibit-read-only t)
9458 ((null org-category)
9459 (if buffer-file-name
9460 (file-name-sans-extension
9461 (file-name-nondirectory buffer-file-name))
9463 ((symbolp org-category) (symbol-name org-category))
9465 beg end cat pos optionp)
9466 (org-with-silent-modifications
9470 (goto-char (point-min))
9471 (put-text-property (point) (point-max) 'org-category def-cat)
9472 (while (re-search-forward
9473 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9474 (setq pos (match-end 0)
9475 optionp (equal (char-after (match-beginning 0)) ?#)
9476 cat (org-trim (match-string 2)))
9478 (setq beg (point-at-bol) end (point-max))
9479 (org-back-to-heading t)
9480 (setq beg (point) end (org-end-of-subtree t t)))
9481 (put-text-property beg end 'org-category cat)
9482 (goto-char pos)))))))
9484 (defun org-refresh-stats-properties ()
9485 "Refresh stats text properties in the buffer."
9487 (org-with-silent-modifications
9491 (goto-char (point-min))
9492 (while (re-search-forward
9493 (concat org-outline-regexp-bol ".*"
9494 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9496 (setq stats (cond ((equal (match-string 3) "0") 0)
9498 (/ (* (string-to-number (match-string 2)) 100)
9499 (string-to-number (match-string 3))))
9500 (t (string-to-number (match-string 1)))))
9501 (org-back-to-heading t)
9502 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9503 'org-stats stats)))))))
9505 (defun org-refresh-effort-properties ()
9506 "Refresh effort properties"
9507 (org-refresh-properties
9509 '((effort . identity)
9510 (effort-minutes . org-duration-string-to-minutes))))
9514 ;;; Link abbreviations
9516 (defun org-link-expand-abbrev (link)
9517 "Apply replacements as defined in `org-link-abbrev-alist'."
9518 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9519 (let* ((key (match-string 1 link))
9520 (as (or (assoc key org-link-abbrev-alist-local)
9521 (assoc key org-link-abbrev-alist)))
9522 (tag (and (match-end 2) (match-string 3 link)))
9528 ((symbolp rpl) (funcall rpl tag))
9529 ((string-match "%(\\([^)]+\\))" rpl)
9532 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9533 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9534 ((string-match "%h" rpl)
9535 (replace-match (url-hexify-string (or tag "")) t t rpl))
9536 (t (concat rpl tag)))))
9539 ;;; Storing and inserting links
9541 (defvar org-insert-link-history nil
9542 "Minibuffer history for links inserted with `org-insert-link'.")
9544 (defvar org-stored-links nil
9545 "Contains the links stored with `org-store-link'.")
9547 (defvar org-store-link-plist nil
9548 "Plist with info about the most recently link created with `org-store-link'.")
9550 (defvar org-link-protocols nil
9551 "Link protocols added to Org-mode using `org-add-link-type'.")
9553 (defvar org-store-link-functions nil
9554 "List of functions that are called to create and store a link.
9555 Each function will be called in turn until one returns a non-nil
9556 value. Each function should check if it is responsible for creating
9557 this link (for example by looking at the major mode).
9558 If not, it must exit and return nil.
9559 If yes, it should return a non-nil value after a calling
9560 `org-store-link-props' with a list of properties and values.
9561 Special properties are:
9563 :type The link prefix, like \"http\". This must be given.
9564 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9565 This is obligatory as well.
9566 :description Optional default description for the second pair
9567 of brackets in an Org-mode link. The user can still change
9568 this when inserting this link into an Org-mode buffer.
9570 In addition to these, any additional properties can be specified
9571 and then used in capture templates.")
9573 (defun org-add-link-type (type &optional follow export)
9574 "Add TYPE to the list of `org-link-types'.
9575 Re-compute all regular expressions depending on `org-link-types'
9577 FOLLOW and EXPORT are two functions.
9579 FOLLOW should take the link path as the single argument and do whatever
9580 is necessary to follow the link, for example find a file or display
9583 EXPORT should format the link path for export to one of the export formats.
9584 It should be a function accepting three arguments:
9586 path the path of the link, the text after the prefix (like \"http:\")
9587 desc the description of the link, if any, or a description added by
9588 org-export-normalize-links if there is none
9589 format the export format, a symbol like `html' or `latex' or `ascii'..
9591 The function may use the FORMAT information to return different values
9592 depending on the format. The return value will be put literally into
9593 the exported file. If the return value is nil, this means Org should
9594 do what it normally does with links which do not have EXPORT defined.
9596 Org-mode has a built-in default for exporting links. If you are happy with
9597 this default, there is no need to define an export function for the link
9598 type. For a simple example of an export function, see `org-bbdb.el'."
9599 (add-to-list 'org-link-types type t)
9600 (org-make-link-regexps)
9601 (if (assoc type org-link-protocols)
9602 (setcdr (assoc type org-link-protocols) (list follow export))
9603 (push (list type follow export) org-link-protocols)))
9605 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9606 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9609 (defun org-store-link (arg)
9610 "\\<org-mode-map>Store an org-link to the current location.
9611 This link is added to `org-stored-links' and can later be inserted
9612 into an org-buffer with \\[org-insert-link].
9614 For some link types, a prefix arg is interpreted.
9615 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9616 For file links, arg negates `org-context-in-file-links'.
9618 A double prefix arg force skipping storing functions that are not
9621 A triple prefix arg force storing a link for each line in the
9624 (org-load-modules-maybe)
9625 (if (and (equal arg '(64)) (org-region-active-p))
9627 (let ((end (region-end)))
9628 (goto-char (region-beginning))
9630 (while (< (point-at-eol) end)
9631 (move-end-of-line 1) (activate-mark)
9632 (let (current-prefix-arg)
9633 (call-interactively 'org-store-link))
9634 (move-beginning-of-line 2)
9635 (set-mark (point)))))
9636 (org-with-limited-levels
9637 (setq org-store-link-plist nil)
9638 (let (link cpltxt desc description search
9639 txt custom-id agenda-link sfuns sfunsn)
9642 ;; Store a link using an external link type
9643 ((and (not (equal arg '(16)))
9646 nil (mapcar (lambda (f)
9647 (let (fs) (if (funcall f) (push f fs))))
9648 org-store-link-functions))
9649 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9650 (or (and (cdr sfuns)
9653 "Which function for creating the link? "
9654 sfunsn nil t (car sfunsn)))))
9655 (funcall (caar sfuns)))
9656 (setq link (plist-get org-store-link-plist :link)
9657 desc (or (plist-get org-store-link-plist
9658 :description) link))))
9660 ;; Store a link from a source code buffer
9661 ((org-src-edit-buffer-p)
9663 (while (or (not label)
9667 (goto-char (point-min))
9669 (regexp-quote (format org-coderef-label-format label))
9671 (when label (message "Label exists already") (sit-for 2))
9672 (setq label (read-string "Code line label: " label)))
9674 (setq link (format org-coderef-label-format label))
9675 (setq gc (- 79 (length link)))
9676 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9678 (setq link (concat "(" label ")") desc nil)))
9680 ;; We are in the agenda, link to referenced location
9681 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9682 (let ((m (or (get-text-property (point) 'org-hd-marker)
9683 (get-text-property (point) 'org-marker))))
9685 (org-with-point-at m
9687 (if (org-called-interactively-p 'any)
9688 (call-interactively 'org-store-link)
9689 (org-store-link nil)))))))
9691 ((eq major-mode 'calendar-mode)
9692 (let ((cd (calendar-cursor-to-date)))
9695 (car org-time-stamp-formats)
9697 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9699 (org-store-link-props :type "calendar" :date cd)))
9701 ((eq major-mode 'help-mode)
9702 (setq link (concat "help:" (save-excursion
9703 (goto-char (point-min))
9704 (looking-at "^[^ ]+")
9706 (org-store-link-props :type "help"))
9708 ((eq major-mode 'w3-mode)
9709 (setq cpltxt (if (and (buffer-name)
9710 (not (string-match "Untitled" (buffer-name))))
9713 link (url-view-url t))
9714 (org-store-link-props :type "w3" :url (url-view-url t)))
9716 ((eq major-mode 'image-mode)
9717 (setq cpltxt (concat "file:"
9718 (abbreviate-file-name buffer-file-name))
9720 (org-store-link-props :type "image" :file buffer-file-name))
9722 ;; In dired, store a link to the file of the current line
9723 ((derived-mode-p 'dired-mode)
9724 (let ((file (dired-get-filename nil t)))
9726 (abbreviate-file-name
9727 (expand-file-name (dired-get-filename nil t)))
9728 ;; otherwise, no file so use current directory.
9730 (setq cpltxt (concat "file:" file)
9733 ((setq search (run-hook-with-args-until-success
9734 'org-create-file-search-functions))
9735 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9737 (setq cpltxt (or description link)))
9739 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9740 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9742 ;; Store a link using the target at point
9743 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9746 (abbreviate-file-name
9747 (buffer-file-name (buffer-base-buffer)))
9748 "::" (match-string 1))
9750 ((and (featurep 'org-id)
9751 (or (eq org-id-link-to-org-use-id t)
9752 (and (org-called-interactively-p 'any)
9753 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9754 (and (eq org-id-link-to-org-use-id
9755 'create-if-interactive-and-no-custom-id)
9757 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9758 ;; Store a link using the ID at point
9759 (setq link (condition-case nil
9760 (prog1 (org-id-store-link)
9761 (setq desc (or (plist-get org-store-link-plist
9765 ;; Probably before first headline, link only to file
9767 (abbreviate-file-name
9768 (buffer-file-name (buffer-base-buffer))))))))
9770 ;; Just link to current headline
9771 (setq cpltxt (concat "file:"
9772 (abbreviate-file-name
9773 (buffer-file-name (buffer-base-buffer)))))
9774 ;; Add a context search string
9775 (when (org-xor org-context-in-file-links arg)
9776 (let* ((ee (org-element-at-point))
9777 (et (org-element-type ee))
9778 (ev (plist-get (cadr ee) :value))
9779 (ek (plist-get (cadr ee) :key))
9780 (eok (and (stringp ek) (string-match "name" ek))))
9782 ((org-at-heading-p) nil)
9783 ((and (eq et 'keyword) eok) ev)
9784 ((org-region-active-p)
9785 (buffer-substring (region-beginning) (region-end)))))
9786 (when (or (null txt) (string-match "\\S-" txt))
9790 (org-make-org-heading-search-string txt)
9792 desc (or (and (eq et 'keyword) eok ev)
9793 (nth 4 (ignore-errors (org-heading-components)))
9795 (if (string-match "::\\'" cpltxt)
9796 (setq cpltxt (substring cpltxt 0 -2)))
9797 (setq link cpltxt))))
9799 ((buffer-file-name (buffer-base-buffer))
9800 ;; Just link to this file here.
9801 (setq cpltxt (concat "file:"
9802 (abbreviate-file-name
9803 (buffer-file-name (buffer-base-buffer)))))
9804 ;; Add a context string.
9805 (when (org-xor org-context-in-file-links arg)
9806 (setq txt (if (org-region-active-p)
9807 (buffer-substring (region-beginning) (region-end))
9808 (buffer-substring (point-at-bol) (point-at-eol))))
9809 ;; Only use search option if there is some text.
9810 (when (string-match "\\S-" txt)
9812 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9816 ((org-called-interactively-p 'interactive)
9817 (user-error "No method for storing a link from this buffer"))
9819 (t (setq link nil)))
9821 ;; We're done setting link and desc, clean up
9822 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9823 (setq link (or link cpltxt)
9824 desc (or desc cpltxt))
9825 (cond ((equal desc "NONE") (setq desc nil))
9826 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9827 (let ((d0 (match-string 3 desc))
9828 (p0 (match-string 5 desc)))
9830 (replace-regexp-in-string
9831 org-bracket-link-regexp
9833 (if (equal (length (match-string 0 desc))
9834 (length desc)) "*" "")) desc)))))
9837 (if (not (and (or (org-called-interactively-p 'any)
9838 executing-kbd-macro) link))
9839 (or agenda-link (and link (org-make-link-string link desc)))
9840 (push (list link desc) org-stored-links)
9841 (message "Stored: %s" (or desc link))
9843 (setq link (concat "file:" (abbreviate-file-name
9844 (buffer-file-name)) "::#" custom-id))
9845 (push (list link desc) org-stored-links))
9846 (car org-stored-links))))))
9848 (defun org-store-link-props (&rest plist)
9849 "Store link properties, extract names and addresses."
9851 (when (setq x (plist-get plist :from))
9852 (setq adr (mail-extract-address-components x))
9853 (setq plist (plist-put plist :fromname (car adr)))
9854 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9855 (when (setq x (plist-get plist :to))
9856 (setq adr (mail-extract-address-components x))
9857 (setq plist (plist-put plist :toname (car adr)))
9858 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9859 (let ((from (plist-get plist :from))
9860 (to (plist-get plist :to)))
9861 (when (and from to org-from-is-user-regexp)
9863 (plist-put plist :fromto
9864 (if (string-match org-from-is-user-regexp from)
9866 (concat "from %f"))))))
9867 (setq org-store-link-plist plist))
9869 (defun org-add-link-props (&rest plist)
9870 "Add these properties to the link property list."
9873 (setq key (pop plist) value (pop plist))
9874 (setq org-store-link-plist
9875 (plist-put org-store-link-plist key value)))))
9877 (defun org-email-link-description (&optional fmt)
9878 "Return the description part of an email link.
9879 This takes information from `org-store-link-plist' and formats it
9880 according to FMT (default from `org-email-link-description-format')."
9881 (setq fmt (or fmt org-email-link-description-format))
9882 (let* ((p org-store-link-plist)
9883 (to (plist-get p :toaddress))
9884 (from (plist-get p :fromaddress))
9887 (cons "%c" (plist-get p :fromto))
9888 (cons "%F" (plist-get p :from))
9889 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9890 (cons "%T" (plist-get p :to))
9891 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9892 (cons "%s" (plist-get p :subject))
9893 (cons "%d" (plist-get p :date))
9894 (cons "%m" (plist-get p :message-id)))))
9895 (when (string-match "%c" fmt)
9896 ;; Check if the user wrote this message
9897 (if (and org-from-is-user-regexp from to
9898 (save-match-data (string-match org-from-is-user-regexp from)))
9899 (setq fmt (replace-match "to %t" t t fmt))
9900 (setq fmt (replace-match "from %f" t t fmt))))
9901 (org-replace-escapes fmt table)))
9903 (defun org-make-org-heading-search-string (&optional string)
9904 "Make search string for the current headline or STRING."
9906 (and (derived-mode-p 'org-mode)
9908 (org-back-to-heading t)
9909 (org-element-property :raw-value (org-element-at-point))))))
9910 (lines org-context-in-file-links))
9911 (or string (setq s (concat "*" s))) ; Add * for headlines
9912 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9913 (when (and string (integerp lines) (> lines 0))
9914 (let ((slines (org-split-string s "\n")))
9915 (when (< lines (length slines))
9918 (reverse (nthcdr (- (length slines) lines)
9919 (reverse slines))) "\n")))))
9920 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9922 (defun org-make-link-string (link &optional description)
9923 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9924 (unless (string-match "\\S-" link)
9925 (error "Empty link"))
9926 (when (and description
9927 (stringp description)
9928 (not (string-match "\\S-" description)))
9929 (setq description nil))
9930 (when (stringp description)
9931 ;; Remove brackets from the description, they are fatal.
9932 (while (string-match "\\[" description)
9933 (setq description (replace-match "{" t t description)))
9934 (while (string-match "\\]" description)
9935 (setq description (replace-match "}" t t description))))
9936 (when (equal link description)
9937 ;; No description needed, it is identical
9938 (setq description nil))
9939 (when (and (not description)
9940 (not (string-match (org-image-file-name-regexp) link))
9941 (not (equal link (org-link-escape link))))
9942 (setq description (org-extract-attributes link)))
9944 (cond ((string-match (org-image-file-name-regexp) link) link)
9945 ((string-match org-link-types-re link)
9946 (concat (match-string 1 link)
9947 (org-link-escape (substring link (match-end 1)))))
9948 (t (org-link-escape link))))
9949 (concat "[[" link "]"
9950 (if description (concat "[" description "]") "")
9953 (defconst org-link-escape-chars
9956 "List of characters that should be escaped in a link when stored to Org.
9957 This is the list that is used for internal purposes.")
9959 (defconst org-link-escape-chars-browser
9962 "List of characters to be escaped before handing over to the browser.
9963 If you consider using this constant then you probably want to use
9964 the function `org-link-escape-browser' instead. See there why
9965 this constant is a candidate to be removed once Org drops support
9966 for Emacs 24.1 and 24.2.")
9968 (defun org-link-escape (text &optional table merge)
9969 "Return percent escaped representation of TEXT.
9970 TEXT is a string with the text to escape.
9971 Optional argument TABLE is a list with characters that should be
9972 escaped. When nil, `org-link-escape-chars' is used.
9973 If optional argument MERGE is set, merge TABLE into
9974 `org-link-escape-chars'."
9975 ;; Don't escape chars in internal links
9976 (if (string-match "^\\*[[:alnum:]]+" text)
9980 (mapc (lambda (defchr)
9981 (unless (member defchr table)
9982 (setq table (cons defchr table))))
9983 org-link-escape-chars))
9985 (setq table org-link-escape-chars)))
9988 (if (or (member char table)
9989 (and (or (< char 32) (= char ?\%) (> char 126))
9991 (mapconcat (lambda (sequence-element)
9992 (format "%%%.2X" sequence-element))
9993 (or (encode-coding-char char 'utf-8)
9994 (error "Unable to percent escape character: %s"
9995 (char-to-string char))) "")
9996 (char-to-string char))) text "")))
9998 (defun org-link-escape-browser (text)
9999 "Escape some characters before handing over to the browser.
10000 This function is a candidate to be removed together with the
10001 constant `org-link-escape-chars-browser' once Org drops support
10002 for Emacs 24.1 and 24.2. All calls to this function will have to
10003 be replaced with `url-encode-url' which is available since Emacs
10005 ;; Example with the Org link
10006 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10007 ;; to open the browser with +subject:"Release 8.2" filled into the
10008 ;; query field: In this case the variable TEXT contains the
10009 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10010 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10011 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10012 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10013 (if (fboundp 'url-encode-url)
10014 (url-encode-url text)
10015 (if (org-string-match-p
10016 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10018 (org-link-escape text org-link-escape-chars-browser)
10021 (defun org-link-unescape (str)
10022 "Unhex hexified Unicode strings as returned from the JavaScript function
10023 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10024 (unless (and (null str) (string= "" str))
10025 (let ((pos 0) (case-fold-search t) unhexed)
10026 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10027 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10028 (setq str (replace-match unhexed t t str))
10029 (setq pos (+ pos (length unhexed))))))
10032 (defun org-link-unescape-compound (hex)
10033 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10034 Note: this function also decodes single byte encodings like
10035 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10037 (let* ((bytes (cdr (split-string hex "%")))
10042 (let* ((val (string-to-number (pop bytes) 16))
10046 ((>= val 252) (cons 6 252))
10047 ((>= val 248) (cons 5 248))
10048 ((>= val 240) (cons 4 240))
10049 ((>= val 224) (cons 3 224))
10050 ((>= val 192) (cons 2 192))
10053 (if (>= val 192) (setq eat (car shift-xor)))
10054 (setq val (logxor val (cdr shift-xor)))
10055 (setq sum (+ (lsh sum (car shift-xor)) val))
10056 (if (> eat 0) (setq eat (- eat 1)))
10058 ((= 0 eat) ;multi byte
10059 (setq ret (concat ret (org-char-to-string sum)))
10061 ((not bytes) ; single byte(s)
10062 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10065 (defun org-link-unescape-single-byte-sequence (hex)
10066 "Unhexify hex-encoded single byte character sequences."
10067 (mapconcat (lambda (byte)
10068 (char-to-string (string-to-number byte 16)))
10069 (cdr (split-string hex "%")) ""))
10071 (defun org-xor (a b)
10075 (defun org-fixup-message-id-for-http (s)
10076 "Replace special characters in a message id, so it can be used in an http query."
10077 (when (string-match "%" s)
10078 (setq s (mapconcat (lambda (c)
10081 (char-to-string c)))
10083 (while (string-match "<" s)
10084 (setq s (replace-match "%3C" t t s)))
10085 (while (string-match ">" s)
10086 (setq s (replace-match "%3E" t t s)))
10087 (while (string-match "@" s)
10088 (setq s (replace-match "%40" t t s)))
10091 (defun org-link-prettify (link)
10092 "Return a human-readable representation of LINK.
10093 The car of LINK must be a raw link.
10094 The cdr of LINK must be either a link description or nil."
10095 (let ((desc (or (cadr link) "<no description>")))
10096 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10097 "<" (car link) ">")))
10100 (defun org-insert-link-global ()
10101 "Insert a link like Org-mode does.
10102 This command can be called in any mode to insert a link in Org-mode syntax."
10104 (org-load-modules-maybe)
10105 (org-run-like-in-org-mode 'org-insert-link))
10107 (defun org-insert-all-links (arg &optional pre post)
10108 "Insert all links in `org-stored-links'.
10109 When a universal prefix, do not delete the links from `org-stored-links'.
10110 When `ARG' is a number, insert the last N link(s).
10111 `PRE' and `POST' are optional arguments to define a string to
10112 prepend or to append."
10114 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10115 (links (copy-seq org-stored-links))
10117 (po (or post "\n"))
10119 (if (null org-stored-links)
10120 (message "No link to insert")
10121 (while (and (or (listp arg) (>= arg cnt))
10122 (setq l (if (listp arg)
10124 (pop org-stored-links))))
10125 (setq cnt (1+ cnt))
10127 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10130 (defun org-insert-last-stored-link (arg)
10131 "Insert the last link stored in `org-stored-links'."
10133 (org-insert-all-links arg "" "\n"))
10135 (defun org-link-fontify-links-to-this-file ()
10136 "Fontify links to the current file in `org-stored-links'."
10137 (let ((f (buffer-file-name)) a b)
10138 (setq a (mapcar (lambda(l)
10139 (let ((ll (car l)))
10140 (when (and (string-match "^file:\\(.+\\)::" ll)
10141 (equal f (expand-file-name (match-string 1 ll))))
10144 (when (featurep 'org-id)
10145 (setq b (mapcar (lambda(l)
10146 (let ((ll (car l)))
10147 (when (and (string-match "^id:\\(.+\\)$" ll)
10148 (equal f (expand-file-name
10149 (or (org-id-find-id-file
10150 (match-string 1 ll)) ""))))
10152 org-stored-links)))
10154 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10155 (delq nil (append a b)))))
10157 (defvar org-link-links-in-this-file nil)
10158 (defun org-insert-link (&optional complete-file link-location default-description)
10159 "Insert a link. At the prompt, enter the link.
10161 Completion can be used to insert any of the link protocol prefixes like
10162 http or ftp in use.
10164 The history can be used to select a link previously stored with
10165 `org-store-link'. When the empty string is entered (i.e. if you just
10166 press RET at the prompt), the link defaults to the most recently
10167 stored link. As SPC triggers completion in the minibuffer, you need to
10168 use M-SPC or C-q SPC to force the insertion of a space character.
10170 You will also be prompted for a description, and if one is given, it will
10171 be displayed in the buffer instead of the link.
10173 If there is already a link at point, this command will allow you to edit link
10174 and description parts.
10176 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10177 be selected using completion. The path to the file will be relative to the
10178 current directory if the file is in the current directory or a subdirectory.
10179 Otherwise, the link will be the absolute path as completed in the minibuffer
10180 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10181 option `org-link-file-path-type'.
10183 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10184 the current directory or below.
10186 With three \\[universal-argument] prefixes, negate the meaning of
10187 `org-keep-stored-link-after-insertion'.
10189 If `org-make-link-description-function' is non-nil, this function will be
10190 called with the link target, and the result will be the default
10193 If the LINK-LOCATION parameter is non-nil, this value will be
10194 used as the link location instead of reading one interactively.
10196 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10197 be used as the default description."
10199 (let* ((wcf (current-window-configuration))
10200 (origbuf (current-buffer))
10201 (region (if (org-region-active-p)
10202 (buffer-substring (region-beginning) (region-end))))
10203 (remove (and region (list (region-beginning) (region-end))))
10205 tmphist ; byte-compile incorrectly complains about this
10206 (link link-location)
10207 (abbrevs org-link-abbrev-alist-local)
10208 entry file all-prefixes auto-desc)
10210 (link-location) ; specified by arg, just use it.
10211 ((org-in-regexp org-bracket-link-regexp 1)
10212 ;; We do have a link at point, and we are going to edit it.
10213 (setq remove (list (match-beginning 0) (match-end 0)))
10214 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10215 (setq link (read-string "Link: "
10217 (org-match-string-no-properties 1)))))
10218 ((or (org-in-regexp org-angle-link-re)
10219 (org-in-regexp org-plain-link-re))
10220 ;; Convert to bracket link
10221 (setq remove (list (match-beginning 0) (match-end 0))
10222 link (read-string "Link: "
10223 (org-remove-angle-brackets (match-string 0)))))
10224 ((member complete-file '((4) (16)))
10225 ;; Completing read for file names.
10226 (setq link (org-file-complete-link complete-file)))
10228 ;; Read link, with completion for stored links.
10229 (org-link-fontify-links-to-this-file)
10230 (org-switch-to-buffer-other-window "*Org Links*")
10231 (with-current-buffer "*Org Links*"
10233 (insert "Insert a link.
10234 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10235 (when org-stored-links
10236 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10237 (insert (mapconcat 'org-link-prettify
10238 (reverse org-stored-links) "\n")))
10239 (goto-char (point-min)))
10240 (let ((cw (selected-window)))
10241 (select-window (get-buffer-window "*Org Links*" 'visible))
10242 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10243 (unless (pos-visible-in-window-p (point-max))
10244 (org-fit-window-to-buffer))
10245 (and (window-live-p cw) (select-window cw)))
10246 ;; Fake a link history, containing the stored links.
10247 (setq tmphist (append (mapcar 'car org-stored-links)
10248 org-insert-link-history))
10249 (setq all-prefixes (append (mapcar 'car abbrevs)
10250 (mapcar 'car org-link-abbrev-alist)
10255 (org-completing-read
10258 (mapcar (lambda (x) (concat x ":"))
10260 (mapcar 'car org-stored-links))
10263 (caar org-stored-links)))
10264 (if (not (string-match "\\S-" link))
10265 (user-error "No link selected"))
10267 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10269 (if (or (member link all-prefixes)
10270 (and (equal ":" (substring link -1))
10271 (member (substring link 0 -1) all-prefixes)
10272 (setq link (substring link 0 -1))))
10273 (setq link (with-current-buffer origbuf
10274 (org-link-try-special-completion link)))))
10275 (set-window-configuration wcf)
10276 (kill-buffer "*Org Links*"))
10277 (setq entry (assoc link org-stored-links))
10278 (or entry (push link org-insert-link-history))
10279 (setq desc (or desc (nth 1 entry)))))
10281 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10282 (not org-keep-stored-link-after-insertion))
10283 (setq org-stored-links (delq (assoc link org-stored-links)
10284 org-stored-links)))
10286 (if (and (string-match org-plain-link-re link)
10287 (not (string-match org-ts-regexp link)))
10288 ;; URL-like link, normalize the use of angular brackets.
10289 (setq link (org-remove-angle-brackets link)))
10291 ;; Check if we are linking to the current file with a search
10292 ;; option If yes, simplify the link by using only the search
10294 (when (and buffer-file-name
10295 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10296 (let* ((path (match-string 1 link))
10297 (case-fold-search nil)
10298 (search (match-string 2 link)))
10300 (if (equal (file-truename buffer-file-name) (file-truename path))
10301 ;; We are linking to this same file, with a search option
10302 (setq link search)))))
10304 ;; Check if we can/should use a relative path. If yes, simplify the link
10305 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10306 (let* ((type (match-string 1 link))
10307 (path (match-string 2 link))
10309 (case-fold-search nil))
10311 ((or (eq org-link-file-path-type 'absolute)
10312 (equal complete-file '(16)))
10313 (setq path (abbreviate-file-name (expand-file-name path))))
10314 ((eq org-link-file-path-type 'noabbrev)
10315 (setq path (expand-file-name path)))
10316 ((eq org-link-file-path-type 'relative)
10317 (setq path (file-relative-name path)))
10320 (if (string-match (concat "^" (regexp-quote
10322 (file-name-as-directory
10323 default-directory))))
10324 (expand-file-name path))
10325 ;; We are linking a file with relative path name.
10326 (setq path (substring (expand-file-name path)
10328 (setq path (abbreviate-file-name (expand-file-name path)))))))
10329 (setq link (concat type path))
10330 (if (equal desc origpath)
10331 (setq desc path))))
10333 (if org-make-link-description-function
10335 (or (condition-case nil
10336 (funcall org-make-link-description-function link desc)
10337 (error (progn (message "Can't get link description from `%s'"
10338 (symbol-name org-make-link-description-function))
10340 (read-string "Description: " default-description)))
10341 (if default-description (setq desc default-description)
10342 (setq desc (or (and auto-desc desc)
10343 (read-string "Description: " desc)))))
10345 (unless (string-match "\\S-" desc) (setq desc nil))
10346 (if remove (apply 'delete-region remove))
10347 (insert (org-make-link-string link desc))))
10349 (defun org-link-try-special-completion (type)
10350 "If there is completion support for link type TYPE, offer it."
10351 (let ((fun (intern (concat "org-" type "-complete-link"))))
10352 (if (functionp fun)
10354 (read-string "Link (no completion support): " (concat type ":")))))
10356 (defun org-file-complete-link (&optional arg)
10357 "Create a file link using completion."
10359 (setq file (org-iread-file-name "File: "))
10360 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10361 (pwd1 (file-name-as-directory (abbreviate-file-name
10362 (expand-file-name ".")))))
10367 (abbreviate-file-name (expand-file-name file)))))
10368 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10369 (setq link (concat "file:" (match-string 1 file))))
10370 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10371 (expand-file-name file))
10373 "file:" (match-string 1 (expand-file-name file)))))
10374 (t (setq link (concat "file:" file)))))
10377 (defun org-iread-file-name (&rest args)
10378 "Read-file-name using `ido-mode' speedup if available.
10379 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10380 See `read-file-name' for a description of parameters."
10381 (org-without-partial-completion
10382 (if (and org-completion-use-ido
10383 (fboundp 'ido-read-file-name)
10384 (boundp 'ido-mode) ido-mode
10385 (listp (second args)))
10386 (let ((ido-enter-matching-directory nil))
10387 (apply 'ido-read-file-name args))
10388 (apply 'read-file-name args))))
10390 (defun org-completing-read (&rest args)
10391 "Completing-read with SPACE being a normal character."
10392 (let ((enable-recursive-minibuffers t)
10393 (minibuffer-local-completion-map
10394 (copy-keymap minibuffer-local-completion-map)))
10395 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10396 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10397 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10398 (apply 'org-icompleting-read args)))
10400 (defun org-completing-read-no-i (&rest args)
10401 (let (org-completion-use-ido org-completion-use-iswitchb)
10402 (apply 'org-completing-read args)))
10404 (defun org-iswitchb-completing-read (prompt choices &rest args)
10405 "Use iswitch as a completing-read replacement to choose from choices.
10406 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10408 (let* ((iswitchb-use-virtual-buffers nil)
10409 (iswitchb-make-buflist-hook
10411 (setq iswitchb-temp-buflist choices))))
10412 (iswitchb-read-buffer prompt)))
10414 (defun org-icompleting-read (&rest args)
10415 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10416 (org-without-partial-completion
10417 (if (and org-completion-use-ido
10418 (fboundp 'ido-completing-read)
10419 (boundp 'ido-mode) ido-mode
10420 (listp (second args)))
10421 (let ((ido-enter-matching-directory nil))
10422 (apply 'ido-completing-read (concat (car args))
10423 (if (consp (car (nth 1 args)))
10424 (mapcar 'car (nth 1 args))
10427 (if (and org-completion-use-iswitchb
10428 (boundp 'iswitchb-mode) iswitchb-mode
10429 (listp (second args)))
10430 (apply 'org-iswitchb-completing-read (concat (car args))
10431 (if (consp (car (nth 1 args)))
10432 (mapcar 'car (nth 1 args))
10435 (apply 'completing-read args)))))
10437 (defun org-extract-attributes (s)
10438 "Extract the attributes cookie from a string and set as text property."
10439 (let (a attr (start 0) key value)
10441 (when (string-match "{{\\([^}]+\\)}}$" s)
10442 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10443 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10444 (setq key (match-string 1 a) value (match-string 2 a)
10445 start (match-end 0)
10446 attr (plist-put attr (intern key) value))))
10447 (org-add-props s nil 'org-attr attr))
10450 ;;; Opening/following a link
10452 (defvar org-link-search-failed nil)
10454 (defvar org-open-link-functions nil
10455 "Hook for functions finding a plain text link.
10456 These functions must take a single argument, the link content.
10457 They will be called for links that look like [[link text][description]]
10458 when LINK TEXT does not have a protocol like \"http:\" and does not look
10459 like a filename (e.g. \"./blue.png\").
10461 These functions will be called *before* Org attempts to resolve the
10462 link by doing text searches in the current buffer - so if you want a
10463 link \"[[target]]\" to still find \"<<target>>\", your function should
10464 handle this as a special case.
10466 When the function does handle the link, it must return a non-nil value.
10467 If it decides that it is not responsible for this link, it must return
10468 nil to indicate that that Org-mode can continue with other options
10469 like exact and fuzzy text search.")
10471 (defun org-next-link (&optional search-backward)
10472 "Move forward to the next link.
10473 If the link is in hidden text, expose it."
10475 (when (and org-link-search-failed (eq this-command last-command))
10476 (goto-char (point-min))
10477 (message "Link search wrapped back to beginning of buffer"))
10478 (setq org-link-search-failed nil)
10479 (let* ((pos (point))
10481 (a (assoc :link ct))
10482 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10483 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10484 ((looking-at org-any-link-re)
10485 ;; Don't stay stuck at link without an org-link face
10486 (forward-char (if search-backward -1 1))))
10487 (if (funcall srch-fun org-any-link-re nil t)
10489 (goto-char (match-beginning 0))
10490 (if (outline-invisible-p) (org-show-context)))
10492 (setq org-link-search-failed t)
10493 (message "No further link found"))))
10495 (defun org-previous-link ()
10496 "Move backward to the previous link.
10497 If the link is in hidden text, expose it."
10499 (funcall 'org-next-link t))
10501 (defun org-translate-link (s)
10502 "Translate a link string if a translation function has been defined."
10503 (if (and org-link-translation-function
10504 (fboundp org-link-translation-function)
10505 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10507 (setq s (funcall org-link-translation-function
10508 (match-string 1 s) (match-string 2 s)))
10509 (concat (car s) ":" (cdr s)))
10512 (defun org-translate-link-from-planner (type path)
10513 "Translate a link from Emacs Planner syntax so that Org can follow it.
10514 This is still an experimental function, your mileage may vary."
10516 ((member type '("http" "https" "news" "ftp"))
10517 ;; standard Internet links are the same.
10519 ((and (equal type "irc") (string-match "^//" path))
10520 ;; Planner has two / at the beginning of an irc link, we have 1.
10521 ;; We should have zero, actually....
10522 (setq path (substring path 1)))
10523 ((and (equal type "lisp") (string-match "^/" path))
10524 ;; Planner has a slash, we do not.
10525 (setq type "elisp" path (substring path 1)))
10526 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10527 ;; A typical message link. Planner has the id after the final slash,
10528 ;; we separate it with a hash mark
10529 (setq path (concat (match-string 1 path) "#"
10530 (org-remove-angle-brackets (match-string 2 path))))))
10533 (defun org-find-file-at-mouse (ev)
10534 "Open file link or URL at mouse."
10536 (mouse-set-point ev)
10537 (org-open-at-point 'in-emacs))
10539 (defun org-open-at-mouse (ev)
10540 "Open file link or URL at mouse.
10541 See the docstring of `org-open-file' for details."
10543 (mouse-set-point ev)
10544 (if (eq major-mode 'org-agenda-mode)
10545 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10546 (org-open-at-point))
10548 (defvar org-window-config-before-follow-link nil
10549 "The window configuration before following a link.
10550 This is saved in case the need arises to restore it.")
10552 (defvar org-open-link-marker (make-marker)
10553 "Marker pointing to the location where `org-open-at-point' was called.")
10556 (defun org-open-at-point-global ()
10557 "Follow a link like Org-mode does.
10558 This command can be called in any mode to follow a link that has
10561 (org-run-like-in-org-mode 'org-open-at-point))
10564 (defun org-open-link-from-string (s &optional arg reference-buffer)
10565 "Open a link in the string S, as if it was in Org-mode."
10566 (interactive "sLink: \nP")
10567 (let ((reference-buffer (or reference-buffer (current-buffer))))
10569 (let ((org-inhibit-startup (not reference-buffer)))
10572 (goto-char (point-min))
10573 (when reference-buffer
10574 (setq org-link-abbrev-alist-local
10575 (with-current-buffer reference-buffer
10576 org-link-abbrev-alist-local)))
10577 (org-open-at-point arg reference-buffer)))))
10579 (defvar org-open-at-point-functions nil
10580 "Hook that is run when following a link at point.
10582 Functions in this hook must return t if they identify and follow
10583 a link at point. If they don't find anything interesting at point,
10584 they must return nil.")
10586 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10587 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10588 (defun org-open-at-point (&optional arg reference-buffer)
10589 "Open link, timestamp, footnote or tags at point.
10591 When point is on a link, follow it. Normally, files will be
10592 opened by an appropriate application. If the optional prefix
10593 argument ARG is non-nil, Emacs will visit the file. With
10594 a double prefix argument, try to open outside of Emacs, in the
10595 application the system uses for this file type.
10597 When point is on a timestamp, open the agenda at the day
10600 When point is a footnote definition, move to the first reference
10601 found. If it is on a reference, move to the associated
10604 When point is on a headline, display a list of every link in the
10605 entry, so it is possible to pick one, or all, of them. If point
10606 is on a tag, call `org-tags-view' instead.
10608 When optional argument REFERENCE-BUFFER is non-nil, it should
10609 specify a buffer from where the link search should happen. This
10610 is used internally by `org-open-link-from-string'.
10612 On top of syntactically correct links, this function will open
10613 the link at point in comments or comment blocks and the first
10614 link in a property drawer line."
10616 ;; On a code block, open block's results.
10617 (unless (call-interactively 'org-babel-open-src-block-result)
10618 (org-load-modules-maybe)
10619 (move-marker org-open-link-marker (point))
10620 (setq org-window-config-before-follow-link (current-window-configuration))
10621 (org-remove-occur-highlights nil nil t)
10622 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10623 (let* ((context (org-element-context)) type value)
10624 ;; On an unsupported type, check if point is contained within
10626 (while (and (not (memq (setq type (org-element-type context))
10627 '(comment comment-block
10628 headline inlinetask link
10629 footnote-definition footnote-reference
10630 node-property timestamp)))
10631 (setq context (org-element-property :parent context))))
10632 (setq value (org-element-property :value context))
10634 ;; Blank lines at the beginning of buffer: bail out.
10635 ((not context) (user-error "No link found"))
10636 ;; Exception n°1: links in property drawers
10637 ((eq type 'node-property)
10638 (org-open-link-from-string
10639 (and (string-match org-any-link-re value)
10640 (match-string-no-properties 0 value))))
10641 ;; Exception n°2: links in comments.
10642 ((memq type '(comment comment-block))
10644 (skip-chars-forward "\\S-" (point-at-eol))
10645 (let ((string-rear (replace-regexp-in-string
10646 "^[ \t]*# [ \t]*" ""
10647 (buffer-substring (point) (line-beginning-position))))
10648 (string-front (buffer-substring (point) (line-end-position))))
10650 (let ((org-inhibit-startup t)) (org-mode))
10652 (goto-char (point-min))
10653 (when (and (search-forward string-rear nil t)
10654 (search-forward string-front (line-end-position) t))
10655 (goto-char (match-beginning 0))
10656 (org-open-at-point)
10657 (when (string= string-rear "") (forward-char)))))))
10658 ;; On a headline or an inlinetask, but not on a timestamp,
10659 ;; a link, a footnote reference or on tags.
10660 ((and (memq type '(headline inlinetask))
10662 (progn (save-excursion (beginning-of-line)
10663 (looking-at org-complex-heading-regexp))
10664 (or (not (match-beginning 5))
10665 (< (point) (match-beginning 5)))))
10666 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10668 (links-end (cdr data)))
10670 (dolist (link (if (stringp links) (list links) links))
10671 (search-forward link nil links-end)
10672 (goto-char (match-beginning 0))
10673 (org-open-at-point))
10674 (require 'org-attach)
10675 (org-attach-reveal 'if-exists))))
10676 ;; Do nothing on white spaces after an object, unless point
10677 ;; is right after it.
10680 (goto-char (org-element-property :end context))
10681 (skip-chars-backward " \t")
10683 (user-error "No link found"))
10684 ((eq type 'timestamp) (org-follow-timestamp-link))
10685 ;; On tags within a headline or an inlinetask.
10686 ((and (memq type '(headline inlinetask))
10687 (progn (save-excursion (beginning-of-line)
10688 (looking-at org-complex-heading-regexp))
10689 (and (match-beginning 5)
10690 (>= (point) (match-beginning 5)))))
10691 (org-tags-view arg (substring (match-string 5) 0 -1)))
10693 (let ((type (org-element-property :type context))
10694 (path (org-link-unescape (org-element-property :path context))))
10695 ;; Switch back to REFERENCE-BUFFER needed when called in
10696 ;; a temporary buffer through `org-open-link-from-string'.
10697 (with-current-buffer (or reference-buffer (current-buffer))
10699 ((equal type "file")
10700 (if (string-match "[*?{]" (file-name-nondirectory path))
10702 ;; Look into `org-link-protocols' in order to find
10703 ;; a DEDICATED-FUNCTION to open file. The function
10704 ;; will be applied on raw link instead of parsed
10705 ;; link due to the limitation in `org-add-link-type'
10706 ;; ("open" function called with a single argument).
10707 ;; If no such function is found, fallback to
10708 ;; `org-open-file'.
10710 ;; Note : "file+emacs" and "file+sys" types are
10711 ;; hard-coded in order to escape the previous
10713 (let* ((option (org-element-property :search-option context))
10714 (app (org-element-property :application context))
10715 (dedicated-function
10716 (nth 1 (assoc app org-link-protocols))))
10717 (if dedicated-function
10718 (funcall dedicated-function
10720 (and option (concat "::" option))))
10721 (apply 'org-open-file
10724 ((equal app "emacs") 'emacs)
10725 ((equal app "sys") 'system))
10726 (cond ((not option) nil)
10727 ((org-string-match-p "\\`[0-9]+\\'" option)
10728 (list (string-to-number option)))
10730 (org-link-unescape option)))))))))
10731 ((assoc type org-link-protocols)
10732 (funcall (nth 1 (assoc type org-link-protocols)) path))
10733 ((equal type "help")
10734 (let ((f-or-v (intern path)))
10735 (cond ((fboundp f-or-v) (describe-function f-or-v))
10736 ((boundp f-or-v) (describe-variable f-or-v))
10737 (t (error "Not a known function or variable")))))
10738 ((member type '("http" "https" "ftp" "mailto" "news"))
10739 (browse-url (org-link-escape-browser (concat type ":" path))))
10740 ((equal type "doi")
10742 (org-link-escape-browser (concat org-doi-server-url path))))
10743 ((equal type "message") (browse-url (concat type ":" path)))
10744 ((equal type "shell")
10745 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10747 (if (or (and (org-string-nw-p
10748 org-confirm-shell-link-not-regexp)
10750 org-confirm-shell-link-not-regexp cmd))
10751 (not org-confirm-shell-link-function)
10752 (funcall org-confirm-shell-link-function
10753 (format "Execute \"%s\" in shell? "
10754 (org-add-props cmd nil
10755 'face 'org-warning))))
10757 (message "Executing %s" cmd)
10758 (shell-command cmd buf)
10759 (when (featurep 'midnight)
10760 (setq clean-buffer-list-kill-buffer-names
10762 clean-buffer-list-kill-buffer-names))))
10763 (user-error "Abort"))))
10764 ((equal type "elisp")
10766 (if (or (and (org-string-nw-p
10767 org-confirm-elisp-link-not-regexp)
10768 (org-string-match-p
10769 org-confirm-elisp-link-not-regexp cmd))
10770 (not org-confirm-elisp-link-function)
10771 (funcall org-confirm-elisp-link-function
10772 (format "Execute \"%s\" as elisp? "
10773 (org-add-props cmd nil
10774 'face 'org-warning))))
10775 (message "%s => %s" cmd
10776 (if (eq (string-to-char cmd) ?\()
10778 (call-interactively (read cmd))))
10779 (user-error "Abort"))))
10782 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10783 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10784 (unless (run-hook-with-args-until-success
10785 'org-open-link-functions path)
10786 (if (not arg) (org-mark-ring-push)
10787 (switch-to-buffer-other-window
10788 (org-get-buffer-for-internal-link (current-buffer))))
10789 (let ((cmd `(org-link-search
10790 ,(if (member type '("custom-id" "coderef"))
10791 (org-element-property :raw-link context)
10793 ,(cond ((equal arg '(4)) 'occur)
10794 ((equal arg '(16)) 'org-occur))
10795 ,(org-element-property :begin context))))
10796 (condition-case nil
10797 (let ((org-link-search-inhibit-query t))
10799 (error (progn (widen) (eval cmd)))))))
10800 (t (browse-url-at-point))))))
10801 ;; On a footnote reference or at a footnote definition's label.
10802 ((or (eq type 'footnote-reference)
10803 (and (eq type 'footnote-definition)
10805 ;; Do not validate action when point is on the
10806 ;; spaces right after the footnote label, in
10807 ;; order to be on par with behaviour on links.
10808 (skip-chars-forward " \t")
10810 (org-element-property :contents-begin context)))
10811 (if begin (< (point) begin)
10812 (= (org-element-property :post-affiliated context)
10813 (line-beginning-position)))))))
10814 (org-footnote-action))
10815 (t (user-error "No link found")))))
10816 (move-marker org-open-link-marker nil)
10817 (run-hook-with-args 'org-follow-link-hook)))
10819 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10820 "Offer links in the current entry and return the selected link.
10821 If there is only one link, return it.
10822 If NTH is an integer, return the NTH link found.
10823 If ZERO is a string, check also this string for a link, and if
10824 there is one, return it."
10825 (with-current-buffer buffer
10831 (in-emacs (if (integerp nth) nil nth))
10832 have-zero end links link c)
10833 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10834 (push (match-string 0 zero) links)
10835 (setq cnt (1- cnt) have-zero t))
10837 (org-back-to-heading t)
10838 (setq end (save-excursion (outline-next-heading) (point)))
10839 (while (re-search-forward org-any-link-re end t)
10840 (push (match-string 0) links))
10841 (setq links (org-uniquify (reverse links))))
10844 (message "No links"))
10845 ((equal (length links) 1)
10846 (setq link (car links)))
10847 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10848 (setq link (nth (if have-zero nth (1- nth)) links)))
10849 (t ; we have to select a link
10851 (save-window-excursion
10852 (delete-other-windows)
10853 (with-output-to-temp-buffer "*Select Link*"
10855 (if (not (string-match org-bracket-link-regexp l))
10856 (princ (format "[%c] %s\n" (incf cnt)
10857 (org-remove-angle-brackets l)))
10859 (princ (format "[%c] %s (%s)\n" (incf cnt)
10860 (match-string 3 l) (match-string 1 l)))
10861 (princ (format "[%c] %s\n" (incf cnt)
10862 (match-string 1 l))))))
10864 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10865 (message "Select link to open, RET to open all:")
10866 (setq c (read-char-exclusive))
10867 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10868 (when (equal c ?q) (user-error "Abort"))
10869 (if (equal c ?\C-m)
10871 (setq nth (- c ?0))
10872 (if have-zero (setq nth (1+ nth)))
10873 (unless (and (integerp nth) (>= (length links) nth))
10874 (user-error "Invalid link selection"))
10875 (setq link (nth (1- nth) links)))))
10876 (cons link end))))))
10878 ;; TODO: These functions are deprecated since `org-open-at-point'
10879 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10880 (defun org-open-file-with-system (path)
10881 "Open file at PATH using the system way of opening it."
10882 (org-open-file path 'system))
10883 (defun org-open-file-with-emacs (path)
10884 "Open file at PATH in Emacs."
10885 (org-open-file path 'emacs))
10890 (defvar org-create-file-search-functions nil
10891 "List of functions to construct the right search string for a file link.
10892 These functions are called in turn with point at the location to
10893 which the link should point.
10895 A function in the hook should first test if it would like to
10896 handle this file type, for example by checking the `major-mode'
10897 or the file extension. If it decides not to handle this file, it
10898 should just return nil to give other functions a chance. If it
10899 does handle the file, it must return the search string to be used
10900 when following the link. The search string will be part of the
10901 file link, given after a double colon, and `org-open-at-point'
10902 will automatically search for it. If special measures must be
10903 taken to make the search successful, another function should be
10904 added to the companion hook `org-execute-file-search-functions',
10907 A function in this hook may also use `setq' to set the variable
10908 `description' to provide a suggestion for the descriptive text to
10909 be used for this link when it gets inserted into an Org-mode
10910 buffer with \\[org-insert-link].")
10912 (defvar org-execute-file-search-functions nil
10913 "List of functions to execute a file search triggered by a link.
10915 Functions added to this hook must accept a single argument, the
10916 search string that was part of the file link, the part after the
10917 double colon. The function must first check if it would like to
10918 handle this search, for example by checking the `major-mode' or
10919 the file extension. If it decides not to handle this search, it
10920 should just return nil to give other functions a chance. If it
10921 does handle the search, it must return a non-nil value to keep
10922 other functions from trying.
10924 Each function can access the current prefix argument through the
10925 variable `current-prefix-arg'. Note that a single prefix is used
10926 to force opening a link in Emacs, so it may be good to only use a
10927 numeric or double prefix to guide the search function.
10929 In case this is needed, a function in this hook can also restore
10930 the window configuration before `org-open-at-point' was called using:
10932 (set-window-configuration org-window-config-before-follow-link)")
10934 (defun org-link-search (s &optional type avoid-pos stealth)
10935 "Search for a link search option.
10936 If S is surrounded by forward slashes, it is interpreted as a
10937 regular expression. In org-mode files, this will create an `org-occur'
10938 sparse tree. In ordinary files, `occur' will be used to list matches.
10939 If the current buffer is in `dired-mode', grep will be used to search
10940 in all files. If AVOID-POS is given, ignore matches near that position.
10942 When optional argument STEALTH is non-nil, do not modify
10943 visibility around point, thus ignoring
10944 `org-show-hierarchy-above', `org-show-following-heading' and
10945 `org-show-siblings' variables."
10946 (let ((case-fold-search t)
10947 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10948 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10949 (append '(("") (" ") ("\t") ("\n"))
10950 org-emphasis-alist)
10953 (pre nil) (post nil)
10954 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10956 ;; First check if there are any special search functions
10957 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10958 ;; Now try the builtin stuff
10959 ((and (equal (string-to-char s0) ?#)
10962 (goto-char (point-min))
10965 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10966 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10967 (setq type 'dedicated
10968 pos (match-beginning 0))))
10969 ;; There is an exact target for this
10971 (org-back-to-heading t)))
10973 (goto-char (point-min))
10976 (concat "<<" (regexp-quote s0) ">>") nil t)
10977 (setq type 'dedicated
10978 pos (match-beginning 0))))
10979 ;; There is an exact target for this
10982 (goto-char (point-min))
10985 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10986 (setq type 'dedicated pos (match-beginning 0))))
10987 ;; Found an element with a matching #+name affiliated keyword.
10989 ((and (string-match "^(\\(.*\\))$" s0)
10991 (goto-char (point-min))
10994 (concat "[^[]" (regexp-quote
10995 (format org-coderef-label-format
10996 (match-string 1 s0))))
10998 (setq type 'dedicated
10999 pos (1+ (match-beginning 0))))))
11000 ;; There is a coderef target for this
11002 ((string-match "^/\\(.*\\)/$" s)
11003 ;; A regular expression
11005 ((derived-mode-p 'org-mode)
11006 (org-occur (match-string 1 s)))
11007 (t (org-do-occur (match-string 1 s)))))
11008 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11009 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11010 (goto-char (point-min))
11012 ((let (case-fold-search)
11013 (re-search-forward (format org-complex-heading-regexp-format
11016 ;; OK, found a match
11017 (setq type 'dedicated)
11018 (goto-char (match-beginning 0)))
11019 ((and (not org-link-search-inhibit-query)
11020 (eq org-link-search-must-match-exact-headline 'query-to-create)
11021 (y-or-n-p "No match - create this as a new heading? "))
11022 (goto-char (point-max))
11023 (or (bolp) (newline))
11024 (insert "* " s "\n")
11025 (beginning-of-line 0))
11028 (error "No match"))))
11030 ;; A normal search string
11031 (when (equal (string-to-char s) ?*)
11032 ;; Anchor on headlines, post may include tags.
11033 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11034 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11035 s (substring s 1)))
11036 (remove-text-properties
11038 '(face nil mouse-face nil keymap nil fontified nil) s)
11039 ;; Make a series of regular expressions to find a match
11040 (setq words (org-split-string s "[ \n\r\t]+")
11042 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11043 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11045 re2a_ (concat "\\(" (mapconcat 'downcase words
11046 "[ \t\r\n]+") "\\)[ \t\r\n]")
11047 re2a (concat "[ \t\r\n]" re2a_)
11048 re4_ (concat "\\(" (mapconcat 'downcase words
11049 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11050 re4 (concat "[^a-zA-Z_]" re4_)
11052 re1 (concat pre re2 post)
11053 re3 (concat pre (if pre re4_ re4) post)
11054 re5 (concat pre ".*" re4)
11055 re2 (concat pre re2)
11056 re2a (concat pre (if pre re2a_ re2a))
11057 re4 (concat pre (if pre re4_ re4))
11058 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11059 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11062 ((eq type 'org-occur) (org-occur reall))
11063 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11064 (t (goto-char (point-min))
11066 (if (or (and (org-search-not-self 1 re0 nil t)
11067 (setq type 'dedicated))
11068 (org-search-not-self 1 re1 nil t)
11069 (org-search-not-self 1 re2 nil t)
11070 (org-search-not-self 1 re2a nil t)
11071 (org-search-not-self 1 re3 nil t)
11072 (org-search-not-self 1 re4 nil t)
11073 (org-search-not-self 1 re5 nil t))
11074 (goto-char (match-beginning 1))
11076 (error "No match"))))))
11077 (and (derived-mode-p 'org-mode)
11079 (org-show-context 'link-search))
11082 (defun org-search-not-self (group &rest args)
11083 "Execute `re-search-forward', but only accept matches that do not
11084 enclose the position of `org-open-link-marker'."
11085 (let ((m org-open-link-marker))
11087 (while (apply 're-search-forward args)
11088 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11089 (goto-char (match-end group))
11090 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11091 (> (match-beginning 0) (marker-position m))
11092 (< (match-end 0) (marker-position m)))
11094 (or (not (org-in-regexp
11095 org-bracket-link-analytic-regexp 1))
11096 (not (match-end 4)) ; no description
11097 (and (<= (match-beginning 4) (point))
11098 (>= (match-end 4) (point))))))
11099 (throw 'exit (point))))))))
11101 (defun org-get-buffer-for-internal-link (buffer)
11102 "Return a buffer to be used for displaying the link target of internal links."
11104 ((not org-display-internal-link-with-indirect-buffer)
11106 ((string-match "(Clone)$" (buffer-name buffer))
11107 (message "Buffer is already a clone, not making another one")
11108 ;; we also do not modify visibility in this case
11110 (t ; make a new indirect buffer for displaying the link
11111 (let* ((bn (buffer-name buffer))
11112 (ibn (concat bn "(Clone)"))
11113 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11114 (with-current-buffer ib (org-overview))
11117 (defun org-do-occur (regexp &optional cleanup)
11118 "Call the Emacs command `occur'.
11119 If CLEANUP is non-nil, remove the printout of the regular expression
11120 in the *Occur* buffer. This is useful if the regex is long and not useful
11124 (let ((cwin (selected-window)) win beg end)
11125 (when (setq win (get-buffer-window "*Occur*"))
11126 (select-window win))
11127 (goto-char (point-min))
11128 (when (re-search-forward "match[a-z]+" nil t)
11129 (setq beg (match-end 0))
11130 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11131 (setq end (1- (match-beginning 0)))))
11132 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11133 (goto-char (point-min))
11134 (select-window cwin))))
11136 ;;; The mark ring for links jumps
11138 (defvar org-mark-ring nil
11139 "Mark ring for positions before jumps in Org-mode.")
11140 (defvar org-mark-ring-last-goto nil
11141 "Last position in the mark ring used to go back.")
11142 ;; Fill and close the ring
11143 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11144 (loop for i from 1 to org-mark-ring-length do
11145 (push (make-marker) org-mark-ring))
11146 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11149 (defun org-mark-ring-push (&optional pos buffer)
11150 "Put the current position or POS into the mark ring and rotate it."
11152 (setq pos (or pos (point)))
11153 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11154 (move-marker (car org-mark-ring)
11156 (or buffer (current-buffer)))
11158 (substitute-command-keys
11159 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11161 (defun org-mark-ring-goto (&optional n)
11162 "Jump to the previous position in the mark ring.
11163 With prefix arg N, jump back that many stored positions. When
11164 called several times in succession, walk through the entire ring.
11165 Org-mode commands jumping to a different position in the current file,
11166 or to another Org-mode file, automatically push the old position
11170 (if (eq last-command this-command)
11171 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11172 (setq p org-mark-ring))
11173 (setq org-mark-ring-last-goto p)
11175 (org-pop-to-buffer-same-window (marker-buffer m))
11177 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11179 (defun org-remove-angle-brackets (s)
11180 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11181 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11183 (defun org-add-angle-brackets (s)
11184 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11185 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11187 (defun org-remove-double-quotes (s)
11188 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11189 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11192 ;;; Following specific links
11194 (defun org-follow-timestamp-link ()
11195 "Open an agenda view for the time-stamp date/range at point."
11197 ((org-at-date-range-p t)
11198 (let ((org-agenda-start-on-weekday)
11199 (t1 (match-string 1))
11200 (t2 (match-string 2)) tt1 tt2)
11201 (setq tt1 (time-to-days (org-time-string-to-time t1))
11202 tt2 (time-to-days (org-time-string-to-time t2)))
11203 (let ((org-agenda-buffer-tmp-name
11204 (format "*Org Agenda(a:%s)"
11205 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11206 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11207 ((org-at-timestamp-p t)
11208 (let ((org-agenda-buffer-tmp-name
11209 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11210 (org-agenda-list nil (time-to-days (org-time-string-to-time
11211 (substring (match-string 1) 0 10)))
11213 (t (error "This should not happen"))))
11216 ;;; Following file links
11217 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11218 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11219 (declare-function mailcap-mime-info
11220 "mailcap" (string &optional request no-decode))
11221 (defvar org-wait nil)
11222 (defun org-open-file (path &optional in-emacs line search)
11223 "Open the file at PATH.
11224 First, this expands any special file name abbreviations. Then the
11225 configuration variable `org-file-apps' is checked if it contains an
11226 entry for this file type, and if yes, the corresponding command is launched.
11228 If no application is found, Emacs simply visits the file.
11230 With optional prefix argument IN-EMACS, Emacs will visit the file.
11231 With a double \\[universal-argument] \\[universal-argument] \
11232 prefix arg, Org tries to avoid opening in Emacs
11233 and to use an external application to visit the file.
11235 Optional LINE specifies a line to go to, optional SEARCH a string
11236 to search for. If LINE or SEARCH is given, the file will be
11237 opened in Emacs, unless an entry from org-file-apps that makes
11238 use of groups in a regexp matches.
11240 If you want to change the way frames are used when following a
11241 link, please customize `org-link-frame-setup'.
11243 If the file does not exist, an error is thrown."
11244 (let* ((file (if (equal path "")
11246 (substitute-in-file-name (expand-file-name path))))
11247 (file-apps (append org-file-apps (org-default-apps)))
11248 (apps (org-remove-if
11249 'org-file-apps-entry-match-against-dlink-p file-apps))
11250 (apps-dlink (org-remove-if-not
11251 'org-file-apps-entry-match-against-dlink-p file-apps))
11252 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11253 (dirp (if remp nil (file-directory-p file)))
11254 (file (if (and dirp org-open-directory-means-index-dot-org)
11255 (concat (file-name-as-directory file) "index.org")
11257 (a-m-a-p (assq 'auto-mode apps))
11258 (dfile (downcase file))
11259 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11260 (link (cond ((and (eq line nil)
11264 (concat file "::" (number-to-string line)))
11266 (concat file "::" search))))
11267 (dlink (downcase link))
11268 (old-buffer (current-buffer))
11270 (old-mode major-mode)
11271 ext cmd link-match-data)
11272 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11273 (setq ext (match-string 1 dfile))
11274 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11275 (setq ext (match-string 1 dfile))))
11277 ((member in-emacs '((16) system))
11278 (setq cmd (cdr (assoc 'system apps))))
11279 (in-emacs (setq cmd 'emacs))
11281 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11282 (and dirp (cdr (assoc 'directory apps)))
11283 ; first, try matching against apps-dlink
11284 ; if we get a match here, store the match data for later
11285 (let ((match (assoc-default dlink apps-dlink
11288 (progn (setq link-match-data (match-data))
11290 (progn (setq in-emacs (or in-emacs line search))
11291 nil))) ; if we have no match in apps-dlink,
11292 ; always open the file in emacs if line or search
11293 ; is given (for backwards compatibility)
11294 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11296 (cdr (assoc ext apps))
11297 (cdr (assoc t apps))))))
11298 (when (eq cmd 'system)
11299 (setq cmd (cdr (assoc 'system apps))))
11300 (when (eq cmd 'default)
11301 (setq cmd (cdr (assoc t apps))))
11302 (when (eq cmd 'mailcap)
11304 (mailcap-parse-mailcaps)
11305 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11306 (command (mailcap-mime-info mime-type)))
11307 (if (stringp command)
11309 (setq cmd 'emacs))))
11310 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11311 (not (file-exists-p file))
11312 (not org-open-non-existing-files))
11313 (user-error "No such file: %s" file))
11315 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11316 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11317 (while (string-match "['\"]%s['\"]" cmd)
11318 (setq cmd (replace-match "%s" t t cmd)))
11319 (while (string-match "%s" cmd)
11320 (setq cmd (replace-match
11322 (shell-quote-argument
11323 (convert-standard-filename file)))
11326 ;; Replace "%1", "%2" etc. in command with group matches from regex
11328 (let ((match-index 1)
11329 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11330 (set-match-data link-match-data)
11331 (while (<= match-index number-of-groups)
11332 (let ((regex (concat "%" (number-to-string match-index)))
11333 (replace-with (match-string match-index dlink)))
11334 (while (string-match regex cmd)
11335 (setq cmd (replace-match replace-with t t cmd))))
11336 (setq match-index (+ match-index 1)))))
11338 (save-window-excursion
11339 (message "Running %s...done" cmd)
11340 (start-process-shell-command cmd nil cmd)
11341 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11344 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11346 (if line (progn (org-goto-line line)
11347 (if (derived-mode-p 'org-mode)
11349 (if search (org-link-search search))))
11351 (let ((file (convert-standard-filename file)))
11353 (set-match-data link-match-data)
11355 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11356 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11357 (or (not (equal old-buffer (current-buffer)))
11358 (not (equal old-pos (point))))
11359 (org-mark-ring-push old-pos old-buffer))))
11361 (defun org-file-apps-entry-match-against-dlink-p (entry)
11362 "This function returns non-nil if `entry' uses a regular
11363 expression which should be matched against the whole link by
11366 It assumes that is the case when the entry uses a regular
11367 expression which has at least one grouping construct and the
11368 action is either a lisp form or a command string containing
11369 '%1', i.e. using at least one subexpression match as a
11371 (let ((selector (car entry))
11372 (action (cdr entry)))
11373 (if (stringp selector)
11374 (and (> (regexp-opt-depth selector) 0)
11375 (or (and (stringp action)
11376 (string-match "%[0-9]" action))
11380 (defun org-default-apps ()
11381 "Return the default applications for this operating system."
11383 ((eq system-type 'darwin)
11384 org-file-apps-defaults-macosx)
11385 ((eq system-type 'windows-nt)
11386 org-file-apps-defaults-windowsnt)
11387 (t org-file-apps-defaults-gnu)))
11389 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11390 "Convert extensions to regular expressions in the cars of LIST.
11391 Also, weed out any non-string entries, because the return value is used
11392 only for regexp matching.
11393 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11394 point to the symbol `emacs', indicating that the file should
11395 be opened in Emacs."
11398 (mapcar (lambda (x)
11399 (if (not (stringp (car x)))
11401 (if (string-match "\\W" (car x))
11403 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11406 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11408 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11409 (defun org-file-remote-p (file)
11410 "Test whether FILE specifies a location on a remote system.
11411 Return non-nil if the location is indeed remote.
11413 For example, the filename \"/user@host:/foo\" specifies a location
11414 on the system \"/user@host:\"."
11415 (cond ((fboundp 'file-remote-p)
11416 (file-remote-p file))
11417 ((fboundp 'tramp-handle-file-remote-p)
11418 (tramp-handle-file-remote-p file))
11419 ((and (boundp 'ange-ftp-name-format)
11420 (string-match (car ange-ftp-name-format) file))
11426 (defun org-get-org-file ()
11427 "Read a filename, with default directory `org-directory'."
11428 (let ((default (or org-default-notes-file remember-data-file)))
11429 (read-file-name (format "File name [%s]: " default)
11430 (file-name-as-directory org-directory)
11433 (defun org-notes-order-reversed-p ()
11434 "Check if the current file should receive notes in reversed order."
11436 ((not org-reverse-note-order) nil)
11437 ((eq t org-reverse-note-order) t)
11438 ((not (listp org-reverse-note-order)) nil)
11440 (let ((all org-reverse-note-order)
11442 (while (setq entry (pop all))
11443 (if (string-match (car entry) buffer-file-name)
11444 (throw 'exit (cdr entry))))
11447 (defvar org-refile-target-table nil
11448 "The list of refile targets, created by `org-refile'.")
11450 (defvar org-agenda-new-buffers nil
11451 "Buffers created to visit agenda files.")
11453 (defvar org-refile-cache nil
11454 "Cache for refile targets.")
11456 (defvar org-refile-markers nil
11457 "All the markers used for caching refile locations.")
11459 (defun org-refile-marker (pos)
11460 "Get a new refile marker, but only if caching is in use."
11461 (if (not org-refile-use-cache)
11463 (let ((m (make-marker)))
11464 (move-marker m pos)
11465 (push m org-refile-markers)
11468 (defun org-refile-cache-clear ()
11469 "Clear the refile cache and disable all the markers."
11470 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11471 (setq org-refile-markers nil)
11472 (setq org-refile-cache nil)
11473 (message "Refile cache has been cleared"))
11475 (defun org-refile-cache-check-set (set)
11476 "Check if all the markers in the cache still have live buffers."
11479 (while (and set (setq marker (nth 3 (pop set))))
11480 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11481 (when (and marker (null (marker-buffer marker)))
11482 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11484 (throw 'exit nil)))
11487 (defun org-refile-cache-put (set &rest identifiers)
11488 "Push the refile targets SET into the cache, under IDENTIFIERS."
11489 (let* ((key (sha1 (prin1-to-string identifiers)))
11490 (entry (assoc key org-refile-cache)))
11493 (push (cons key set) org-refile-cache))))
11495 (defun org-refile-cache-get (&rest identifiers)
11496 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11498 ((not org-refile-cache) nil)
11499 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11501 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11502 org-refile-cache))))
11503 (and set (org-refile-cache-check-set set) set)))))
11505 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11506 "Produce a table with refile targets."
11507 (let ((case-fold-search nil)
11508 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11509 (entries (or org-refile-targets '((nil . (:level . 1)))))
11510 targets tgs txt re files f desc descre fast-path-p level pos0)
11511 (message "Getting targets...")
11512 (with-current-buffer (or default-buffer (current-buffer))
11513 (while (setq entry (pop entries))
11514 (setq files (car entry) desc (cdr entry))
11515 (setq fast-path-p nil)
11517 ((null files) (setq files (list (current-buffer))))
11518 ((eq files 'org-agenda-files)
11519 (setq files (org-agenda-files 'unrestricted)))
11520 ((and (symbolp files) (fboundp files))
11521 (setq files (funcall files)))
11522 ((and (symbolp files) (boundp files))
11523 (setq files (symbol-value files))))
11524 (if (stringp files) (setq files (list files)))
11526 ((eq (car desc) :tag)
11527 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11528 ((eq (car desc) :todo)
11529 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11530 ((eq (car desc) :regexp)
11531 (setq descre (cdr desc)))
11532 ((eq (car desc) :level)
11533 (setq descre (concat "^\\*\\{" (number-to-string
11534 (if org-odd-levels-only
11535 (1- (* 2 (cdr desc)))
11538 ((eq (car desc) :maxlevel)
11539 (setq fast-path-p t)
11540 (setq descre (concat "^\\*\\{1," (number-to-string
11541 (if org-odd-levels-only
11542 (1- (* 2 (cdr desc)))
11545 (t (error "Bad refiling target description %s" desc)))
11546 (while (setq f (pop files))
11547 (with-current-buffer
11548 (if (bufferp f) f (org-get-agenda-file-buffer f))
11550 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11552 (if (bufferp f) (setq f (buffer-file-name
11553 (buffer-base-buffer f))))
11554 (setq f (and f (expand-file-name f)))
11555 (if (eq org-refile-use-outline-path 'file)
11556 (push (list (file-name-nondirectory f) f nil nil) tgs))
11560 (goto-char (point-min))
11561 (while (re-search-forward descre nil t)
11562 (goto-char (setq pos0 (point-at-bol)))
11564 (when org-refile-target-verify-function
11566 (or (funcall org-refile-target-verify-function)
11568 (when (and (looking-at org-complex-heading-regexp)
11569 (not (member (match-string 4) excluded-entries))
11571 (setq level (org-reduced-level
11572 (- (match-end 1) (match-beginning 1)))
11573 txt (org-link-display-format (match-string 4))
11574 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11575 re (format org-complex-heading-regexp-format
11576 (regexp-quote (match-string 4))))
11577 (when org-refile-use-outline-path
11578 (setq txt (mapconcat
11581 (if (eq org-refile-use-outline-path
11583 (list (file-name-nondirectory
11585 (buffer-base-buffer))))
11586 (if (eq org-refile-use-outline-path
11588 (list (buffer-file-name
11589 (buffer-base-buffer)))))
11590 (org-get-outline-path fast-path-p
11594 (push (list txt f re (org-refile-marker (point)))
11596 (when (= (point) pos0)
11597 ;; verification function has not moved point
11598 (goto-char (point-at-eol))))))))
11599 (when org-refile-use-cache
11600 (org-refile-cache-put tgs (buffer-file-name) descre))
11601 (setq targets (append tgs targets))))))
11602 (message "Getting targets...done")
11603 (nreverse targets)))
11605 (defun org-protect-slash (s)
11606 (while (string-match "/" s)
11607 (setq s (replace-match "\\" t t s)))
11610 (defvar org-olpa (make-vector 20 nil))
11612 (defun org-get-outline-path (&optional fastp level heading)
11613 "Return the outline path to the current entry, as a list.
11615 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11616 routine which makes outline path derivations for an entire file,
11617 avoiding backtracing. Refile target collection makes use of that."
11621 (error "Outline path failure, more than 19 levels"))
11622 (loop for i from level upto 19 do
11623 (aset org-olpa i nil))
11625 (delq nil (append org-olpa nil))
11626 (aset org-olpa level heading)))
11627 (let (rtn case-fold-search)
11631 (while (org-up-heading-safe)
11632 (when (looking-at org-complex-heading-regexp)
11634 (replace-regexp-in-string
11635 ;; Remove statistical/checkboxes cookies
11636 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11637 (org-match-string-no-properties 4)))
11641 (defun org-format-outline-path (path &optional width prefix separator)
11642 "Format the outline path PATH for display.
11643 WIDTH is the maximum number of characters that is available.
11644 PREFIX is a prefix to be included in the returned string,
11645 such as the file name.
11646 SEPARATOR is inserted between the different parts of the path,
11647 the default is \"/\"."
11648 (setq width (or width 79))
11649 (if prefix (setq width (- width (length prefix))))
11652 (let* ((nsteps (length path))
11653 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11654 (maxwidth (if (<= total-width width)
11655 10000 ;; everything fits
11656 ;; we need to shorten the level headings
11657 (/ (- width nsteps) nsteps)))
11658 (org-odd-levels-only nil)
11660 (total (1+ (length prefix))))
11661 (setq maxwidth (max maxwidth 10))
11663 (if prefix (or separator "/"))
11667 (if (and (= n nsteps) (< maxwidth 10000))
11668 (setq maxwidth (- total-width total)))
11669 (if (< (length h) maxwidth)
11670 (progn (setq total (+ total (length h) 1)) h)
11671 (setq h (substring h 0 (- maxwidth 2))
11672 total (+ total maxwidth 1))
11673 (if (string-match "[ \t]+\\'" h)
11674 (setq h (substring h 0 (match-beginning 0))))
11675 (setq h (concat h "..")))
11676 (org-add-props h nil 'face
11677 (nth (% (1- n) org-n-level-faces)
11680 path (or separator "/"))))))
11682 (defun org-display-outline-path (&optional file current separator just-return-string)
11683 "Display the current outline path in the echo area.
11685 If FILE is non-nil, prepend the output with the file name.
11686 If CURRENT is non-nil, append the current heading to the output.
11687 SEPARATOR is passed through to `org-format-outline-path'. It separates
11688 the different parts of the path and defaults to \"/\".
11689 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11691 (let* (case-fold-search
11692 (bfn (buffer-file-name (buffer-base-buffer)))
11693 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11695 (if current (setq path (append path
11697 (org-back-to-heading t)
11698 (if (looking-at org-complex-heading-regexp)
11699 (list (match-string 4)))))))
11701 (org-format-outline-path
11704 (and file bfn (concat (file-name-nondirectory bfn) separator))
11706 (if just-return-string
11707 (org-no-properties res)
11708 (org-unlogged-message "%s" res))))
11710 (defvar org-refile-history nil
11711 "History for refiling operations.")
11713 (defvar org-after-refile-insert-hook nil
11714 "Hook run after `org-refile' has inserted its stuff at the new location.
11715 Note that this is still *before* the stuff will be removed from
11716 the *old* location.")
11718 (defvar org-capture-last-stored-marker)
11719 (defvar org-refile-keep nil
11720 "Non-nil means `org-refile' will copy instead of refile.")
11723 "Like `org-refile', but copy."
11725 (let ((org-refile-keep t))
11726 (funcall 'org-refile nil nil nil "Copy")))
11728 (defun org-refile (&optional arg default-buffer rfloc msg)
11729 "Move the entry or entries at point to another heading.
11730 The list of target headings is compiled using the information in
11731 `org-refile-targets', which see.
11733 At the target location, the entry is filed as a subitem of the
11734 target heading. Depending on `org-reverse-note-order', the new
11735 subitem will either be the first or the last subitem.
11737 If there is an active region, all entries in that region will be
11738 refiled. However, the region must fulfill the requirement that
11739 the first heading sets the top-level of the moved text.
11741 With prefix arg ARG, the command will only visit the target
11742 location and not actually move anything.
11744 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11745 refiling operation has put the subtree.
11747 With a numeric prefix argument of `2', refile to the running clock.
11749 With a numeric prefix argument of `3', emulate `org-refile-keep'
11750 being set to `t' and copy to the target location, don't move it.
11751 Beware that keeping refiled entries may result in duplicated ID
11754 RFLOC can be a refile location obtained in a different way.
11756 MSG is a string to replace \"Refile\" in the default prompt with
11757 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11759 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11761 If you are using target caching (see `org-refile-use-cache'), you
11762 have to clear the target cache in order to find new targets.
11763 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11764 prefix argument (`C-u C-u C-u C-c C-w')."
11766 (if (member arg '(0 (64)))
11767 (org-refile-cache-clear)
11768 (let* ((actionmsg (cond (msg msg)
11769 ((equal arg 3) "Refile (and keep)")
11771 (cbuf (current-buffer))
11772 (regionp (org-region-active-p))
11773 (region-start (and regionp (region-beginning)))
11774 (region-end (and regionp (region-end)))
11775 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11776 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11777 pos it nbuf file re level reversed)
11778 (setq last-command nil)
11780 (goto-char region-start)
11781 (or (bolp) (goto-char (point-at-bol)))
11782 (setq region-start (point))
11783 (unless (or (org-kill-is-subtree-p
11784 (buffer-substring region-start region-end))
11785 (prog1 org-refile-active-region-within-subtree
11786 (let ((s (point-at-eol)))
11787 (org-toggle-heading)
11788 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11789 (user-error "The region is not a (sequence of) subtree(s)")))
11790 (if (equal arg '(16))
11791 (org-refile-goto-last-stored)
11794 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11796 (setq it (list (or org-clock-heading "running clock")
11798 (marker-buffer org-clock-hd-marker))
11800 (marker-position org-clock-hd-marker)))
11803 (let (heading-text)
11805 (unless (and arg (listp arg))
11806 (org-back-to-heading t)
11808 (replace-regexp-in-string
11809 org-bracket-link-regexp
11811 (nth 4 (org-heading-components)))))
11812 (org-refile-get-location
11813 (cond ((and arg (listp arg)) "Goto")
11814 (regionp (concat actionmsg " region to"))
11815 (t (concat actionmsg " subtree \""
11816 heading-text "\" to")))
11818 (and (not (equal '(4) arg))
11819 org-refile-allow-creating-parent-nodes)
11821 (setq file (nth 1 it)
11826 (equal (buffer-file-name) file)
11828 (and (>= pos region-start)
11829 (<= pos region-end))
11830 (and (>= pos (point))
11831 (< pos (save-excursion
11832 (org-end-of-subtree t t))))))
11833 (error "Cannot refile to position inside the tree or region"))
11834 (setq nbuf (or (find-buffer-visiting file)
11835 (find-file-noselect file)))
11836 (if (and arg (not (equal arg 3)))
11838 (org-pop-to-buffer-same-window nbuf)
11840 (org-show-context 'org-goto))
11843 (org-kill-new (buffer-substring region-start region-end))
11844 (org-save-markers-in-region region-start region-end))
11845 (org-copy-subtree 1 nil t))
11846 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11847 (find-file-noselect file)))
11848 (setq reversed (org-notes-order-reversed-p))
11855 (looking-at org-outline-regexp)
11856 (setq level (org-get-valid-level (funcall outline-level) 1))
11859 (or (outline-next-heading) (point-max))
11860 (or (save-excursion (org-get-next-sibling))
11861 (org-end-of-subtree t t)
11865 (goto-char (point-max))
11866 (goto-char (point-min))
11867 (or (outline-next-heading) (goto-char (point-max)))))
11868 (if (not (bolp)) (newline))
11869 (org-paste-subtree level nil nil t)
11870 (when org-log-refile
11871 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11872 (unless (eq org-log-refile 'note)
11873 (save-excursion (org-add-log-note))))
11874 (and org-auto-align-tags
11875 (let ((org-loop-over-headlines-in-active-region nil))
11876 (org-set-tags nil t)))
11877 (let ((bookmark-name (plist-get org-bookmark-names-plist
11879 (when bookmark-name
11880 (with-demoted-errors
11881 (bookmark-set bookmark-name))))
11882 ;; If we are refiling for capture, make sure that the
11883 ;; last-capture pointers point here
11884 (when (org-bound-and-true-p org-refile-for-capture)
11885 (let ((bookmark-name (plist-get org-bookmark-names-plist
11886 :last-capture-marker)))
11887 (when bookmark-name
11888 (with-demoted-errors
11889 (bookmark-set bookmark-name))))
11890 (move-marker org-capture-last-stored-marker (point)))
11891 (if (fboundp 'deactivate-mark) (deactivate-mark))
11892 (run-hooks 'org-after-refile-insert-hook))))
11893 (unless org-refile-keep
11895 (delete-region (point) (+ (point) (- region-end region-start)))
11897 (and (org-back-to-heading t) (point))
11898 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11899 (when (featurep 'org-inlinetask)
11900 (org-inlinetask-remove-END-maybe))
11901 (setq org-markers-to-move nil)
11902 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11904 (defun org-refile-goto-last-stored ()
11905 "Go to the location where the last refile was stored."
11907 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11908 (message "This is the location of the last refile"))
11910 (defun org-refile--get-location (refloc tbl)
11911 "When user refile to REFLOC, find the associated target in TBL.
11912 Also check `org-refile-target-table'."
11916 (lambda (r) (or (assoc r tbl)
11917 (assoc r org-refile-target-table)))
11918 (list (replace-regexp-in-string "/$" "" refloc)
11919 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11921 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11923 "Prompt the user for a refile location, using PROMPT.
11924 PROMPT should not be suffixed with a colon and a space, because
11925 this function appends the default value from
11926 `org-refile-history' automatically, if that is not empty.
11927 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11928 this is used for the GOTO interface."
11929 (let ((org-refile-targets org-refile-targets)
11930 (org-refile-use-outline-path org-refile-use-outline-path)
11932 (when (and (derived-mode-p 'org-mode)
11933 (not org-refile-use-cache)
11937 (setq excluded-entries
11938 (append excluded-entries (list (org-get-heading t t)))))))
11939 (setq org-refile-target-table
11940 (org-refile-get-targets default-buffer excluded-entries)))
11941 (unless org-refile-target-table
11942 (user-error "No refile targets"))
11943 (let* ((cbuf (current-buffer))
11944 (partial-completion-mode nil)
11945 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11946 (cfunc (if (and org-refile-use-outline-path
11947 org-outline-path-complete-in-steps)
11948 'org-olpath-completing-read
11949 'org-icompleting-read))
11950 (extra (if org-refile-use-outline-path "/" ""))
11951 (cbnex (concat (buffer-name) extra))
11952 (filename (and cfn (expand-file-name cfn)))
11955 (if (and (not (member org-refile-use-outline-path
11956 '(file full-file-path)))
11957 (not (equal filename (nth 1 x))))
11958 (cons (concat (car x) extra " ("
11959 (file-name-nondirectory (nth 1 x)) ")")
11961 (cons (concat (car x) extra) (cdr x))))
11962 org-refile-target-table))
11963 (completion-ignore-case t)
11965 (prompt (concat prompt
11966 (or (and (car org-refile-history)
11967 (concat " (default " (car org-refile-history) ")"))
11968 (and (assoc cbnex tbl) (setq cdef cbnex)
11969 (concat " (default " cbnex ")"))) ": "))
11970 pa answ parent-target child parent old-hist)
11971 (setq old-hist org-refile-history)
11972 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11973 nil 'org-refile-history (or cdef (car org-refile-history))))
11974 (if (setq pa (org-refile--get-location answ tbl))
11976 (org-refile-check-position pa)
11977 (when (or (not org-refile-history)
11978 (not (eq old-hist org-refile-history))
11979 (not (equal (car pa) (car org-refile-history))))
11980 (setq org-refile-history
11981 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11983 (cdr org-refile-history))))
11984 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11985 (pop org-refile-history)))
11987 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11989 (setq parent (match-string 1 answ)
11990 child (match-string 2 answ))
11991 (setq parent-target (org-refile--get-location parent tbl))
11992 (when (and parent-target
11993 (or (eq new-nodes t)
11994 (and (eq new-nodes 'confirm)
11995 (y-or-n-p (format "Create new node \"%s\"? "
11997 (org-refile-new-child parent-target child)))
11998 (user-error "Invalid target location")))))
12000 (declare-function org-string-nw-p "org-macs" (s))
12001 (defun org-refile-check-position (refile-pointer)
12002 "Check if the refile pointer matches the headline to which it points."
12003 (let* ((file (nth 1 refile-pointer))
12004 (re (nth 2 refile-pointer))
12005 (pos (nth 3 refile-pointer))
12007 (if (and (not (markerp pos)) (not file))
12008 (user-error "Please indicate a target file in the refile path")
12009 (when (org-string-nw-p re)
12010 (setq buffer (if (markerp pos)
12011 (marker-buffer pos)
12012 (or (find-buffer-visiting file)
12013 (find-file-noselect file))))
12014 (with-current-buffer buffer
12019 (beginning-of-line 1)
12020 (unless (org-looking-at-p re)
12021 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12023 (defun org-refile-new-child (parent-target child)
12024 "Use refile target PARENT-TARGET to add new CHILD below it."
12025 (unless parent-target
12026 (error "Cannot find parent for new node"))
12027 (let ((file (nth 1 parent-target))
12028 (pos (nth 3 parent-target))
12030 (with-current-buffer (or (find-buffer-visiting file)
12031 (find-file-noselect file))
12037 (goto-char (point-max))
12038 (if (not (bolp)) (newline)))
12039 (when (looking-at org-outline-regexp)
12040 (setq level (funcall outline-level))
12041 (org-end-of-subtree t t))
12042 (org-back-over-empty-lines)
12043 (insert "\n" (make-string
12044 (if pos (org-get-valid-level level 1) 1) ?*)
12046 (beginning-of-line 0)
12047 (list (concat (car parent-target) "/" child) file "" (point)))))))
12049 (defun org-olpath-completing-read (prompt collection &rest args)
12050 "Read an outline path like a file name."
12051 (let ((thetable collection)
12052 (org-completion-use-ido nil) ; does not work with ido.
12053 (org-completion-use-iswitchb nil)) ; or iswitchb
12055 'org-icompleting-read prompt
12056 (lambda (string predicate &optional flag)
12057 (let (rtn r f (l (length string)))
12061 (try-completion string thetable))
12064 (setq rtn (all-completions string thetable predicate))
12067 (setq r (substring x l))
12068 (if (string-match " ([^)]*)$" x)
12069 (setq f (match-string 0 x))
12071 (if (string-match "/" r)
12072 (concat string (substring r 0 (match-end 0)) f)
12077 (assoc string thetable)))))
12080 ;;;; Dynamic blocks
12082 (defun org-find-dblock (name)
12083 "Find the first dynamic block with name NAME in the buffer.
12084 If not found, stay at current position and return nil."
12085 (let ((case-fold-search t) pos)
12087 (goto-char (point-min))
12088 (setq pos (and (re-search-forward
12089 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12090 (match-beginning 0))))
12091 (if pos (goto-char pos))
12094 (defun org-create-dblock (plist)
12095 "Create a dynamic block section, with parameters taken from PLIST.
12096 PLIST must contain a :name entry which is used as the name of the block."
12097 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12100 (let ((col (current-column))
12101 (name (plist-get plist :name)))
12102 (insert "#+BEGIN: " name)
12104 (if (eq (car plist) :name)
12105 (setq plist (cddr plist))
12106 (insert " " (prin1-to-string (pop plist)))))
12107 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12108 (beginning-of-line -2)))
12110 (defun org-prepare-dblock ()
12111 "Prepare dynamic block for refresh.
12112 This empties the block, puts the cursor at the insert position and returns
12113 the property list including an extra property :name with the block name."
12114 (unless (looking-at org-dblock-start-re)
12115 (user-error "Not at a dynamic block"))
12116 (let* ((begdel (1+ (match-end 0)))
12117 (name (org-no-properties (match-string 1)))
12118 (params (append (list :name name)
12119 (read (concat "(" (match-string 3) ")")))))
12121 (beginning-of-line 1)
12122 (skip-chars-forward " \t")
12123 (setq params (plist-put params :indentation-column (current-column))))
12124 (unless (re-search-forward org-dblock-end-re nil t)
12125 (error "Dynamic block not terminated"))
12128 (list :content (buffer-substring
12129 begdel (match-beginning 0)))))
12130 (delete-region begdel (match-beginning 0))
12135 (defun org-map-dblocks (&optional command)
12136 "Apply COMMAND to all dynamic blocks in the current buffer.
12137 If COMMAND is not given, use `org-update-dblock'."
12138 (let ((cmd (or command 'org-update-dblock)))
12140 (goto-char (point-min))
12141 (while (re-search-forward org-dblock-start-re nil t)
12142 (goto-char (match-beginning 0))
12144 (condition-case nil
12146 (error (message "Error during update of dynamic block"))))
12147 (unless (re-search-forward org-dblock-end-re nil t)
12148 (error "Dynamic block not terminated"))))))
12150 (defun org-dblock-update (&optional arg)
12151 "User command for updating dynamic blocks.
12152 Update the dynamic block at point. With prefix ARG, update all dynamic
12153 blocks in the buffer."
12156 (org-update-all-dblocks)
12157 (or (looking-at org-dblock-start-re)
12158 (org-beginning-of-dblock))
12159 (org-update-dblock)))
12161 (defun org-update-dblock ()
12162 "Update the dynamic block at point.
12163 This means to empty the block, parse for parameters and then call
12164 the correct writing function."
12167 (let* ((win (selected-window))
12169 (line (org-current-line))
12170 (params (org-prepare-dblock))
12171 (name (plist-get params :name))
12172 (indent (plist-get params :indentation-column))
12173 (cmd (intern (concat "org-dblock-write:" name))))
12174 (message "Updating dynamic block `%s' at line %d..." name line)
12175 (funcall cmd params)
12176 (message "Updating dynamic block `%s' at line %d...done" name line)
12178 (when (and indent (> indent 0))
12179 (setq indent (make-string indent ?\ ))
12181 (select-window win)
12182 (org-beginning-of-dblock)
12184 (while (not (looking-at org-dblock-end-re))
12186 (beginning-of-line 2))
12187 (when (looking-at org-dblock-end-re)
12188 (and (looking-at "[ \t]+")
12189 (replace-match ""))
12190 (insert indent)))))))
12192 (defun org-beginning-of-dblock ()
12193 "Find the beginning of the dynamic block at point.
12194 Error if there is no such block at point."
12195 (let ((pos (point))
12198 (if (and (re-search-backward org-dblock-start-re nil t)
12199 (setq beg (match-beginning 0))
12200 (re-search-forward org-dblock-end-re nil t)
12201 (> (match-end 0) pos))
12204 (error "Not in a dynamic block"))))
12206 (defun org-update-all-dblocks ()
12207 "Update all dynamic blocks in the buffer.
12208 This function can be used in a hook."
12210 (when (derived-mode-p 'org-mode)
12211 (org-map-dblocks 'org-update-dblock)))
12216 (declare-function org-export-backend-name "org-export" (cl-x))
12217 (declare-function org-export-backend-options "org-export" (cl-x))
12218 (defun org-get-export-keywords ()
12219 "Return a list of all currently understood export keywords.
12220 Export keywords include options, block names, attributes and
12221 keywords relative to each registered export back-end."
12224 (org-bound-and-true-p org-export--registered-backends)
12225 (delq nil keywords))
12226 ;; Back-end name (for keywords, like #+LATEX:)
12227 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12228 (dolist (option-entry (org-export-backend-options backend))
12229 ;; Back-end options.
12230 (push (nth 1 option-entry) keywords)))))
12232 (defconst org-options-keywords
12233 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12234 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12235 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12236 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12237 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12239 (defcustom org-structure-template-alist
12240 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12241 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12242 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12243 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12244 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12245 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12246 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12248 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12250 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12253 ("I" "#+INCLUDE: %file ?"))
12254 "Structure completion elements.
12255 This is a list of abbreviation keys and values. The value gets inserted
12256 if you type `<' followed by the key and then press the completion key,
12257 usually `TAB'. %file will be replaced by a file name after prompting
12258 for the file using completion. The cursor will be placed at the position
12259 of the `?` in the template.
12260 There are two templates for each key, the first uses the original Org syntax,
12261 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12262 the default when the /org-mtags.el/ module has been loaded. See also the
12263 variable `org-mtags-prefer-muse-templates'."
12264 :group 'org-completion
12267 (string :tag "Key")
12268 (string :tag "Template")))
12270 :package-version '(Org . "8.3"))
12272 (defun org-try-structure-completion ()
12273 "Try to complete a structure template before point.
12274 This looks for strings like \"<e\" on an otherwise empty line and
12276 (let ((l (buffer-substring (point-at-bol) (point)))
12278 (when (and (looking-at "[ \t]*$")
12279 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12280 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12281 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12282 (match-beginning 1)) a)
12285 (defun org-complete-expand-structure-template (start cell)
12286 "Expand a structure template."
12287 (let ((rpl (nth 1 cell))
12289 (delete-region start (point))
12290 (when (string-match "\\`[ \t]*#\\+" rpl)
12293 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12294 (setq ind (buffer-substring (point-at-bol) (point))))
12296 (setq start (point))
12297 (if (string-match "%file" rpl)
12298 (setq rpl (replace-match
12302 (abbreviate-file-name (read-file-name "Include file: ")))
12305 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12306 (concat "\n" ind)))
12308 (if (re-search-backward "\\?" start t) (delete-char 1))))
12310 ;;;; TODO, DEADLINE, Comments
12312 (defun org-toggle-comment ()
12313 "Change the COMMENT state of an entry."
12316 (org-back-to-heading)
12317 (looking-at org-complex-heading-regexp)
12318 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12319 (skip-chars-forward " \t")
12320 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12321 (if (org-in-commented-heading-p t)
12322 (delete-region (point)
12323 (progn (search-forward " " (line-end-position) 'move)
12324 (skip-chars-forward " \t")
12326 (insert org-comment-string)
12327 (unless (eolp) (insert " ")))))
12329 (defvar org-last-todo-state-is-todo nil
12330 "This is non-nil when the last TODO state change led to a TODO state.
12331 If the last change removed the TODO tag or switched to DONE, then
12334 (defvar org-setting-tags nil) ; dynamically skipped
12336 (defvar org-todo-setup-filter-hook nil
12337 "Hook for functions that pre-filter todo specs.
12338 Each function takes a todo spec and returns either nil or the spec
12339 transformed into canonical form." )
12341 (defvar org-todo-get-default-hook nil
12342 "Hook for functions that get a default item for todo.
12343 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12344 nil or a string to be used for the todo mark." )
12346 (defvar org-agenda-headline-snapshot-before-repeat)
12348 (defun org-current-effective-time ()
12349 "Return current time adjusted for `org-extend-today-until' variable."
12350 (let* ((ct (org-current-time))
12351 (dct (decode-time ct))
12354 (org-use-last-clock-out-time-as-effective-time
12355 (or (org-clock-get-last-clock-out-time) ct))
12356 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12357 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12361 (defun org-todo-yesterday (&optional arg)
12362 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12364 (if (eq major-mode 'org-agenda-mode)
12365 (apply 'org-agenda-todo-yesterday arg)
12366 (let* ((hour (third (decode-time
12367 (org-current-time))))
12368 (org-extend-today-until (1+ hour)))
12371 (defvar org-block-entry-blocking ""
12372 "First entry preventing the TODO state change.")
12374 (defun org-cancel-repeater ()
12375 "Cancel a repeater by setting its numeric value to zero."
12378 (org-back-to-heading t)
12379 (let ((bound1 (point))
12380 (bound0 (save-excursion (outline-next-heading) (point))))
12381 (when (re-search-forward
12382 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12383 org-deadline-time-regexp "\\)\\|\\("
12384 org-ts-regexp "\\)")
12386 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12387 (replace-match "0" t nil nil 1))))))
12389 (defun org-todo (&optional arg)
12390 "Change the TODO state of an item.
12391 The state of an item is given by a keyword at the start of the heading,
12393 *** TODO Write paper
12396 The different keywords are specified in the variable `org-todo-keywords'.
12397 By default the available states are \"TODO\" and \"DONE\".
12398 So for this example: when the item starts with TODO, it is changed to DONE.
12399 When it starts with DONE, the DONE is removed. And when neither TODO nor
12400 DONE are present, add TODO at the beginning of the heading.
12402 With \\[universal-argument] prefix arg, use completion to determine the new \
12404 With numeric prefix arg, switch to that state.
12405 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12406 keywords (nextset).
12407 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12408 With a numeric prefix arg of 0, inhibit note taking for the change.
12409 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12411 When called through ELisp, arg is also interpreted in the following way:
12412 'none -> empty state
12413 \"\"(empty string) -> switch to empty state
12414 'done -> switch to DONE
12415 'nextset -> switch to the next set of keywords
12416 'previousset -> switch to the previous set of keywords
12417 \"WAITING\" -> switch to the specified keyword, but only if it
12418 really is a member of `org-todo-keywords'."
12420 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12421 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12422 'region-start-level 'region))
12423 org-loop-over-headlines-in-active-region)
12426 org-loop-over-headlines-in-active-region
12427 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12428 (if (equal arg '(16)) (setq arg 'nextset))
12429 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12430 (let ((org-blocker-hook org-blocker-hook)
12433 (when (equal arg '(64))
12434 (setq arg nil org-blocker-hook nil))
12435 (when (and org-blocker-hook
12436 (or org-inhibit-blocking
12437 (org-entry-get nil "NOBLOCKING")))
12438 (setq org-blocker-hook nil))
12441 (org-back-to-heading t)
12442 (when (org-in-commented-heading-p t)
12443 (org-toggle-comment)
12445 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12446 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12447 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12448 (let* ((match-data (match-data))
12449 (startpos (point-at-bol))
12450 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12451 (org-log-done org-log-done)
12452 (org-log-repeat org-log-repeat)
12453 (org-todo-log-states org-todo-log-states)
12454 (org-inhibit-logging
12456 (progn (setq arg nil) 'note) org-inhibit-logging))
12457 (this (match-string 1))
12458 (hl-pos (match-beginning 0))
12459 (head (org-get-todo-sequence-head this))
12460 (ass (assoc head org-todo-kwd-alist))
12461 (interpret (nth 1 ass))
12462 (done-word (nth 3 ass))
12463 (final-done-word (nth 4 ass))
12464 (org-last-state (or this ""))
12465 (completion-ignore-case t)
12466 (member (member this org-todo-keywords-1))
12467 (tail (cdr member))
12469 ((and org-todo-key-trigger
12470 (or (and (equal arg '(4))
12471 (eq org-use-fast-todo-selection 'prefix))
12472 (and (not arg) org-use-fast-todo-selection
12473 (not (eq org-use-fast-todo-selection
12475 ;; Use fast selection
12476 (org-fast-todo-selection))
12477 ((and (equal arg '(4))
12478 (or (not org-use-fast-todo-selection)
12479 (not org-todo-key-trigger)))
12480 ;; Read a state with completion
12481 (org-icompleting-read
12482 "State: " (mapcar 'list org-todo-keywords-1)
12486 (if tail (car tail) nil)
12487 (car org-todo-keywords-1)))
12489 (if (equal member org-todo-keywords-1)
12492 (nth (- (length org-todo-keywords-1)
12494 org-todo-keywords-1)
12495 (org-last org-todo-keywords-1))))
12496 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12497 (setq arg nil))) ; hack to fall back to cycling
12499 ;; user or caller requests a specific state
12501 ((equal arg "") nil)
12502 ((eq arg 'none) nil)
12503 ((eq arg 'done) (or done-word (car org-done-keywords)))
12505 (or (car (cdr (member head org-todo-heads)))
12506 (car org-todo-heads)))
12507 ((eq arg 'previousset)
12508 (let ((org-todo-heads (reverse org-todo-heads)))
12509 (or (car (cdr (member head org-todo-heads)))
12510 (car org-todo-heads))))
12511 ((car (member arg org-todo-keywords-1)))
12513 (user-error "State `%s' not valid in this file" arg))
12514 ((nth (1- (prefix-numeric-value arg))
12515 org-todo-keywords-1))))
12516 ((null member) (or head (car org-todo-keywords-1)))
12517 ((equal this final-done-word) nil) ;; -> make empty
12518 ((null tail) nil) ;; -> first entry
12519 ((memq interpret '(type priority))
12520 (if (eq this-command last-command)
12522 (if (> (length tail) 0)
12523 (or done-word (car org-done-keywords))
12528 (run-hook-with-args-until-success
12529 'org-todo-get-default-hook org-state org-last-state)
12531 (next (if org-state (concat " " org-state " ") " "))
12532 (change-plist (list :type 'todo-state-change :from this :to org-state
12533 :position startpos))
12535 (when org-blocker-hook
12536 (setq org-last-todo-state-is-todo
12537 (not (member this org-done-keywords)))
12538 (unless (save-excursion
12540 (org-with-wide-buffer
12541 (run-hook-with-args-until-failure
12542 'org-blocker-hook change-plist))))
12543 (if (org-called-interactively-p 'interactive)
12544 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12545 this org-state org-block-entry-blocking)
12547 (message "TODO state change from %s to %s blocked (by \"%s\")"
12548 this org-state org-block-entry-blocking)
12549 (throw 'exit nil))))
12550 (store-match-data match-data)
12551 (replace-match next t t)
12552 (cond ((equal this org-state)
12553 (message "TODO state was already %s" (org-trim next)))
12554 ((pos-visible-in-window-p hl-pos)
12555 (message "TODO state changed to %s" (org-trim next))))
12557 (setq head (org-get-todo-sequence-head org-state)
12558 ass (assoc head org-todo-kwd-alist)
12559 interpret (nth 1 ass)
12560 done-word (nth 3 ass)
12561 final-done-word (nth 4 ass)))
12562 (when (memq arg '(nextset previousset))
12563 (message "Keyword-Set %d/%d: %s"
12564 (- (length org-todo-sets) -1
12565 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12566 (length org-todo-sets)
12567 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12568 (setq org-last-todo-state-is-todo
12569 (not (member org-state org-done-keywords)))
12570 (setq now-done-p (and (member org-state org-done-keywords)
12571 (not (member this org-done-keywords))))
12572 (and logging (org-local-logging logging))
12573 (when (and (or org-todo-log-states org-log-done)
12574 (not (eq org-inhibit-logging t))
12575 (not (memq arg '(nextset previousset))))
12576 ;; we need to look at recording a time and note
12577 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12578 (nth 2 (assoc this org-todo-log-states))))
12579 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12580 (setq dolog 'time))
12581 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12583 (member org-state org-not-done-keywords)
12584 (not (member this org-not-done-keywords))))
12585 ;; This is now a todo state and was not one before
12586 ;; If there was a CLOSED time stamp, get rid of it.
12587 (org-add-planning-info nil nil 'closed))
12588 (when (and now-done-p org-log-done)
12589 ;; It is now done, and it was not done before
12590 (org-add-planning-info 'closed (org-current-effective-time))
12591 (if (and (not dolog) (eq 'note org-log-done))
12592 (org-add-log-setup 'done org-state this 'findpos 'note)))
12593 (when (and org-state dolog)
12594 ;; This is a non-nil state, and we need to log it
12595 (org-add-log-setup 'state org-state this 'findpos dolog)))
12596 ;; Fixup tag positioning
12597 (org-todo-trigger-tag-changes org-state)
12598 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12599 (when org-provide-todo-statistics
12600 (org-update-parent-todo-statistics))
12601 (run-hooks 'org-after-todo-state-change-hook)
12602 (if (and arg (not (member org-state org-done-keywords)))
12603 (setq head (org-get-todo-sequence-head org-state)))
12604 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12605 ;; Do we need to trigger a repeat?
12607 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12608 ;; This is for the agenda, take a snapshot of the headline.
12610 (setq org-agenda-headline-snapshot-before-repeat
12611 (org-get-heading))))
12612 (org-auto-repeat-maybe org-state))
12613 ;; Fixup cursor location if close to the keyword
12614 (if (and (outline-on-heading-p)
12616 (save-excursion (beginning-of-line 1)
12617 (looking-at org-todo-line-regexp))
12618 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12620 (goto-char (or (match-end 2) (match-end 1)))
12621 (and (looking-at " ") (just-one-space))))
12622 (when org-trigger-hook
12624 (run-hook-with-args 'org-trigger-hook change-plist)))
12625 (when commentp (org-toggle-comment))))))))
12627 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12628 "Block turning an entry into a TODO, using the hierarchy.
12629 This checks whether the current task should be blocked from state
12630 changes. Such blocking occurs when:
12632 1. The task has children which are not all in a completed state.
12634 2. A task has a parent with the property :ORDERED:, and there
12635 are siblings prior to the current task with incomplete
12638 3. The parent of the task is blocked because it has siblings that should
12639 be done first, or is child of a block grandparent TODO entry."
12641 (if (not org-enforce-todo-dependencies)
12642 t ; if locally turned off don't block
12644 ;; If this is not a todo state change, or if this entry is already DONE,
12646 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12647 (member (plist-get change-plist :from)
12648 (cons 'done org-done-keywords))
12649 (member (plist-get change-plist :to)
12650 (cons 'todo org-not-done-keywords))
12651 (not (plist-get change-plist :to)))
12652 (throw 'dont-block t))
12653 ;; If this task has children, and any are undone, it's blocked
12655 (org-back-to-heading t)
12656 (let ((this-level (funcall outline-level)))
12657 (outline-next-heading)
12658 (let ((child-level (funcall outline-level)))
12659 (while (and (not (eobp))
12660 (> child-level this-level))
12661 ;; this todo has children, check whether they are all
12663 (if (and (not (org-entry-is-done-p))
12664 (org-entry-is-todo-p))
12665 (progn (setq org-block-entry-blocking (org-get-heading))
12666 (throw 'dont-block nil)))
12667 (outline-next-heading)
12668 (setq child-level (funcall outline-level))))))
12669 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12670 ;; any previous siblings are undone, it's blocked
12672 (org-back-to-heading t)
12673 (let* ((pos (point))
12674 (parent-pos (and (org-up-heading-safe) (point))))
12675 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12676 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12678 (re-search-forward org-not-done-heading-regexp pos t))
12679 (setq org-block-entry-blocking (match-string 0))
12680 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12681 ;; Search further up the hierarchy, to see if an ancestor is blocked
12683 (goto-char parent-pos)
12684 (if (not (looking-at org-not-done-heading-regexp))
12685 (throw 'dont-block t)) ; do not block, parent is not a TODO
12687 (setq parent-pos (and (org-up-heading-safe) (point)))
12688 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12689 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12691 (re-search-forward org-not-done-heading-regexp pos t)
12692 (setq org-block-entry-blocking (org-get-heading)))
12693 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12695 (defcustom org-track-ordered-property-with-tag nil
12696 "Should the ORDERED property also be shown as a tag?
12697 The ORDERED property decides if an entry should require subtasks to be
12698 completed in sequence. Since a property is not very visible, setting
12699 this option means that toggling the ORDERED property with the command
12700 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12701 not relevant for the behavior, but it makes things more visible.
12703 Note that toggling the tag with tags commands will not change the property
12704 and therefore not influence behavior!
12706 This can be t, meaning the tag ORDERED should be used, It can also be a
12707 string to select a different tag for this task."
12710 (const :tag "No tracking" nil)
12711 (const :tag "Track with ORDERED tag" t)
12712 (string :tag "Use other tag")))
12714 (defun org-toggle-ordered-property ()
12715 "Toggle the ORDERED property of the current entry.
12716 For better visibility, you can track the value of this property with a tag.
12717 See variable `org-track-ordered-property-with-tag'."
12719 (let* ((t1 org-track-ordered-property-with-tag)
12720 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12722 (org-back-to-heading)
12723 (if (org-entry-get nil "ORDERED")
12725 (org-delete-property "ORDERED")
12726 (and tag (org-toggle-tag tag 'off))
12727 (message "Subtasks can be completed in arbitrary order"))
12728 (org-entry-put nil "ORDERED" "t")
12729 (and tag (org-toggle-tag tag 'on))
12730 (message "Subtasks must be completed in sequence")))))
12732 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12733 (defun org-block-todo-from-checkboxes (change-plist)
12734 "Block turning an entry into a TODO, using checkboxes.
12735 This checks whether the current task should be blocked from state
12736 changes because there are unchecked boxes in this entry."
12737 (if (not org-enforce-todo-checkbox-dependencies)
12738 t ; if locally turned off don't block
12740 ;; If this is not a todo state change, or if this entry is already DONE,
12742 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12743 (member (plist-get change-plist :from)
12744 (cons 'done org-done-keywords))
12745 (member (plist-get change-plist :to)
12746 (cons 'todo org-not-done-keywords))
12747 (not (plist-get change-plist :to)))
12748 (throw 'dont-block t))
12749 ;; If this task has checkboxes that are not checked, it's blocked
12751 (org-back-to-heading t)
12752 (let ((beg (point)) end)
12753 (outline-next-heading)
12756 (if (org-list-search-forward
12757 (concat (org-item-beginning-re)
12758 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12762 (if (boundp 'org-blocked-by-checkboxes)
12763 (setq org-blocked-by-checkboxes t))
12764 (throw 'dont-block nil)))))
12765 t))) ; do not block
12767 (defun org-entry-blocked-p ()
12768 "Is the current entry blocked?"
12769 (org-with-silent-modifications
12770 (if (org-entry-get nil "NOBLOCKING")
12771 nil ;; Never block this entry
12772 (not (run-hook-with-args-until-failure
12774 (list :type 'todo-state-change
12779 (defun org-update-statistics-cookies (all)
12780 "Update the statistics cookie, either from TODO or from checkboxes.
12781 This should be called with the cursor in a line with a statistics cookie."
12785 (org-update-checkbox-count 'all)
12786 (org-map-entries 'org-update-parent-todo-statistics))
12787 (if (not (org-at-heading-p))
12788 (org-update-checkbox-count)
12789 (let ((pos (point-marker))
12791 (ignore-errors (org-back-to-heading t))
12792 (if (not (org-at-heading-p))
12793 (org-update-checkbox-count)
12794 (setq l1 (org-outline-level))
12795 (setq end (save-excursion
12796 (outline-next-heading)
12797 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12799 (if (and (save-excursion
12801 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12802 (not (save-excursion (re-search-forward
12803 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12804 (org-update-checkbox-count)
12805 (if (and l2 (> l2 l1))
12808 (org-update-parent-todo-statistics))
12810 (beginning-of-line 1)
12811 (while (re-search-forward
12812 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12814 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12816 (move-marker pos nil)))))
12818 (defvar org-entry-property-inherited-from) ;; defined below
12819 (defun org-update-parent-todo-statistics ()
12820 "Update any statistics cookie in the parent of the current headline.
12821 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12822 the entire subtree and this will travel up the hierarchy and update
12823 statistics everywhere."
12824 (let* ((prop (save-excursion (org-up-heading-safe)
12825 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12826 (recursive (or (not org-hierarchical-todo-statistics)
12827 (and prop (string-match "\\<recursive\\>" prop))))
12828 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12831 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12832 level ltoggle l1 new ndel
12833 (cnt-all 0) (cnt-done 0) is-percent kwd
12834 checkbox-beg ov ovs ove cookie-present)
12837 (beginning-of-line 1)
12838 (setq ltoggle (funcall outline-level))
12839 ;; Three situations are to consider:
12841 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12842 ;; to the top-level ancestor on the headline;
12844 ;; 2. If parent has "recursive" property, repeat up to the
12845 ;; headline setting that property, taking inheritance into
12848 ;; 3. Else, move up to direct parent and proceed only once.
12849 (while (and (setq level (org-up-heading-safe))
12850 (or recursive first)
12852 (setq first nil cookie-present nil)
12856 (downcase (or (org-entry-get nil "COOKIE_DATA")
12859 (while (re-search-forward box-re (point-at-eol) t)
12860 (setq cnt-all 0 cnt-done 0 cookie-present t)
12861 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12863 (unless (outline-next-heading) (throw 'exit nil))
12864 (while (and (looking-at org-complex-heading-regexp)
12865 (> (setq l1 (length (match-string 1))) level))
12866 (setq kwd (and (or recursive (= l1 ltoggle))
12868 (if (or (eq org-provide-todo-statistics 'all-headlines)
12869 (and (eq org-provide-todo-statistics t)
12870 (or (member kwd org-done-keywords)))
12871 (and (listp org-provide-todo-statistics)
12872 (stringp (car org-provide-todo-statistics))
12873 (or (member kwd org-provide-todo-statistics)
12874 (member kwd org-done-keywords)))
12875 (and (listp org-provide-todo-statistics)
12876 (listp (car org-provide-todo-statistics))
12877 (or (member kwd (car org-provide-todo-statistics))
12878 (and (member kwd org-done-keywords)
12879 (member kwd (cadr org-provide-todo-statistics))))))
12880 (setq cnt-all (1+ cnt-all))
12881 (if (eq org-provide-todo-statistics t)
12882 (and kwd (setq cnt-all (1+ cnt-all)))))
12883 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12884 (member kwd org-done-keywords))
12885 (and (listp org-provide-todo-statistics)
12886 (listp (car org-provide-todo-statistics))
12887 (member kwd org-done-keywords)
12888 (member kwd (cadr org-provide-todo-statistics)))
12889 (and (listp org-provide-todo-statistics)
12890 (stringp (car org-provide-todo-statistics))
12891 (member kwd org-done-keywords)))
12892 (setq cnt-done (1+ cnt-done)))
12893 (outline-next-heading)))
12896 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12897 (format "[%d/%d]" cnt-done cnt-all))
12898 ndel (- (match-end 0) checkbox-beg))
12899 ;; handle overlays when updating cookie from column view
12900 (when (setq ov (car (overlays-at checkbox-beg)))
12901 (setq ovs (overlay-start ov) ove (overlay-end ov))
12902 (delete-overlay ov))
12903 (goto-char checkbox-beg)
12905 (delete-region (point) (+ (point) ndel))
12906 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12907 (when ov (move-overlay ov ovs ove)))
12908 (when cookie-present
12909 (run-hook-with-args 'org-after-todo-statistics-hook
12910 cnt-done (- cnt-all cnt-done))))))
12911 (run-hooks 'org-todo-statistics-hook)))
12913 (defvar org-after-todo-statistics-hook nil
12914 "Hook that is called after a TODO statistics cookie has been updated.
12915 Each function is called with two arguments: the number of not-done entries
12916 and the number of done entries.
12918 For example, the following function, when added to this hook, will switch
12919 an entry to DONE when all children are done, and back to TODO when new
12920 entries are set to a TODO status. Note that this hook is only called
12921 when there is a statistics cookie in the headline!
12923 (defun org-summary-todo (n-done n-not-done)
12924 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12925 (let (org-log-done org-log-states) ; turn off logging
12926 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12929 (defvar org-todo-statistics-hook nil
12930 "Hook that is run whenever Org thinks TODO statistics should be updated.
12931 This hook runs even if there is no statistics cookie present, in which case
12932 `org-after-todo-statistics-hook' would not run.")
12934 (defun org-todo-trigger-tag-changes (state)
12935 "Apply the changes defined in `org-todo-state-tags-triggers'."
12936 (let ((l org-todo-state-tags-triggers)
12938 (when (or (not state) (equal state ""))
12939 (setq changes (append changes (cdr (assoc "" l)))))
12940 (when (and (stringp state) (> (length state) 0))
12941 (setq changes (append changes (cdr (assoc state l)))))
12942 (when (member state org-not-done-keywords)
12943 (setq changes (append changes (cdr (assoc 'todo l)))))
12944 (when (member state org-done-keywords)
12945 (setq changes (append changes (cdr (assoc 'done l)))))
12946 (dolist (c changes)
12947 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12949 (defun org-local-logging (value)
12950 "Get logging settings from a property VALUE."
12952 ;; directly set the variables, they are already local.
12953 (setq org-log-done nil
12955 org-todo-log-states nil)
12956 (setq words (org-split-string value))
12957 (while (setq w (pop words))
12959 ((setq a (assoc w org-startup-options))
12960 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12961 (set (nth 1 a) (nth 2 a))))
12962 ((setq a (org-extract-log-state-settings w))
12963 (and (member (car a) org-todo-keywords-1)
12964 (push a org-todo-log-states)))))))
12966 (defun org-get-todo-sequence-head (kwd)
12967 "Return the head of the TODO sequence to which KWD belongs.
12968 If KWD is not set, check if there is a text property remembering the
12973 (or (get-text-property (point-at-bol) 'org-todo-head)
12975 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12976 nil (point-at-eol)))
12977 (get-text-property p 'org-todo-head))))
12978 ((not (member kwd org-todo-keywords-1))
12979 (car org-todo-keywords-1))
12980 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12982 (defun org-fast-todo-selection ()
12983 "Fast TODO keyword selection with single keys.
12984 Returns the new TODO keyword, or nil if no state change should occur."
12985 (let* ((fulltable org-todo-key-alist)
12986 (done-keywords org-done-keywords) ;; needed for the faces.
12987 (maxlen (apply 'max (mapcar
12989 (if (stringp (car x)) (string-width (car x)) 0))
12992 (fwidth (+ maxlen 3 1 3))
12993 (ncol (/ (- (window-width) 4) fwidth))
12997 (save-window-excursion
12999 (set-buffer (get-buffer-create " *Org todo*"))
13000 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13002 (org-set-local 'org-done-keywords done-keywords)
13003 (setq tbl fulltable cnt 0)
13004 (while (setq e (pop tbl))
13006 ((equal e '(:startgroup))
13007 (push '() groups) (setq ingroup t)
13008 (when (not (= cnt 0))
13012 ((equal e '(:endgroup))
13013 (setq ingroup nil cnt 0)
13015 ((equal e '(:newline))
13016 (when (not (= cnt 0))
13020 (while (equal (car tbl) '(:newline))
13022 (setq tbl (cdr tbl)))))
13024 (setq tg (car e) c (cdr e))
13025 (if ingroup (push tg (car groups)))
13026 (setq tg (org-add-props tg nil 'face
13027 (org-get-todo-face tg)))
13028 (if (and (= cnt 0) (not ingroup)) (insert " "))
13029 (insert "[" c "] " tg (make-string
13030 (- fwidth 4 (length tg)) ?\ ))
13031 (when (= (setq cnt (1+ cnt)) ncol)
13033 (if ingroup (insert " "))
13036 (goto-char (point-min))
13037 (if (not expert) (org-fit-window-to-buffer))
13038 (message "[a-z..]:Set [SPC]:clear")
13039 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13042 (and (= c ?q) (not (rassoc c fulltable))))
13043 (setq quit-flag t))
13045 ((setq e (rassoc c fulltable) tg (car e))
13047 (t (setq quit-flag t)))))))
13049 (defun org-entry-is-todo-p ()
13050 (member (org-get-todo-state) org-not-done-keywords))
13052 (defun org-entry-is-done-p ()
13053 (member (org-get-todo-state) org-done-keywords))
13055 (defun org-get-todo-state ()
13056 "Return the TODO keyword of the current subtree."
13058 (org-back-to-heading t)
13059 (and (looking-at org-todo-line-regexp)
13061 (match-string 2))))
13063 (defun org-at-date-range-p (&optional inactive-ok)
13064 "Is the cursor inside a date range?"
13068 (let ((pos (point)))
13069 (skip-chars-backward "^[<\r\n")
13070 (skip-chars-backward "<[")
13071 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13072 (>= (match-end 0) pos)
13074 (skip-chars-backward "^<[\r\n")
13075 (skip-chars-backward "<[")
13076 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13077 (>= (match-end 0) pos)
13081 (defun org-get-repeat (&optional tagline)
13082 "Check if there is a deadline/schedule with repeater in this entry."
13085 (org-back-to-heading t)
13086 (and (re-search-forward (if tagline
13087 (concat tagline "\\s-*" org-repeat-re)
13089 (org-entry-end-position) t)
13090 (match-string-no-properties 1)))))
13092 (defvar org-last-changed-timestamp)
13093 (defvar org-last-inserted-timestamp)
13094 (defvar org-log-post-message)
13095 (defvar org-log-note-purpose)
13096 (defvar org-log-note-how nil)
13097 (defvar org-log-note-extra)
13098 (defun org-auto-repeat-maybe (done-word)
13099 "Check if the current headline contains a repeated deadline/schedule.
13100 If yes, set TODO state back to what it was and change the base date
13101 of repeating deadline/scheduled time stamps to new date.
13102 This function is run automatically after each state change to a DONE state."
13103 ;; last-state is dynamically scoped into this function
13104 (let* ((repeat (org-get-repeat))
13105 (aa (assoc org-last-state org-todo-kwd-alist))
13106 (interpret (nth 1 aa))
13108 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13109 (msg "Entry repeats: ")
13111 (org-todo-log-states nil)
13112 re type n what ts time to-state)
13113 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13114 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13115 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13116 org-todo-repeat-to-state))
13117 (unless (and to-state (member to-state org-todo-keywords-1))
13118 (setq to-state (if (eq interpret 'type) org-last-state head)))
13119 (org-todo to-state)
13120 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13121 (org-entry-put nil "LAST_REPEAT" (format-time-string
13122 (org-time-stamp-format t t))))
13123 (when org-log-repeat
13124 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13125 (memq 'org-add-log-note post-command-hook))
13126 ;; OK, we are already setup for some record
13127 (if (eq org-log-repeat 'note)
13128 ;; make sure we take a note, not only a time stamp
13129 (setq org-log-note-how 'note))
13130 ;; Set up for taking a record
13131 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13133 'findpos org-log-repeat)))
13134 (org-back-to-heading t)
13135 (org-add-planning-info nil nil 'closed)
13136 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13137 org-deadline-time-regexp "\\)\\|\\("
13138 org-ts-regexp "\\)"))
13139 (while (re-search-forward
13140 re (save-excursion (outline-next-heading) (point)) t)
13141 (setq type (if (match-end 1) org-scheduled-string
13142 (if (match-end 3) org-deadline-string "Plain:"))
13143 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13144 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13145 (setq n (string-to-number (match-string 2 ts))
13146 what (match-string 3 ts))
13147 (if (equal what "w") (setq n (* n 7) what "d"))
13148 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13149 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13150 ;; Preparation, see if we need to modify the start date for the change
13151 (when (match-end 1)
13152 (setq time (save-match-data (org-time-string-to-time ts)))
13154 ((equal (match-string 1 ts) ".")
13155 ;; Shift starting date to today
13156 (org-timestamp-change
13157 (- (org-today) (time-to-days time))
13159 ((equal (match-string 1 ts) "+")
13160 (let ((nshiftmax 10) (nshift 0))
13161 (while (or (= nshift 0)
13162 (<= (time-to-days time)
13163 (time-to-days (current-time))))
13164 (when (= (incf nshift) nshiftmax)
13165 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13166 (user-error "Abort")))
13167 (org-timestamp-change n (cdr (assoc what whata)))
13168 (org-at-timestamp-p t)
13169 (setq ts (match-string 1))
13170 (setq time (save-match-data (org-time-string-to-time ts)))))
13171 (org-timestamp-change (- n) (cdr (assoc what whata)))
13172 ;; rematch, so that we have everything in place for the real shift
13173 (org-at-timestamp-p t)
13174 (setq ts (match-string 1))
13175 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13176 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13177 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13178 (setq org-log-post-message msg)
13179 (message "%s" msg))))
13181 (defun org-show-todo-tree (arg)
13182 "Make a compact tree which shows all headlines marked with TODO.
13183 The tree will show the lines where the regexp matches, and all higher
13184 headlines above the match.
13185 With a \\[universal-argument] prefix, prompt for a regexp to match.
13186 With a numeric prefix N, construct a sparse tree for the Nth element
13187 of `org-todo-keywords-1'."
13189 (let ((case-fold-search nil)
13191 (cond ((null arg) org-not-done-regexp)
13193 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13194 (mapcar 'list org-todo-keywords-1))))
13196 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13198 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13199 (regexp-quote (nth (1- (prefix-numeric-value arg))
13200 org-todo-keywords-1)))
13201 (t (user-error "Invalid prefix argument: %s" arg)))))
13202 (message "%d TODO entries found"
13203 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13205 (defun org-deadline (arg &optional time)
13206 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13207 With one universal prefix argument, remove any deadline from the item.
13208 With two universal prefix arguments, prompt for a warning delay.
13209 With argument TIME, set the deadline at the corresponding date. TIME
13210 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13212 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13213 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13214 'region-start-level 'region))
13215 org-loop-over-headlines-in-active-region)
13217 `(org-deadline ',arg ,time)
13218 org-loop-over-headlines-in-active-region
13219 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13220 (let* ((old-date (org-entry-get nil "DEADLINE"))
13221 (old-date-time (if old-date (org-time-string-to-time old-date)))
13222 (repeater (and old-date
13224 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13226 (match-string 1 old-date))))
13229 (when (and old-date org-log-redeadline)
13230 (org-add-log-setup 'deldeadline nil old-date 'findpos
13231 org-log-redeadline))
13232 (org-remove-timestamp-with-keyword org-deadline-string)
13233 (message "Item no longer has a deadline."))
13236 (org-back-to-heading t)
13237 (if (re-search-forward
13238 org-deadline-time-regexp
13239 (save-excursion (outline-next-heading) (point)) t)
13240 (let* ((rpl0 (match-string 1))
13241 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13243 (concat org-deadline-string
13249 (org-read-date nil t nil "Warn starting from" old-date-time)))
13250 (time-to-days old-date-time))))
13252 (user-error "No deadline information to update"))))
13254 (org-add-planning-info 'deadline time 'closed)
13255 (when (and old-date org-log-redeadline
13256 (not (equal old-date
13257 (substring org-last-inserted-timestamp 1 -1))))
13258 (org-add-log-setup 'redeadline nil old-date 'findpos
13259 org-log-redeadline))
13262 (org-back-to-heading t)
13263 (when (re-search-forward (concat org-deadline-string " "
13264 org-last-inserted-timestamp)
13266 (outline-next-heading) (point)) t)
13267 (goto-char (1- (match-end 0)))
13268 (insert " " repeater)
13269 (setq org-last-inserted-timestamp
13270 (concat (substring org-last-inserted-timestamp 0 -1)
13272 (substring org-last-inserted-timestamp -1))))))
13273 (message "Deadline on %s" org-last-inserted-timestamp))))))
13275 (defun org-schedule (arg &optional time)
13276 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13277 With one universal prefix argument, remove any scheduling date from the item.
13278 With two universal prefix arguments, prompt for a delay cookie.
13279 With argument TIME, scheduled at the corresponding date. TIME can
13280 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13282 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13283 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13284 'region-start-level 'region))
13285 org-loop-over-headlines-in-active-region)
13287 `(org-schedule ',arg ,time)
13288 org-loop-over-headlines-in-active-region
13289 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13290 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13291 (old-date-time (if old-date (org-time-string-to-time old-date)))
13292 (repeater (and old-date
13294 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13296 (match-string 1 old-date))))
13300 (when (and old-date org-log-reschedule)
13301 (org-add-log-setup 'delschedule nil old-date 'findpos
13302 org-log-reschedule))
13303 (org-remove-timestamp-with-keyword org-scheduled-string)
13304 (message "Item is no longer scheduled.")))
13307 (org-back-to-heading t)
13308 (if (re-search-forward
13309 org-scheduled-time-regexp
13310 (save-excursion (outline-next-heading) (point)) t)
13311 (let* ((rpl0 (match-string 1))
13312 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13314 (concat org-scheduled-string
13320 (org-read-date nil t nil "Delay until" old-date-time)))
13321 (time-to-days old-date-time))))
13323 (user-error "No scheduled information to update"))))
13325 (org-add-planning-info 'scheduled time 'closed)
13326 (when (and old-date org-log-reschedule
13327 (not (equal old-date
13328 (substring org-last-inserted-timestamp 1 -1))))
13329 (org-add-log-setup 'reschedule nil old-date 'findpos
13330 org-log-reschedule))
13333 (org-back-to-heading t)
13334 (when (re-search-forward (concat org-scheduled-string " "
13335 org-last-inserted-timestamp)
13337 (outline-next-heading) (point)) t)
13338 (goto-char (1- (match-end 0)))
13339 (insert " " repeater)
13340 (setq org-last-inserted-timestamp
13341 (concat (substring org-last-inserted-timestamp 0 -1)
13343 (substring org-last-inserted-timestamp -1))))))
13344 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13346 (defun org-get-scheduled-time (pom &optional inherit)
13347 "Get the scheduled time as a time tuple, of a format suitable
13348 for calling org-schedule with, or if there is no scheduling,
13350 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13352 (apply 'encode-time (org-parse-time-string time)))))
13354 (defun org-get-deadline-time (pom &optional inherit)
13355 "Get the deadline as a time tuple, of a format suitable for
13356 calling org-deadline with, or if there is no scheduling, returns
13358 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13360 (apply 'encode-time (org-parse-time-string time)))))
13362 (defun org-remove-timestamp-with-keyword (keyword)
13363 "Remove all time stamps with KEYWORD in the current entry."
13364 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13367 (org-back-to-heading t)
13369 (outline-next-heading)
13370 (while (re-search-backward re beg t)
13372 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13373 (equal (char-before) ?\ ))
13374 (backward-delete-char 1)
13375 (if (string-match "^[ \t]*$" (buffer-substring
13376 (point-at-bol) (point-at-eol)))
13377 (delete-region (point-at-bol)
13378 (min (point-max) (1+ (point-at-eol))))))))))
13380 (defvar org-time-was-given) ; dynamically scoped parameter
13381 (defvar org-end-time-was-given) ; dynamically scoped parameter
13383 (defun org-add-planning-info (what &optional time &rest remove)
13384 "Insert new timestamp with keyword in the line directly after the headline.
13385 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13386 If non is given, the user is prompted for a date.
13387 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13390 (let (org-time-was-given org-end-time-was-given default-time default-input)
13392 (when (and (memq what '(scheduled deadline))
13394 (and (stringp time)
13395 (string-match "^[-+]+[0-9]" time))))
13396 ;; Try to get a default date/time from existing timestamp
13398 (org-back-to-heading t)
13399 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13400 (when (re-search-forward (if (eq what 'scheduled)
13401 org-scheduled-time-regexp
13402 org-deadline-time-regexp)
13404 (setq ts (match-string 1)
13405 default-time (apply 'encode-time (org-parse-time-string ts))
13406 default-input (and ts (org-get-compact-tod ts)))))))
13410 ;; This is a string (relative or absolute), set proper date
13411 (apply 'encode-time
13412 (org-read-date-analyze
13413 time default-time (decode-time default-time)))
13414 ;; If necessary, get the time from the user
13415 (or time (org-read-date nil 'to-time nil nil
13416 default-time default-input)))))
13418 (when (and org-insert-labeled-timestamps-at-point
13419 (memq what '(scheduled deadline)))
13421 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13422 (org-insert-time-stamp time org-time-was-given
13423 nil nil nil (list org-end-time-was-given))
13425 (org-with-wide-buffer
13426 (let (col list elt ts buffer-invisibility-spec)
13427 (org-back-to-heading t)
13428 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13429 (goto-char (match-end 1))
13430 (setq col (current-column))
13431 (goto-char (match-end 0))
13432 (if (eobp) (insert "\n") (forward-char 1))
13433 (unless (or what (org-looking-at-p org-planning-line-re))
13434 ;; Nothing to add, nothing to remove...... :-)
13436 (if (and (not (looking-at org-outline-regexp))
13437 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13439 (not (equal (match-string 1) org-clock-string)))
13440 (narrow-to-region (match-beginning 0) (match-end 0))
13441 (insert-before-markers "\n")
13443 (narrow-to-region (point) (point))
13444 (and org-adapt-indentation (org-indent-to-column col)))
13445 ;; Check if we have to remove something.
13446 (setq list (cons what remove))
13448 (setq elt (pop list))
13449 (when (or (and (eq elt 'scheduled)
13450 (re-search-forward org-scheduled-time-regexp nil t))
13451 (and (eq elt 'deadline)
13452 (re-search-forward org-deadline-time-regexp nil t))
13453 (and (eq elt 'closed)
13454 (re-search-forward org-closed-time-regexp nil t)))
13456 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13457 (and (looking-at "[ \t]+") (replace-match ""))
13458 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13461 (if (or (bolp) (eq (char-before) ?\s)) "" " ")
13462 (cond ((eq what 'scheduled) org-scheduled-string)
13463 ((eq what 'deadline) org-deadline-string)
13464 ((eq what 'closed) org-closed-string))
13466 (setq ts (org-insert-time-stamp
13468 (or org-time-was-given
13469 (and (eq what 'closed) org-log-done-with-time))
13471 nil nil (list org-end-time-was-given)))
13473 (eq (char-before) ?\s)
13474 (memq (char-after) '(?\n ?\s))
13478 (goto-char (point-min))
13480 (when (and (looking-at "[ \t]*\n") (eq (char-before) ?\n))
13481 (delete-region (1- (point)) (line-end-position)))
13484 (defvar org-log-note-marker (make-marker))
13485 (defvar org-log-note-purpose nil)
13486 (defvar org-log-note-state nil)
13487 (defvar org-log-note-previous-state nil)
13488 (defvar org-log-note-extra nil)
13489 (defvar org-log-note-window-configuration nil)
13490 (defvar org-log-note-return-to (make-marker))
13491 (defvar org-log-note-effective-time nil
13492 "Remembered current time so that dynamically scoped
13493 `org-extend-today-until' affects tha timestamps in state change
13496 (defvar org-log-post-message nil
13497 "Message to be displayed after a log note has been stored.
13498 The auto-repeater uses this.")
13500 (defun org-add-note ()
13501 "Add a note to the current entry.
13502 This is done in the same way as adding a state change note."
13504 (org-add-log-setup 'note nil nil 'findpos nil))
13506 (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
13507 "Set up the post command hook to take a note.
13508 If this is about to TODO state change, the new state is expected in STATE.
13509 When FINDPOS is non-nil, find the correct position for the note in
13510 the current entry. If not, assume that it can be inserted at point.
13511 HOW is an indicator what kind of note should be created.
13512 EXTRA is additional text that will be inserted into the notes buffer."
13513 (let* ((org-log-into-drawer (org-log-into-drawer))
13514 (drawer (cond ((stringp org-log-into-drawer) org-log-into-drawer)
13515 (org-log-into-drawer "LOGBOOK"))))
13516 (org-with-wide-buffer
13518 (org-back-to-heading t)
13519 ;; Skip planning info and property drawer.
13521 (when (org-looking-at-p org-planning-line-re) (forward-line))
13522 (when (looking-at org-property-drawer-re)
13523 (goto-char (match-end 0))
13525 (let ((end (if (org-at-heading-p) (point)
13526 (save-excursion (outline-next-heading) (point)))))
13529 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13530 (case-fold-search t))
13532 ;; Try to find existing drawer.
13533 (while (re-search-forward regexp end t)
13534 (let ((element (org-element-at-point)))
13535 (when (eq (org-element-type element) 'drawer)
13536 (when (and (not org-log-states-order-reversed)
13537 (org-element-property :contents-end element))
13538 (goto-char (org-element-property :contents-end element)))
13539 (throw 'exit nil))))
13540 ;; No drawer found. Create one.
13541 (unless (bolp) (insert "\n"))
13542 (let ((beg (point)))
13543 (insert ":" drawer ":\n:END:\n")
13544 (org-indent-region beg (point)))
13545 (end-of-line -1))))
13546 (org-log-state-notes-insert-after-drawers
13547 (while (and (looking-at org-drawer-regexp)
13548 (progn (goto-char (match-end 0))
13549 (re-search-forward org-property-end-re end t)))
13551 (unless org-log-states-order-reversed
13552 (and (= (char-after) ?\n) (forward-char 1))
13553 (org-skip-over-state-notes)
13554 (skip-chars-backward " \t\n\r")))
13555 (move-marker org-log-note-marker (point))
13556 (setq org-log-note-purpose purpose
13557 org-log-note-state state
13558 org-log-note-previous-state prev-state
13559 org-log-note-how how
13560 org-log-note-extra extra
13561 org-log-note-effective-time (org-current-effective-time))
13562 (add-hook 'post-command-hook 'org-add-log-note 'append))))
13564 (defun org-skip-over-state-notes ()
13565 "Skip past the list of State notes in an entry."
13566 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13567 (when (ignore-errors (goto-char (org-in-item-p)))
13568 (let* ((struct (org-list-struct))
13569 (prevs (org-list-prevs-alist struct)))
13570 (while (looking-at "[ \t]*- State")
13571 (goto-char (or (org-list-get-next-item (point) struct prevs)
13572 (org-list-get-item-end (point) struct)))))))
13574 (defun org-add-log-note (&optional purpose)
13575 "Pop up a window for taking a note, and add this note later at point."
13576 (remove-hook 'post-command-hook 'org-add-log-note)
13577 (setq org-log-note-window-configuration (current-window-configuration))
13578 (delete-other-windows)
13579 (move-marker org-log-note-return-to (point))
13580 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13581 (goto-char org-log-note-marker)
13582 (org-switch-to-buffer-other-window "*Org Note*")
13584 (if (memq org-log-note-how '(time state))
13585 (let (current-prefix-arg) (org-store-log-note))
13586 (let ((org-inhibit-startup t)) (org-mode))
13587 (insert (format "# Insert note for %s.
13588 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13590 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13591 ((eq org-log-note-purpose 'done) "closed todo item")
13592 ((eq org-log-note-purpose 'state)
13593 (format "state change from \"%s\" to \"%s\""
13594 (or org-log-note-previous-state "")
13595 (or org-log-note-state "")))
13596 ((eq org-log-note-purpose 'reschedule)
13598 ((eq org-log-note-purpose 'delschedule)
13599 "no longer scheduled")
13600 ((eq org-log-note-purpose 'redeadline)
13601 "changing deadline")
13602 ((eq org-log-note-purpose 'deldeadline)
13603 "removing deadline")
13604 ((eq org-log-note-purpose 'refile)
13606 ((eq org-log-note-purpose 'note)
13608 (t (error "This should not happen")))))
13609 (if org-log-note-extra (insert org-log-note-extra))
13610 (org-set-local 'org-finish-function 'org-store-log-note)
13611 (run-hooks 'org-log-buffer-setup-hook)))
13613 (defvar org-note-abort nil) ; dynamically scoped
13614 (defun org-store-log-note ()
13615 "Finish taking a log note, and insert it to where it belongs."
13616 (let ((txt (buffer-string)))
13617 (kill-buffer (current-buffer))
13618 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13620 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13621 (setq txt (replace-match "" t t txt)))
13622 (if (string-match "\\s-+\\'" txt)
13623 (setq txt (replace-match "" t t txt)))
13624 (setq lines (org-split-string txt "\n"))
13625 (when (and note (string-match "\\S-" note))
13627 (org-replace-escapes
13629 (list (cons "%u" (user-login-name))
13630 (cons "%U" user-full-name)
13631 (cons "%t" (format-time-string
13632 (org-time-stamp-format 'long 'inactive)
13633 org-log-note-effective-time))
13634 (cons "%T" (format-time-string
13635 (org-time-stamp-format 'long nil)
13636 org-log-note-effective-time))
13637 (cons "%d" (format-time-string
13638 (org-time-stamp-format nil 'inactive)
13639 org-log-note-effective-time))
13640 (cons "%D" (format-time-string
13641 (org-time-stamp-format nil nil)
13642 org-log-note-effective-time))
13643 (cons "%s" (if org-log-note-state
13644 (concat "\"" org-log-note-state "\"")
13646 (cons "%S" (if org-log-note-previous-state
13647 (concat "\"" org-log-note-previous-state "\"")
13649 (if lines (setq note (concat note " \\\\")))
13651 (when (or current-prefix-arg org-note-abort)
13652 (when org-log-into-drawer
13653 (org-remove-empty-drawer-at org-log-note-marker))
13656 (with-current-buffer (marker-buffer org-log-note-marker)
13658 (goto-char org-log-note-marker)
13659 (move-marker org-log-note-marker nil)
13661 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13662 (setq ind (save-excursion
13663 (if (ignore-errors (goto-char (org-in-item-p)))
13664 (let ((struct (org-list-struct)))
13666 (org-list-get-top-point struct) struct))
13667 (skip-chars-backward " \r\t\n")
13669 ((and (org-at-heading-p)
13670 org-adapt-indentation)
13671 (1+ (org-current-level)))
13672 ((org-at-heading-p) 0)
13673 (t (org-get-indentation))))))
13674 (setq bul (org-list-bullet-string "-"))
13675 (org-indent-line-to ind)
13676 (insert bul (pop lines))
13677 (let ((ind-body (+ (length bul) ind)))
13680 (org-indent-line-to ind-body)
13681 (insert (pop lines))))
13682 (message "Note stored")
13683 (org-back-to-heading t)
13684 (org-cycle-hide-drawers 'children))
13685 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13686 ;; from within `org-add-log-note' because `buffer-undo-list'
13687 ;; is then modified outside of `org-with-remote-undo'.
13688 (when (eq this-command 'org-agenda-todo)
13689 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13690 ;; Don't add undo information when called from `org-agenda-todo'
13691 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13692 (set-window-configuration org-log-note-window-configuration)
13693 (with-current-buffer (marker-buffer org-log-note-return-to)
13694 (goto-char org-log-note-return-to))
13695 (move-marker org-log-note-return-to nil)
13696 (and org-log-post-message (message "%s" org-log-post-message))))
13698 (defun org-remove-empty-drawer-at (pos)
13699 "Remove an empty drawer at position POS.
13700 POS may also be a marker."
13701 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13702 (org-with-wide-buffer
13704 (let ((drawer (org-element-at-point)))
13705 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13706 (not (org-element-property :contents-begin drawer)))
13707 (delete-region (org-element-property :begin drawer)
13708 (progn (goto-char (org-element-property :end drawer))
13709 (skip-chars-backward " \r\t\n")
13713 (defvar org-ts-type nil)
13714 (defun org-sparse-tree (&optional arg type)
13715 "Create a sparse tree, prompt for the details.
13716 This command can create sparse trees. You first need to select the type
13717 of match used to create the tree:
13719 t Show all TODO entries.
13720 T Show entries with a specific TODO keyword.
13721 m Show entries selected by a tags/property match.
13722 p Enter a property name and its value (both with completion on existing
13723 names/values) and show entries with that property.
13724 r Show entries matching a regular expression (`/' can be used as well).
13725 b Show deadlines and scheduled items before a date.
13726 a Show deadlines and scheduled items after a date.
13727 d Show deadlines due within `org-deadline-warning-days'.
13728 D Show deadlines and scheduled items between a date range."
13730 (setq type (or type org-sparse-tree-default-date-type))
13731 (setq org-ts-type type)
13732 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13733 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13734 [c]ycle through date types: %s"
13736 (all "all timestamps")
13737 (scheduled "only scheduled")
13738 (deadline "only deadline")
13739 (active "only active timestamps")
13740 (inactive "only inactive timestamps")
13741 (scheduled-or-deadline "scheduled/deadline")
13742 (closed "with a closed time-stamp")
13743 (otherwise "scheduled/deadline")))
13744 (let ((answer (read-char-exclusive)))
13749 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13750 inactive closed)))))
13751 (?d (call-interactively 'org-check-deadlines))
13752 (?b (call-interactively 'org-check-before-date))
13753 (?a (call-interactively 'org-check-after-date))
13754 (?D (call-interactively 'org-check-dates-range))
13755 (?t (call-interactively 'org-show-todo-tree))
13756 (?T (org-show-todo-tree '(4)))
13757 (?m (call-interactively 'org-match-sparse-tree))
13759 (let* ((kwd (org-icompleting-read
13760 "Property: " (mapcar 'list (org-buffer-property-keys))))
13761 (value (org-icompleting-read
13762 "Value: " (mapcar 'list (org-property-values kwd)))))
13763 (unless (string-match "\\`{.*}\\'" value)
13764 (setq value (concat "\"" value "\"")))
13765 (org-match-sparse-tree arg (concat kwd "=" value))))
13766 ((?r ?R ?/) (call-interactively 'org-occur))
13767 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13769 (defvar org-occur-highlights nil
13770 "List of overlays used for occur matches.")
13771 (make-variable-buffer-local 'org-occur-highlights)
13772 (defvar org-occur-parameters nil
13773 "Parameters of the active org-occur calls.
13774 This is a list, each call to org-occur pushes as cons cell,
13775 containing the regular expression and the callback, onto the list.
13776 The list can contain several entries if `org-occur' has been called
13777 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13778 will only contain one set of parameters. When the highlights are
13779 removed (for example with `C-c C-c', or with the next edit (depending
13780 on `org-remove-highlights-with-change'), this variable is emptied
13782 (make-variable-buffer-local 'org-occur-parameters)
13784 (defun org-occur (regexp &optional keep-previous callback)
13785 "Make a compact tree which shows all matches of REGEXP.
13786 The tree will show the lines where the regexp matches, and all higher
13787 headlines above the match. It will also show the heading after the match,
13788 to make sure editing the matching entry is easy.
13789 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13790 call to `org-occur' will be kept, to allow stacking of calls to this
13792 If CALLBACK is non-nil, it is a function which is called to confirm
13793 that the match should indeed be shown."
13794 (interactive "sRegexp: \nP")
13795 (when (equal regexp "")
13796 (user-error "Regexp cannot be empty"))
13797 (unless keep-previous
13798 (org-remove-occur-highlights nil nil t))
13799 (push (cons regexp callback) org-occur-parameters)
13802 (goto-char (point-min))
13803 (if (or (not keep-previous) ; do not want to keep
13804 (not org-occur-highlights)) ; no previous matches
13807 (while (re-search-forward regexp nil t)
13808 (when (or (not callback)
13809 (save-match-data (funcall callback)))
13810 (setq cnt (1+ cnt))
13811 (when org-highlight-sparse-tree-matches
13812 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13813 (org-show-context 'occur-tree))))
13814 (when org-remove-highlights-with-change
13815 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13817 (unless org-sparse-tree-open-archived-trees
13818 (org-hide-archived-subtrees (point-min) (point-max)))
13819 (run-hooks 'org-occur-hook)
13820 (if (org-called-interactively-p 'interactive)
13821 (message "%d match(es) for regexp %s" cnt regexp))
13824 (defun org-occur-next-match (&optional n reset)
13825 "Function for `next-error-function' to find sparse tree matches.
13826 N is the number of matches to move, when negative move backwards.
13827 RESET is entirely ignored - this function always goes back to the
13828 starting point when no match is found."
13829 (let* ((limit (if (< n 0) (point-min) (point-max)))
13830 (search-func (if (< n 0)
13831 'previous-single-char-property-change
13832 'next-single-char-property-change))
13837 (while (setq p1 (funcall search-func (point) 'org-type))
13838 (when (equal p1 limit)
13840 (user-error "No more matches"))
13841 (when (equal (get-char-property p1 'org-type) 'org-occur)
13845 (throw 'exit (point))))
13848 (user-error "No more matches"))))
13850 (defun org-show-context (&optional key)
13851 "Make sure point and context are visible.
13852 How much context is shown depends upon the variables
13853 `org-show-hierarchy-above', `org-show-following-heading',
13854 `org-show-entry-below' and `org-show-siblings'."
13855 (let ((heading-p (org-at-heading-p t))
13856 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13857 (following-p (org-get-alist-option org-show-following-heading key))
13858 (entry-p (org-get-alist-option org-show-entry-below key))
13859 (siblings-p (org-get-alist-option org-show-siblings key)))
13860 ;; Show heading or entry text
13861 (if (and heading-p (not entry-p))
13862 (org-flag-heading nil) ; only show the heading
13863 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13864 (org-show-hidden-entry))) ; show entire entry
13866 ;; Show next sibling, or heading below text
13868 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13869 (org-flag-heading nil))))
13870 (when siblings-p (org-show-siblings))
13872 ;; show all higher headings, possibly with siblings
13874 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13876 (org-flag-heading nil)
13877 (when siblings-p (org-show-siblings)))))))
13879 (defvar org-reveal-start-hook nil
13880 "Hook run before revealing a location.")
13882 (defun org-reveal (&optional siblings)
13883 "Show current entry, hierarchy above it, and the following headline.
13884 This can be used to show a consistent set of context around locations
13885 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13886 not t for the search context.
13888 With optional argument SIBLINGS, on each level of the hierarchy all
13889 siblings are shown. This repairs the tree structure to what it would
13890 look like when opened with hierarchical calls to `org-cycle'.
13891 With double optional argument \\[universal-argument] \\[universal-argument], \
13892 go to the parent and show the
13895 (run-hooks 'org-reveal-start-hook)
13896 (let ((org-show-hierarchy-above t)
13897 (org-show-following-heading t)
13898 (org-show-siblings (if siblings t org-show-siblings)))
13899 (org-show-context nil))
13900 (when (equal siblings '(16))
13902 (when (org-up-heading-safe)
13904 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13906 (defun org-highlight-new-match (beg end)
13907 "Highlight from BEG to END and mark the highlight is an occur headline."
13908 (let ((ov (make-overlay beg end)))
13909 (overlay-put ov 'face 'secondary-selection)
13910 (overlay-put ov 'org-type 'org-occur)
13911 (push ov org-occur-highlights)))
13913 (defun org-remove-occur-highlights (&optional beg end noremove)
13914 "Remove the occur highlights from the buffer.
13915 BEG and END are ignored. If NOREMOVE is nil, remove this function
13916 from the `before-change-functions' in the current buffer."
13918 (unless org-inhibit-highlight-removal
13919 (mapc 'delete-overlay org-occur-highlights)
13920 (setq org-occur-highlights nil)
13921 (setq org-occur-parameters nil)
13923 (remove-hook 'before-change-functions
13924 'org-remove-occur-highlights 'local))))
13928 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13929 "Regular expression matching the priority indicator.")
13931 (defvar org-remove-priority-next-time nil)
13933 (defun org-priority-up ()
13934 "Increase the priority of the current item."
13936 (org-priority 'up))
13938 (defun org-priority-down ()
13939 "Decrease the priority of the current item."
13941 (org-priority 'down))
13943 (defun org-priority (&optional action show)
13944 "Change the priority of an item.
13945 ACTION can be `set', `up', `down', or a character."
13947 (if (equal action '(4))
13948 (org-show-priority)
13949 (unless org-enable-priority-commands
13950 (user-error "Priority commands are disabled"))
13951 (setq action (or action 'set))
13952 (let (current new news have remove)
13954 (org-back-to-heading t)
13955 (if (looking-at org-priority-regexp)
13956 (setq current (string-to-char (match-string 2))
13959 ((eq action 'remove)
13960 (setq remove t new ?\ ))
13961 ((or (eq action 'set)
13962 (if (featurep 'xemacs) (characterp action) (integerp action)))
13963 (if (not (eq action 'set))
13965 (message "Priority %c-%c, SPC to remove: "
13966 org-highest-priority org-lowest-priority)
13968 (setq new (read-char-exclusive))))
13969 (if (and (= (upcase org-highest-priority) org-highest-priority)
13970 (= (upcase org-lowest-priority) org-lowest-priority))
13971 (setq new (upcase new)))
13972 (cond ((equal new ?\ ) (setq remove t))
13973 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13974 (user-error "Priority must be between `%c' and `%c'"
13975 org-highest-priority org-lowest-priority))))
13978 (1- current) ; normal cycling
13979 ;; last priority was empty
13980 (if (eq last-command this-command)
13981 org-lowest-priority ; wrap around empty to lowest
13983 (if org-priority-start-cycle-with-default
13984 org-default-priority
13985 (1- org-default-priority))))))
13988 (1+ current) ; normal cycling
13989 ;; last priority was empty
13990 (if (eq last-command this-command)
13991 org-highest-priority ; wrap around empty to highest
13993 (if org-priority-start-cycle-with-default
13994 org-default-priority
13995 (1+ org-default-priority))))))
13996 (t (user-error "Invalid action")))
13997 (if (or (< (upcase new) org-highest-priority)
13998 (> (upcase new) org-lowest-priority))
13999 (if (and (memq action '(up down))
14000 (not have) (not (eq last-command this-command)))
14001 ;; `new' is from default priority
14003 "The default can not be set, see `org-default-priority' why")
14004 ;; normal cycling: `new' is beyond highest/lowest priority
14005 ;; and is wrapped around to the empty priority
14007 (setq news (format "%c" new))
14010 (replace-match "" t t nil 1)
14011 (replace-match news t t nil 2))
14013 (user-error "No priority cookie found in line")
14014 (let ((case-fold-search nil))
14015 (looking-at org-todo-line-regexp))
14018 (goto-char (match-end 2))
14019 (insert " [#" news "]"))
14020 (goto-char (match-beginning 3))
14021 (insert "[#" news "] "))))
14022 (org-set-tags nil 'align))
14024 (message "Priority removed")
14025 (message "Priority of current item set to %s" news)))))
14027 (defun org-show-priority ()
14028 "Show the priority of the current item.
14029 This priority is composed of the main priority given with the [#A] cookies,
14030 and by additional input from the age of a schedules or deadline entry."
14032 (let ((pri (if (eq major-mode 'org-agenda-mode)
14033 (org-get-at-bol 'priority)
14036 (beginning-of-line)
14037 (and (looking-at org-heading-regexp)
14038 (org-get-priority (match-string 0))))))))
14039 (message "Priority is %d" (if pri pri -1000))))
14041 (defun org-get-priority (s)
14042 "Find priority cookie and return priority."
14044 (if (functionp org-get-priority-function)
14045 (funcall org-get-priority-function)
14046 (if (not (string-match org-priority-regexp s))
14047 (* 1000 (- org-lowest-priority org-default-priority))
14048 (* 1000 (- org-lowest-priority
14049 (string-to-char (match-string 2 s))))))))
14053 (defvar org-agenda-archives-mode)
14054 (defvar org-map-continue-from nil
14055 "Position from where mapping should continue.
14056 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14058 (defvar org-scanner-tags nil
14059 "The current tag list while the tags scanner is running.")
14060 (defvar org-trust-scanner-tags nil
14061 "Should `org-get-tags-at' use the tags for the scanner.
14062 This is for internal dynamical scoping only.
14063 When this is non-nil, the function `org-get-tags-at' will return the value
14064 of `org-scanner-tags' instead of building the list by itself. This
14065 can lead to large speed-ups when the tags scanner is used in a file with
14066 many entries, and when the list of tags is retrieved, for example to
14067 obtain a list of properties. Building the tags list for each entry in such
14068 a file becomes an N^2 operation - but with this variable set, it scales
14071 (defun org-scan-tags (action matcher todo-only &optional start-level)
14072 "Scan headline tags with inheritance and produce output ACTION.
14074 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14075 or `agenda' to produce an entry list for an agenda view. It can also be
14076 a Lisp form or a function that should be called at each matched headline, in
14077 this case the return value is a list of all return values from these calls.
14079 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14080 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14081 only lines with a not-done TODO keyword are included in the output.
14082 This should be the same variable that was scoped into
14083 and set by `org-make-tags-matcher' when it constructed MATCHER.
14085 START-LEVEL can be a string with asterisks, reducing the scope to
14086 headlines matching this string."
14087 (require 'org-agenda)
14088 (let* ((re (concat "^"
14090 ;; Get the correct level to match
14091 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14092 org-outline-regexp)
14094 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14095 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14096 (props (list 'face 'default
14097 'done-face 'org-agenda-done
14098 'undone-face 'default
14099 'mouse-face 'highlight
14100 'org-not-done-regexp org-not-done-regexp
14101 'org-todo-regexp org-todo-regexp
14102 'org-complex-heading-regexp org-complex-heading-regexp
14104 (format "mouse-2 or RET jump to org file %s"
14105 (abbreviate-file-name
14106 (or (buffer-file-name (buffer-base-buffer))
14107 (buffer-name (buffer-base-buffer)))))))
14108 (org-map-continue-from nil)
14109 lspos tags tags-list
14110 (tags-alist (list (cons 0 org-file-tags)))
14111 (llast 0) rtn rtn1 level category i txt
14112 todo marker entry priority)
14113 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14114 (setq action (list 'lambda nil action)))
14116 (goto-char (point-min))
14117 (when (eq action 'sparse-tree)
14119 (org-remove-occur-highlights))
14120 (while (let (case-fold-search)
14121 (re-search-forward re nil t))
14122 (setq org-map-continue-from nil)
14124 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14125 tags (if (match-end 4) (org-match-string-no-properties 4)))
14126 (goto-char (setq lspos (match-beginning 0)))
14127 (setq level (org-reduced-level (org-outline-level))
14128 category (org-get-category))
14129 (setq i llast llast level)
14130 ;; remove tag lists from same and sublevels
14131 (while (>= i level)
14132 (when (setq entry (assoc i tags-alist))
14133 (setq tags-alist (delete entry tags-alist)))
14135 ;; add the next tags
14137 (setq tags (org-split-string tags ":")
14139 (cons (cons level tags) tags-alist)))
14140 ;; compile tags for current headline
14142 (if org-use-tag-inheritance
14143 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14145 org-scanner-tags tags-list)
14146 (when org-use-tag-inheritance
14147 (setcdr (car tags-alist)
14148 (mapcar (lambda (x)
14149 (setq x (copy-sequence x))
14150 (org-add-prop-inherited x))
14151 (cdar tags-alist))))
14152 (when (and tags org-use-tag-inheritance
14153 (or (not (eq t org-use-tag-inheritance))
14154 org-tags-exclude-from-inheritance))
14155 ;; selective inheritance, remove uninherited ones
14156 (setcdr (car tags-alist)
14157 (org-remove-uninherited-tags (cdar tags-alist))))
14160 ;; eval matcher only when the todo condition is OK
14161 (and (or (not todo-only) (member todo org-not-done-keywords))
14162 (let ((case-fold-search t) (org-trust-scanner-tags t))
14165 ;; Call the skipper, but return t if it does not skip,
14166 ;; so that the `and' form continues evaluating
14168 (unless (eq action 'sparse-tree) (org-agenda-skip))
14171 ;; Check if timestamps are deselecting this entry
14172 (or (not todo-only)
14173 (and (member todo org-not-done-keywords)
14174 (or (not org-agenda-tags-todo-honor-ignore-options)
14175 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14177 ;; select this headline
14179 ((eq action 'sparse-tree)
14180 (and org-highlight-sparse-tree-matches
14181 (org-get-heading) (match-end 0)
14182 (org-highlight-new-match
14183 (match-beginning 1) (match-end 1)))
14184 (org-show-context 'tags-tree))
14185 ((eq action 'agenda)
14186 (setq txt (org-agenda-format-item
14189 (if (eq org-tags-match-list-sublevels 'indented)
14190 (make-string (1- level) ?.) "")
14194 priority (org-get-priority txt))
14196 (setq marker (org-agenda-new-marker))
14197 (org-add-props txt props
14198 'org-marker marker 'org-hd-marker marker 'org-category category
14200 'priority priority 'type "tagsmatch")
14202 ((functionp action)
14203 (setq org-map-continue-from nil)
14205 (setq rtn1 (funcall action))
14207 (t (user-error "Invalid action")))
14209 ;; if we are to skip sublevels, jump to end of subtree
14210 (unless org-tags-match-list-sublevels
14211 (org-end-of-subtree t)
14212 (backward-char 1))))
14213 ;; Get the correct position from where to continue
14214 (if org-map-continue-from
14215 (goto-char org-map-continue-from)
14216 (and (= (point) lspos) (end-of-line 1)))))
14217 (when (and (eq action 'sparse-tree)
14218 (not org-sparse-tree-open-archived-trees))
14219 (org-hide-archived-subtrees (point-min) (point-max)))
14222 (defun org-remove-uninherited-tags (tags)
14223 "Remove all tags that are not inherited from the list TAGS."
14225 ((eq org-use-tag-inheritance t)
14226 (if org-tags-exclude-from-inheritance
14227 (org-delete-all org-tags-exclude-from-inheritance tags)
14229 ((not org-use-tag-inheritance) nil)
14230 ((stringp org-use-tag-inheritance)
14233 (if (and (string-match org-use-tag-inheritance x)
14234 (not (member x org-tags-exclude-from-inheritance)))
14237 ((listp org-use-tag-inheritance)
14240 (if (member x org-use-tag-inheritance) x nil))
14243 (defun org-match-sparse-tree (&optional todo-only match)
14244 "Create a sparse tree according to tags string MATCH.
14245 MATCH can contain positive and negative selection of tags, like
14246 \"+WORK+URGENT-WITHBOSS\".
14247 If optional argument TODO-ONLY is non-nil, only select lines that are
14250 (org-agenda-prepare-buffers (list (current-buffer)))
14251 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14253 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14255 (defvar org-cached-props nil)
14256 (defun org-cached-entry-get (pom property)
14257 (if (or (eq t org-use-property-inheritance)
14258 (and (stringp org-use-property-inheritance)
14259 (string-match org-use-property-inheritance property))
14260 (and (listp org-use-property-inheritance)
14261 (member property org-use-property-inheritance)))
14262 ;; Caching is not possible, check it directly
14263 (org-entry-get pom property 'inherit)
14264 ;; Get all properties, so that we can do complicated checks easily
14265 (cdr (assoc property (or org-cached-props
14266 (setq org-cached-props
14267 (org-entry-properties pom)))))))
14269 (defun org-global-tags-completion-table (&optional files)
14270 "Return the list of all tags in all agenda buffer/files.
14271 Optional FILES argument is a list of files which can be used
14272 instead of the agenda files."
14279 (set-buffer (find-file-noselect file))
14280 (append (org-get-buffer-tags)
14281 (mapcar (lambda (x) (if (stringp (car-safe x))
14282 (list (car-safe x)) nil))
14284 (if (and files (car files))
14286 (org-agenda-files))))))))
14288 (defun org-make-tags-matcher (match)
14289 "Create the TAGS/TODO matcher form for the selection string MATCH.
14291 The variable `todo-only' is scoped dynamically into this function.
14292 It will be set to t if the matcher restricts matching to TODO entries,
14293 otherwise will not be touched.
14295 Returns a cons of the selection string MATCH and the constructed
14296 lisp form implementing the matcher. The matcher is to be evaluated
14297 at an Org entry, with point on the headline, and returns t if the
14298 entry matches the selection string MATCH. The returned lisp form
14299 references two variables with information about the entry, which
14300 must be bound around the form's evaluation: todo, the TODO keyword
14301 at the entry (or nil of none); and tags-list, the list of all tags
14302 at the entry including inherited ones. Additionally, the category
14303 of the entry (if any) must be specified as the text property
14304 'org-category on the headline.
14306 See also `org-scan-tags'.
14308 (declare (special todo-only))
14309 (unless (boundp 'todo-only)
14310 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14312 ;; Get a new match request, with completion against the global
14313 ;; tags table and the local tags in current buffer
14314 (let ((org-last-tags-completion-table
14316 (delq nil (append (org-get-buffer-tags)
14317 (org-global-tags-completion-table))))))
14318 (setq match (org-completing-read-no-i
14319 "Match: " 'org-tags-completion-function nil nil nil
14320 'org-tags-history))))
14322 ;; Parse the string and create a lisp form
14323 (let ((match0 match)
14324 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14326 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14327 orterms term orlist re-p str-p level-p level-op time-p
14328 prop-p pn pv po gv rest (start 0) (ss 0))
14329 ;; Expand group tags
14330 (setq match (org-tags-expand match))
14332 ;; Check if there is a TODO part of this match, which would be the
14333 ;; part after a "/". TO make sure that this slash is not part of
14334 ;; a property value to be matched against, we also check that there
14335 ;; is no " after that slash.
14336 ;; First, find the last slash
14337 (while (string-match "/+" match ss)
14338 (setq start (match-beginning 0) ss (match-end 0)))
14339 (if (and (string-match "/+" match start)
14340 (not (save-match-data (string-match "\"" match start))))
14341 ;; match contains also a todo-matching request
14343 (setq tagsmatch (substring match 0 (match-beginning 0))
14344 todomatch (substring match (match-end 0)))
14345 (if (string-match "^!" todomatch)
14346 (setq todo-only t todomatch (substring todomatch 1)))
14347 (if (string-match "^\\s-*$" todomatch)
14348 (setq todomatch nil)))
14349 ;; only matching tags
14350 (setq tagsmatch match todomatch nil))
14352 ;; Make the tags matcher
14353 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14354 (setq tagsmatcher t)
14355 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14356 (while (setq term (pop orterms))
14357 (while (and (equal (substring term -1) "\\") orterms)
14358 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14359 (while (string-match re term)
14360 (setq rest (substring term (match-end 0))
14361 minus (and (match-end 1)
14362 (equal (match-string 1 term) "-"))
14363 tag (save-match-data (replace-regexp-in-string
14365 (match-string 2 term)))
14366 re-p (equal (string-to-char tag) ?{)
14367 level-p (match-end 4)
14368 prop-p (match-end 5)
14370 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14372 (setq level-op (org-op-to-function (match-string 3 term)))
14373 `(,level-op level ,(string-to-number
14374 (match-string 4 term))))
14376 (setq pn (match-string 5 term)
14377 po (match-string 6 term)
14378 pv (match-string 7 term)
14379 re-p (equal (string-to-char pv) ?{)
14380 str-p (equal (string-to-char pv) ?\")
14381 time-p (save-match-data
14382 (string-match "^\"[[<].*[]>]\"$" pv))
14383 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14384 (if time-p (setq pv (org-matcher-time pv)))
14385 (setq po (org-op-to-function po (if time-p 'time str-p)))
14387 ((equal pn "CATEGORY")
14388 (setq gv '(get-text-property (point) 'org-category)))
14392 (setq gv `(org-cached-entry-get nil ,pn))))
14395 `(not (string-match ,pv (or ,gv "")))
14396 `(string-match ,pv (or ,gv "")))
14398 `(,po (or ,gv "") ,pv)
14399 `(,po (string-to-number (or ,gv ""))
14400 ,(string-to-number pv) ))))
14401 (t `(member ,tag tags-list)))
14402 mm (if minus (list 'not mm) mm)
14404 (push mm tagsmatcher))
14405 (push (if (> (length tagsmatcher) 1)
14406 (cons 'and tagsmatcher)
14409 (setq tagsmatcher nil))
14410 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14412 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14413 ;; Make the todo matcher
14414 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14415 (setq todomatcher t)
14416 (setq orterms (org-split-string todomatch "|") orlist nil)
14417 (while (setq term (pop orterms))
14418 (while (string-match re term)
14419 (setq minus (and (match-end 1)
14420 (equal (match-string 1 term) "-"))
14421 kwd (match-string 2 term)
14422 re-p (equal (string-to-char kwd) ?{)
14423 term (substring term (match-end 0))
14425 `(string-match ,(substring kwd 1 -1) todo)
14426 (list 'equal 'todo kwd))
14427 mm (if minus (list 'not mm) mm))
14428 (push mm todomatcher))
14429 (push (if (> (length todomatcher) 1)
14430 (cons 'and todomatcher)
14433 (setq todomatcher nil))
14434 (setq todomatcher (if (> (length orlist) 1)
14435 (cons 'or orlist) (car orlist))))
14437 ;; Return the string and lisp forms of the matcher
14438 (setq matcher (if todomatcher
14439 (list 'and tagsmatcher todomatcher)
14442 (setq matcher (list 'and '(member todo org-not-done-keywords)
14444 (cons match0 matcher)))
14446 (defun org-tags-expand (match &optional single-as-list downcased)
14447 "Expand group tags in MATCH.
14449 This replaces every group tag in MATCH with a regexp tag search.
14450 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14451 will be replaced like this:
14453 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14454 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14455 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14457 Replacing by a regexp preserves the structure of the match.
14458 E.g., this expansion
14460 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14462 will match anything tagged with \"Lab\" and \"Home\", or tagged
14463 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14465 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14466 assumed to be a single group tag, and the function will return
14467 the list of tags in this group.
14469 When DOWNCASE is non-nil, expand downcased TAGS."
14471 (let* ((case-fold-search t)
14472 (stable org-mode-syntax-table)
14473 (tal (or org-tag-groups-alist-for-agenda
14474 org-tag-groups-alist))
14476 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14477 (tml (mapcar 'car tal))
14478 (rtnmatch match) rpl)
14479 ;; @ and _ are allowed as word-components in tags
14480 (modify-syntax-entry ?@ "w" stable)
14481 (modify-syntax-entry ?_ "w" stable)
14483 (with-syntax-table stable
14485 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14486 (regexp-opt tml) "\\>\\)") rtnmatch)))
14487 (let* ((dir (match-string 1 rtnmatch))
14488 (tag (match-string 2 rtnmatch))
14489 (tag (if downcased (downcase tag) tag)))
14490 (setq tml (delete tag tml))
14491 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14492 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14493 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14494 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14495 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14497 (or (reverse rpl) (list rtnmatch))
14499 (if single-as-list (list (if downcased (downcase match) match))
14502 (defun org-op-to-function (op &optional stringp)
14503 "Turn an operator into the appropriate function."
14506 ((equal op "<" ) '(< string< org-time<))
14507 ((equal op ">" ) '(> org-string> org-time>))
14508 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14509 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14510 ((member op '("=" "==")) '(= string= org-time=))
14511 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14512 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14514 (defun org<> (a b) (not (= a b)))
14515 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14516 (defun org-string>= (a b) (not (string< a b)))
14517 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14518 (defun org-string<> (a b) (not (string= a b)))
14519 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14520 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14521 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14522 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14523 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14524 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14526 "Convert S to a floating point time.
14527 If S is already a number, just return it. If it is a string, parse
14528 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14532 (condition-case nil
14533 (float-time (apply 'encode-time (org-parse-time-string s)))
14537 (defun org-time-today ()
14538 "Time in seconds today at 0:00.
14539 Returns the float number of seconds since the beginning of the
14540 epoch to the beginning of today (00:00)."
14541 (float-time (apply 'encode-time
14542 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14544 (defun org-matcher-time (s)
14545 "Interpret a time comparison value."
14548 ((string= s "<now>") (float-time))
14549 ((string= s "<today>") (org-time-today))
14550 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14551 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14552 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14553 (+ (org-time-today)
14554 (* (string-to-number (match-string 1 s))
14555 (cdr (assoc (match-string 2 s)
14556 '(("d" . 86400.0) ("w" . 604800.0)
14557 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14560 (defun org-match-any-p (re list)
14561 "Does re match any element of list?"
14562 (setq list (mapcar (lambda (x) (string-match re x)) list))
14565 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14566 (defvar org-tags-overlay (make-overlay 1 1))
14567 (org-detach-overlay org-tags-overlay)
14569 (defun org-get-local-tags-at (&optional pos)
14570 "Get a list of tags defined in the current headline."
14571 (org-get-tags-at pos 'local))
14573 (defun org-get-local-tags ()
14574 "Get a list of tags defined in the current headline."
14575 (org-get-tags-at nil 'local))
14577 (defun org-get-tags-at (&optional pos local)
14578 "Get a list of all headline tags applicable at POS.
14579 POS defaults to point. If tags are inherited, the list contains
14580 the targets in the same sequence as the headlines appear, i.e.
14581 the tags of the current headline come last.
14582 When LOCAL is non-nil, only return tags from the current headline,
14583 ignore inherited ones."
14585 (if (and org-trust-scanner-tags
14586 (or (not pos) (equal pos (point)))
14589 (let (tags ltags lastpos parent)
14593 (goto-char (or pos (point)))
14596 (condition-case nil
14598 (org-back-to-heading t)
14599 (while (not (equal lastpos (point)))
14600 (setq lastpos (point))
14602 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14603 (setq ltags (org-split-string
14604 (org-match-string-no-properties 1) ":"))
14606 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14609 (org-remove-uninherited-tags ltags)
14612 (or org-use-tag-inheritance (throw 'done t))
14613 (if local (throw 'done t))
14614 (or (org-up-heading-safe) (error nil))
14619 (reverse (delete-dups
14621 (org-remove-uninherited-tags
14622 org-file-tags) tags)))))))))
14624 (defun org-add-prop-inherited (s)
14625 (add-text-properties 0 (length s) '(inherited t) s)
14628 (defun org-toggle-tag (tag &optional onoff)
14629 "Toggle the tag TAG for the current line.
14630 If ONOFF is `on' or `off', don't toggle but set to this state."
14633 (org-back-to-heading t)
14634 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14637 (setq current (match-string 1))
14638 (replace-match ""))
14640 (setq current (nreverse (org-split-string current ":")))
14644 (or (member tag current) (push tag current)))
14646 (or (not (member tag current)) (setq current (delete tag current))))
14647 (t (if (member tag current)
14648 (setq current (delete tag current))
14650 (push tag current))))
14654 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14655 (org-set-tags nil t))
14656 (delete-horizontal-space))
14657 (run-hooks 'org-after-tags-change-hook))
14660 (defun org-align-tags-here (to-col)
14661 ;; Assumes that this is a headline
14662 "Align tags on the current headline to TO-COL."
14663 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14664 (beginning-of-line 1)
14665 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14666 (< pos (match-beginning 2)))
14668 (setq tags-l (- (match-end 2) (match-beginning 2)))
14669 (goto-char (match-beginning 1))
14671 (delete-region (point) (1+ (match-beginning 2)))
14672 (setq ncol (max (current-column)
14676 (- (abs to-col) tags-l))))
14678 (insert (make-string (- ncol (current-column)) ?\ ))
14679 (setq ncol (current-column))
14680 (when indent-tabs-mode (tabify p (point-at-eol)))
14681 (org-move-to-column (min ncol col)))
14684 (defun org-set-tags-command (&optional arg just-align)
14685 "Call the set-tags command for the current entry."
14687 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14688 (org-set-tags arg just-align)
14690 (unless (and (org-region-active-p)
14691 org-loop-over-headlines-in-active-region)
14692 (org-back-to-heading t))
14693 (org-set-tags arg just-align))))
14695 (defun org-set-tags-to (data)
14696 "Set the tags of the current entry to DATA, replacing the current tags.
14697 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14698 If DATA is nil or the empty string, any tags will be removed."
14699 (interactive "sTags: ")
14703 ((equal data "") "")
14705 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14708 (concat ":" (mapconcat 'identity data ":") ":"))))
14711 (org-back-to-heading t)
14712 (when (looking-at org-complex-heading-regexp)
14715 (goto-char (match-beginning 5))
14717 (delete-region (point) (point-at-eol))
14718 (org-set-tags nil 'align))
14719 (goto-char (point-at-eol))
14721 (org-set-tags nil 'align)))
14722 (beginning-of-line 1)
14723 (if (looking-at ".*?\\([ \t]+\\)$")
14724 (delete-region (match-beginning 1) (match-end 1))))))
14726 (defun org-align-all-tags ()
14727 "Align the tags i all headings."
14730 (or (ignore-errors (org-back-to-heading t))
14731 (outline-next-heading))
14732 (if (org-at-heading-p)
14734 (message "No headings"))))
14736 (defvar org-indent-indentation-per-level)
14737 (defun org-set-tags (&optional arg just-align)
14738 "Set the tags for the current headline.
14739 With prefix ARG, realign all tags in headings in the current buffer.
14740 When JUST-ALIGN is non-nil, only align tags."
14742 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14743 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14744 'region-start-level 'region))
14745 org-loop-over-headlines-in-active-region)
14747 ;; We don't use ARG and JUST-ALIGN here because these args
14748 ;; are not useful when looping over headlines.
14750 org-loop-over-headlines-in-active-region
14751 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14752 (let* ((re org-outline-regexp-bol)
14753 (current (unless arg (org-get-tags-string)))
14754 (col (current-column))
14755 (org-setting-tags t)
14756 table current-tags inherited-tags ; computed below when needed
14757 tags p0 c0 c1 rpl di tc level)
14760 (goto-char (point-min))
14761 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14762 (while (re-search-forward re nil t)
14763 (org-set-tags nil t)
14765 (message "All tags realigned to column %d" org-tags-column))
14767 (setq tags current)
14768 ;; Get a new set of tags from the user
14770 (setq table (append org-tag-persistent-alist
14771 (or org-tag-alist (org-get-buffer-tags))
14773 org-complete-tags-always-offer-all-agenda-tags
14774 (org-global-tags-completion-table
14775 (org-agenda-files))))
14776 org-last-tags-completion-table table
14777 current-tags (org-split-string current ":")
14778 inherited-tags (nreverse
14779 (nthcdr (length current-tags)
14780 (nreverse (org-get-tags-at))))
14782 (if (or (eq t org-use-fast-tag-selection)
14783 (and org-use-fast-tag-selection
14784 (delq nil (mapcar 'cdr table))))
14785 (org-fast-tag-selection
14786 current-tags inherited-tags table
14787 (if org-fast-tag-selection-include-todo
14788 org-todo-key-alist))
14789 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14791 (org-icompleting-read "Tags: "
14792 'org-tags-completion-function
14793 nil nil current 'org-tags-history))))))
14794 (while (string-match "[-+&]+" tags)
14795 ;; No boolean logic, just a list
14796 (setq tags (replace-match ":" t t tags))))
14798 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14800 (if org-tags-sort-function
14801 (setq tags (mapconcat 'identity
14802 (sort (org-split-string
14803 tags (org-re "[^[:alnum:]_@#%]+"))
14804 org-tags-sort-function) ":")))
14806 (if (string-match "\\`[\t ]*\\'" tags)
14808 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14809 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14811 ;; Insert new tags at the correct column
14812 (beginning-of-line 1)
14813 (setq level (or (and (looking-at org-outline-regexp)
14814 (- (match-end 0) (point) 1))
14817 ((and (equal current "") (equal tags "")))
14818 ((re-search-forward
14819 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14821 (if (equal tags "")
14823 (goto-char (match-beginning 0))
14824 (setq c0 (current-column)
14825 ;; compute offset for the case of org-indent-mode active
14826 di (if (org-bound-and-true-p org-indent-mode)
14827 (* (1- org-indent-indentation-per-level) (1- level))
14829 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14830 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14831 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14832 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14833 (replace-match rpl t t)
14834 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14836 (t (error "Tags alignment failed")))
14837 (org-move-to-column col)
14839 (run-hooks 'org-after-tags-change-hook))))))
14841 (defun org-change-tag-in-region (beg end tag off)
14842 "Add or remove TAG for each entry in the region.
14843 This works in the agenda, and also in an org-mode buffer."
14845 (list (region-beginning) (region-end)
14846 (let ((org-last-tags-completion-table
14847 (if (derived-mode-p 'org-mode)
14849 (delq nil (append (org-get-buffer-tags)
14850 (org-global-tags-completion-table))))
14851 (org-global-tags-completion-table))))
14852 (org-icompleting-read
14853 "Tag: " 'org-tags-completion-function nil nil nil
14854 'org-tags-history))
14856 (message "[s]et or
[r]emove? ")
14857 (equal (read-char-exclusive) ?r))))
14858 (if (fboundp 'deactivate-mark) (deactivate-mark))
14859 (let ((agendap (equal major-mode 'org-agenda-mode))
14860 l1 l2 m buf pos newhead (cnt 0))
14862 (setq l2 (1- (org-current-line)))
14864 (setq l1 (org-current-line))
14865 (loop for l from l1 to l2 do
14867 (setq m (get-text-property (point) 'org-hd-marker))
14868 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14870 (setq buf (if agendap (marker-buffer m) (current-buffer))
14871 pos (if agendap m (point)))
14872 (with-current-buffer buf
14876 (setq cnt (1+ cnt))
14877 (org-toggle-tag tag (if off 'off 'on))
14878 (setq newhead (org-get-heading)))))
14879 (and agendap (org-agenda-change-all-lines newhead m))))
14880 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14882 (defun org-tags-completion-function (string predicate &optional flag)
14883 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14884 (confirm (lambda (x) (stringp (car x)))))
14885 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14886 (setq s1 (match-string 1 string)
14887 s2 (match-string 2 string))
14888 (setq s1 "" s2 string))
14892 (setq rtn (try-completion s2 ctable confirm))
14895 (concat s1 s2 (substring rtn (length s2))
14896 (if (and org-add-colon-after-tag-completion
14897 (assoc rtn ctable))
14902 (all-completions s2 ctable confirm))
14905 (assoc s2 ctable)))))
14907 (defun org-fast-tag-insert (kwd tags face &optional end)
14908 "Insert KDW, and the TAGS, the latter with face FACE.
14910 (insert (format "%-12s" (concat kwd ":"))
14911 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14914 (defun org-fast-tag-show-exit (flag)
14917 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14918 (replace-match ""))
14921 (org-move-to-column (- (window-width) 19) t)
14922 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14924 (defun org-set-current-tags-overlay (current prefix)
14925 "Add an overlay to CURRENT tag with PREFIX."
14926 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14927 (if (featurep 'xemacs)
14928 (org-overlay-display org-tags-overlay (concat prefix s)
14929 'secondary-selection)
14930 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14931 (org-overlay-display org-tags-overlay (concat prefix s)))))
14933 (defvar org-last-tag-selection-key nil)
14934 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14935 "Fast tag selection with single keys.
14936 CURRENT is the current list of tags in the headline, INHERITED is the
14937 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14938 possibly with grouping information. TODO-TABLE is a similar table with
14939 TODO keywords, should these have keys assigned to them.
14940 If the keys are nil, a-z are automatically assigned.
14941 Returns the new tags string, or nil to not change the current settings."
14942 (let* ((fulltable (append table todo-table))
14943 (maxlen (apply 'max (mapcar
14945 (if (stringp (car x)) (string-width (car x)) 0))
14947 (buf (current-buffer))
14948 (expert (eq org-fast-tag-selection-single-key 'expert))
14950 (fwidth (+ maxlen 3 1 3))
14951 (ncol (/ (- (window-width) 4) fwidth))
14954 tg cnt e c char c1 c2 ntable tbl rtn
14955 ov-start ov-end ov-prefix
14956 (exit-after-next org-fast-tag-selection-single-key)
14957 (done-keywords org-done-keywords)
14960 (beginning-of-line 1)
14962 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14963 (setq ov-start (match-beginning 1)
14964 ov-end (match-end 1)
14966 (setq ov-start (1- (point-at-eol))
14967 ov-end (1+ ov-start))
14968 (skip-chars-forward "^\n\r")
14971 (buffer-substring (1- (point)) (point))
14972 (if (> (current-column) org-tags-column)
14974 (make-string (- org-tags-column (current-column)) ?\ ))))))
14975 (move-overlay org-tags-overlay ov-start ov-end)
14976 (save-window-excursion
14978 (set-buffer (get-buffer-create " *Org tags*"))
14979 (delete-other-windows)
14980 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14981 (org-switch-to-buffer-other-window " *Org tags*"))
14983 (org-set-local 'org-done-keywords done-keywords)
14984 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14985 (org-fast-tag-insert "Current" current c-face "\n\n")
14986 (org-fast-tag-show-exit exit-after-next)
14987 (org-set-current-tags-overlay current ov-prefix)
14988 (setq tbl fulltable char ?a cnt 0)
14989 (while (setq e (pop tbl))
14991 ((equal (car e) :startgroup)
14992 (push '() groups) (setq ingroup t)
14993 (when (not (= cnt 0))
14996 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14997 ((equal (car e) :endgroup)
14998 (setq ingroup nil cnt 0)
14999 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15000 ((equal e '(:newline))
15001 (when (not (= cnt 0))
15005 (while (equal (car tbl) '(:newline))
15007 (setq tbl (cdr tbl)))))
15008 ((equal e '(:grouptags)) nil)
15010 (setq tg (copy-sequence (car e)) c2 nil)
15013 ;; automatically assign a character.
15014 (setq c1 (string-to-char
15015 (downcase (substring
15016 tg (if (= (string-to-char tg) ?@) 1 0)))))
15017 (if (or (rassoc c1 ntable) (rassoc c1 table))
15018 (while (or (rassoc char ntable) (rassoc char table))
15019 (setq char (1+ char)))
15021 (setq c (or c2 char)))
15022 (if ingroup (push tg (car groups)))
15023 (setq tg (org-add-props tg nil 'face
15025 ((not (assoc tg table))
15026 (org-get-todo-face tg))
15027 ((member tg current) c-face)
15028 ((member tg inherited) i-face))))
15029 (if (equal (caar tbl) :grouptags)
15030 (org-add-props tg nil 'face 'org-tag-group))
15031 (if (and (= cnt 0) (not ingroup)) (insert " "))
15032 (insert "[" c "] " tg (make-string
15033 (- fwidth 4 (length tg)) ?\ ))
15034 (push (cons tg c) ntable)
15035 (when (= (setq cnt (1+ cnt)) ncol)
15037 (if ingroup (insert " "))
15039 (setq ntable (nreverse ntable))
15041 (goto-char (point-min))
15042 (if (not expert) (org-fit-window-to-buffer))
15046 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15047 (if (not groups) "no " "")
15048 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15049 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15050 (setq org-last-tag-selection-key c)
15052 ((= c ?\r) (throw 'exit t))
15054 (setq groups (not groups))
15055 (goto-char (point-min))
15056 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15059 (org-fast-tag-show-exit
15060 (setq exit-after-next (not exit-after-next)))
15062 (delete-other-windows)
15063 (set-window-buffer (split-window-vertically) " *Org tags*")
15064 (org-switch-to-buffer-other-window " *Org tags*")
15065 (org-fit-window-to-buffer)))
15067 (and (= c ?q) (not (rassoc c ntable))))
15068 (org-detach-overlay org-tags-overlay)
15069 (setq quit-flag t))
15072 (if exit-after-next (setq exit-after-next 'now)))
15074 (condition-case nil
15075 (setq tg (org-icompleting-read
15078 (with-current-buffer buf
15079 (org-get-buffer-tags)))))
15080 (quit (setq tg "")))
15081 (when (string-match "\\S-" tg)
15082 (add-to-list 'buffer-tags (list tg))
15083 (if (member tg current)
15084 (setq current (delete tg current))
15085 (push tg current)))
15086 (if exit-after-next (setq exit-after-next 'now)))
15087 ((setq e (rassoc c todo-table) tg (car e))
15088 (with-current-buffer buf
15089 (save-excursion (org-todo tg)))
15090 (if exit-after-next (setq exit-after-next 'now)))
15091 ((setq e (rassoc c ntable) tg (car e))
15092 (if (member tg current)
15093 (setq current (delete tg current))
15094 (loop for g in groups do
15097 (setq current (delete x current)))
15100 (if exit-after-next (setq exit-after-next 'now))))
15102 ;; Create a sorted list
15106 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15107 (if (eq exit-after-next 'now) (throw 'exit t))
15108 (goto-char (point-min))
15109 (beginning-of-line 2)
15110 (delete-region (point) (point-at-eol))
15111 (org-fast-tag-insert "Current" current c-face)
15112 (org-set-current-tags-overlay current ov-prefix)
15113 (while (re-search-forward
15114 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15115 (setq tg (match-string 1))
15116 (add-text-properties
15117 (match-beginning 1) (match-end 1)
15120 ((member tg current) c-face)
15121 ((member tg inherited) i-face)
15122 (t (get-text-property (match-beginning 1) 'face))))))
15123 (goto-char (point-min)))))
15124 (org-detach-overlay org-tags-overlay)
15126 (mapconcat 'identity current ":")
15129 (defun org-get-tags-string ()
15130 "Get the TAGS string in the current headline."
15131 (unless (org-at-heading-p t)
15132 (user-error "Not on a heading"))
15134 (beginning-of-line 1)
15135 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15136 (org-match-string-no-properties 1)
15139 (defun org-get-tags ()
15140 "Get the list of tags specified in the current headline."
15141 (org-split-string (org-get-tags-string) ":"))
15143 (defun org-get-buffer-tags ()
15144 "Get a table of all tags used in the buffer, for completion."
15147 (goto-char (point-min))
15148 (while (re-search-forward
15149 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15150 (when (equal (char-after (point-at-bol 0)) ?*)
15151 (mapc (lambda (x) (add-to-list 'tags x))
15152 (org-split-string (org-match-string-no-properties 1) ":")))))
15153 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15154 (mapcar 'list tags)))
15156 ;;;; The mapping API
15158 (defun org-map-entries (func &optional match scope &rest skip)
15159 "Call FUNC at each headline selected by MATCH in SCOPE.
15161 FUNC is a function or a lisp form. The function will be called without
15162 arguments, with the cursor positioned at the beginning of the headline.
15163 The return values of all calls to the function will be collected and
15164 returned as a list.
15166 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15167 does not need to preserve point. After evaluation, the cursor will be
15168 moved to the end of the line (presumably of the headline of the
15169 processed entry) and search continues from there. Under some
15170 circumstances, this may not produce the wanted results. For example,
15171 if you have removed (e.g. archived) the current (sub)tree it could
15172 mean that the next entry will be skipped entirely. In such cases, you
15173 can specify the position from where search should continue by making
15174 FUNC set the variable `org-map-continue-from' to the desired buffer
15177 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15178 Only headlines that are matched by this query will be considered during
15179 the iteration. When MATCH is nil or t, all headlines will be
15180 visited by the iteration.
15182 SCOPE determines the scope of this command. It can be any of:
15184 nil The current buffer, respecting the restriction if any
15185 tree The subtree started with the entry at point
15186 region The entries within the active region, if any
15188 The entries within the active region, but only those at
15189 the same level than the first one.
15190 file The current buffer, without restriction
15192 The current buffer, and any archives associated with it
15193 agenda All agenda files
15194 agenda-with-archives
15195 All agenda files with any archive files associated with them
15197 If this is a list, all files in the list will be scanned
15199 The remaining args are treated as settings for the skipping facilities of
15200 the scanner. The following items can be given here:
15202 archive skip trees with the archive tag
15203 comment skip trees with the COMMENT keyword
15204 function or Emacs Lisp form:
15205 will be used as value for `org-agenda-skip-function', so
15206 whenever the function returns a position, FUNC will not be
15207 called for that entry and search will continue from the
15210 If your function needs to retrieve the tags including inherited tags
15211 at the *current* entry, you can use the value of the variable
15212 `org-scanner-tags' which will be much faster than getting the value
15213 with `org-get-tags-at'. If your function gets properties with
15214 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15215 to t around the call to `org-entry-properties' to get the same speedup.
15216 Note that if your function moves around to retrieve tags and properties at
15217 a *different* entry, you cannot use these techniques."
15218 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15219 (not (org-region-active-p)))
15220 (let* ((org-agenda-archives-mode nil) ; just to make sure
15221 (org-agenda-skip-archived-trees (memq 'archive skip))
15222 (org-agenda-skip-comment-trees (memq 'comment skip))
15223 (org-agenda-skip-function
15224 (car (org-delete-all '(comment archive) skip)))
15225 (org-tags-match-list-sublevels t)
15226 (start-level (eq scope 'region-start-level))
15228 org-todo-keywords-for-agenda
15229 org-done-keywords-for-agenda
15230 org-todo-keyword-alist-for-agenda
15231 org-tag-alist-for-agenda
15235 ((eq match t) (setq matcher t))
15236 ((eq match nil) (setq matcher t))
15237 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15241 (cond ((eq scope 'tree)
15242 (org-back-to-heading t)
15243 (org-narrow-to-subtree)
15245 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15246 (org-region-active-p))
15247 ;; If needed, set start-level to a string like "2"
15250 (goto-char (region-beginning))
15251 (unless (org-at-heading-p) (outline-next-heading))
15252 (setq start-level (org-current-level))))
15253 (narrow-to-region (region-beginning)
15255 (goto-char (region-end))
15256 (unless (and (bolp) (org-at-heading-p))
15257 (outline-next-heading))
15263 (org-agenda-prepare-buffers
15264 (list (buffer-file-name (current-buffer))))
15265 (setq res (org-scan-tags func matcher todo-only start-level)))
15266 ;; Get the right scope
15268 ((and scope (listp scope) (symbolp (car scope)))
15269 (setq scope (eval scope)))
15270 ((eq scope 'agenda)
15271 (setq scope (org-agenda-files t)))
15272 ((eq scope 'agenda-with-archives)
15273 (setq scope (org-agenda-files t))
15274 (setq scope (org-add-archive-files scope)))
15276 (setq scope (list (buffer-file-name))))
15277 ((eq scope 'file-with-archives)
15278 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15279 (org-agenda-prepare-buffers scope)
15280 (while (setq file (pop scope))
15281 (with-current-buffer (org-find-base-buffer-visiting file)
15285 (goto-char (point-min))
15286 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15291 (defconst org-special-properties
15292 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOSED" "PRIORITY"
15293 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15294 "The special properties valid in Org-mode.
15295 These are properties that are not defined in the property drawer,
15296 but in some other way.")
15298 (defconst org-default-properties
15299 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15300 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15301 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15302 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15303 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15304 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15305 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15306 "Some properties that are used by Org mode for various purposes.
15307 Being in this list makes sure that they are offered for completion.")
15309 (defun org--update-property-plist (key val props)
15310 "Associate KEY to VAL in alist PROPS.
15311 Modifications are made by side-effect. Return new alist."
15312 (let* ((appending (string= (substring key -1) "+"))
15313 (key (if appending (substring key 0 -1) key))
15314 (old (assoc-string key props t)))
15315 (if (not old) (cons (cons key val) props)
15316 (setcdr old (if appending (concat (cdr old) " " val) val))
15319 (defun org-get-property-block (&optional beg force)
15320 "Return the (beg . end) range of the body of the property drawer.
15321 BEG is the beginning of the current subtree, or of the part
15322 before the first headline. If it is not given, it will be found.
15323 If the drawer does not exist, create it if FORCE is non-nil, or
15325 (org-with-wide-buffer
15326 (when beg (goto-char beg))
15327 (unless (org-before-first-heading-p)
15328 (let ((beg (cond (beg)
15329 ((or (not (featurep 'org-inlinetask))
15330 (org-inlinetask-in-task-p))
15331 (org-back-to-heading t))
15332 (t (org-with-limited-levels (org-back-to-heading t))))))
15334 (when (org-looking-at-p org-planning-line-re) (forward-line))
15335 (cond ((looking-at org-property-drawer-re)
15337 (cons (point) (progn (goto-char (match-end 0))
15338 (line-beginning-position))))
15341 (org-insert-property-drawer)
15342 (let ((pos (save-excursion (search-forward ":END:")
15343 (line-beginning-position))))
15344 (cons pos pos))))))))
15346 (defun org-at-property-p ()
15347 "Non-nil when point is inside a property drawer.
15348 See `org-property-re' for match data, if applicable."
15350 (beginning-of-line)
15351 (and (looking-at org-property-re)
15352 (let ((property-drawer (save-match-data (org-get-property-block))))
15353 (and property-drawer (< (point) (cdr property-drawer)))))))
15355 (defun org-property-action ()
15356 "Do an action on properties."
15358 (unless (org-at-property-p) (user-error "Not at a property"))
15359 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15360 (let ((c (read-char-exclusive)))
15362 (?s (call-interactively #'org-set-property))
15363 (?d (call-interactively #'org-delete-property))
15364 (?D (call-interactively #'org-delete-property-globally))
15365 (?c (call-interactively #'org-compute-property-at-point))
15366 (otherwise (user-error "No such property action %c" c)))))
15368 (defun org-inc-effort ()
15369 "Increment the value of the effort property in the current entry."
15371 (org-set-effort nil t))
15373 (defvar org-clock-effort) ; Defined in org-clock.el.
15374 (defvar org-clock-current-task) ; Defined in org-clock.el.
15375 (defun org-set-effort (&optional value increment)
15376 "Set the effort property of the current entry.
15377 With numerical prefix arg, use the nth allowed value, 0 stands for the
15378 10th allowed value.
15380 When INCREMENT is non-nil, set the property to the next allowed value."
15382 (if (equal value 0) (setq value 10))
15383 (let* ((completion-ignore-case t)
15384 (prop org-effort-property)
15385 (cur (org-entry-get nil prop))
15386 (allowed (org-property-get-allowed-values nil prop 'table))
15387 (existing (mapcar 'list (org-property-values prop)))
15388 (heading (nth 4 (org-heading-components)))
15391 ((stringp value) value)
15392 ((and allowed (integerp value))
15393 (or (car (nth (1- value) allowed))
15394 (car (org-last allowed))))
15395 ((and allowed increment)
15396 (or (caadr (member (list cur) allowed))
15397 (user-error "Allowed effort values are not set")))
15399 (message "Select 1-9,0, [RET%s]: %s"
15400 (if cur (concat "=" cur) "")
15401 (mapconcat 'car allowed " "))
15402 (setq rpl (read-char-exclusive))
15403 (if (equal rpl ?\r)
15405 (setq rpl (- rpl ?0))
15406 (if (equal rpl 0) (setq rpl 10))
15407 (if (and (> rpl 0) (<= rpl (length allowed)))
15408 (car (nth (1- rpl) allowed))
15409 (org-completing-read "Effort: " allowed nil))))
15411 (let (org-completion-use-ido org-completion-use-iswitchb)
15412 (org-completing-read
15413 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15414 (concat "[" cur "]") "")
15416 existing nil nil "" nil cur))))))
15417 (unless (equal (org-entry-get nil prop) val)
15418 (org-entry-put nil prop val))
15419 (org-refresh-property
15420 '((effort . identity)
15421 (effort-minutes . org-duration-string-to-minutes))
15423 (when (string= heading org-clock-current-task)
15424 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15425 (org-clock-update-mode-line))
15426 (message "%s is now %s" prop val)))
15428 (defun org-entry-properties (&optional pom which)
15429 "Get all properties of the current entry.
15431 When POM is a buffer position, get all properties from the entry
15434 This includes the TODO keyword, the tags, time strings for
15435 deadline, scheduled, and clocking, and any additional properties
15436 defined in the entry.
15438 If WHICH is nil or `all', get all properties. If WHICH is
15439 `special' or `standard', only get that subclass. If WHICH is
15440 a string, only get that property.
15442 Return value is an alist. Keys are properties, as upcased
15444 (org-with-point-at pom
15445 (when (and (derived-mode-p 'org-mode)
15446 (ignore-errors (org-back-to-heading t)))
15448 (let* ((beg (point))
15449 (specific (and (stringp which) (upcase which)))
15450 (which (cond ((not specific) which)
15451 ((member specific org-special-properties) 'special)
15454 ;; Get the special properties, like TODO and TAGS.
15455 (when (memq which '(nil all special))
15456 (when (or (not specific) (string= specific "CLOCKSUM"))
15457 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15459 (push (cons "CLOCKSUM"
15460 (org-columns-number-to-string
15461 (/ (float clocksum) 60.) 'add_times))
15463 (when specific (throw 'exit props)))
15464 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15465 (let ((clocksumt (get-text-property (point)
15466 :org-clock-minutes-today)))
15468 (push (cons "CLOCKSUM_T"
15469 (org-columns-number-to-string
15470 (/ (float clocksumt) 60.) 'add_times))
15472 (when specific (throw 'exit props)))
15473 (when (or (not specific) (string= specific "TODO"))
15474 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15475 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15476 (when specific (throw 'exit props)))
15477 (when (or (not specific) (string= specific "PRIORITY"))
15478 (when (looking-at org-priority-regexp)
15479 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15480 (when specific (throw 'exit props)))
15481 (when (or (not specific) (string= specific "FILE"))
15482 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15484 (when specific (throw 'exit props)))
15485 (when (or (not specific) (string= specific "TAGS"))
15486 (let ((value (org-string-nw-p (org-get-tags-string))))
15487 (when value (push (cons "TAGS" value) props)))
15488 (when specific (throw 'exit props)))
15489 (when (or (not specific) (string= specific "ALLTAGS"))
15490 (let ((value (org-get-tags-at)))
15492 (push (cons "ALLTAGS"
15493 (format ":%s:" (mapconcat #'identity value ":")))
15495 (when specific (throw 'exit props)))
15496 (when (or (not specific) (string= specific "BLOCKED"))
15497 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15498 (when specific (throw 'exit props)))
15499 (when (or (not specific)
15500 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15502 (when (org-looking-at-p org-planning-line-re)
15504 (let ((bol (line-beginning-position)))
15505 ;; Backward compatibility: time keywords used to be
15506 ;; configurable (before 8.3). Make sure we get the
15507 ;; correct keyword.
15508 (dolist (k (if (not specific)
15509 (list org-closed-string
15510 org-deadline-string
15511 org-scheduled-string)
15512 (list (cond ((string= specific "CLOSED")
15514 ((string= specific "DEADLINE")
15515 org-deadline-string)
15516 (t org-scheduled-string)))))
15518 (when (search-backward k bol t)
15519 (goto-char (match-end 0))
15520 (skip-chars-forward " \t")
15521 (and (looking-at org-ts-regexp-both)
15522 (push (cons specific (match-string 0)) props)))))))
15523 (when specific (throw 'exit props)))
15524 (when (or (not specific)
15525 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15528 (let ((regexp (if (or (string= specific "TIMESTAMP")
15529 (assoc "TIMESTAMP_IA" ts))
15531 org-ts-regexp-both)))
15533 (while (re-search-forward regexp end t)
15535 (let ((object (org-element-context)))
15536 ;; Accept to match timestamps in node
15537 ;; properties, too.
15538 (when (memq (org-element-type object)
15539 '(node-property timestamp))
15541 (org-element-property :type object)))
15543 ((and (memq type '(active active-range))
15544 (not (equal specific "TIMESTAMP_IA")))
15545 (unless (assoc "TIMESTAMP" ts)
15546 (push (cons "TIMESTAMP"
15547 (org-element-property
15548 :raw-value object))
15550 (when specific (throw 'exit ts))))
15551 ((and (memq type '(inactive inactive-range))
15552 (not (string= specific "TIMESTAMP")))
15553 (unless (assoc "TIMESTAMP_IA" ts)
15554 (push (cons "TIMESTAMP_IA"
15555 (org-element-property
15556 :raw-value object))
15558 (when specific (throw 'exit ts))))))
15559 ;; Both timestamp types are found,
15560 ;; move to next part.
15561 (when (= (length ts) 2) (throw 'next ts)))))
15564 ;; First look for timestamps within headline.
15565 (let ((ts (funcall find-ts (line-end-position) nil)))
15566 (if (= (length ts) 2) (setq props (nconc ts props))
15568 ;; Then find timestamps in the section, skipping
15570 (when (org-looking-at-p org-planning-line-re)
15572 (let ((end (save-excursion (outline-next-heading))))
15573 (setq props (nconc (funcall find-ts end ts) props))))))))
15574 ;; Get the standard properties, like :PROP:.
15575 (when (memq which '(nil all standard))
15576 ;; If we are looking after a specific property, delegate
15577 ;; to `org-entry-get', which is faster. However, make an
15578 ;; exception for "CATEGORY", since it can be also set
15579 ;; through keywords (i.e. #+CATEGORY).
15580 (if (and specific (not (equal specific "CATEGORY")))
15581 (let ((value (org-entry-get beg specific nil t)))
15582 (throw 'exit (and value (list (cons specific value)))))
15583 (let ((range (org-get-property-block beg)))
15585 (let ((end (cdr range)) seen-base)
15586 (goto-char (car range))
15587 ;; Unlike to `org--update-property-plist', we
15588 ;; handle the case where base values is found
15589 ;; after its extension. We also forbid standard
15590 ;; properties to be named as special properties.
15591 (while (re-search-forward org-property-re end t)
15592 (let* ((key (upcase (org-match-string-no-properties 2)))
15593 (extendp (org-string-match-p "\\+\\'" key))
15594 (key-base (if extendp (substring key 0 -1) key))
15595 (value (org-match-string-no-properties 3)))
15597 ((member-ignore-case key-base org-special-properties))
15600 (org--update-property-plist key value props)))
15601 ((member key seen-base))
15602 (t (push key seen-base)
15603 (let ((p (assoc-string key props t)))
15604 (if p (setcdr p (concat value " " (cdr p)))
15605 (push (cons key value) props))))))))))))
15606 (unless (assoc "CATEGORY" props)
15607 (push (cons "CATEGORY" (org-get-category)) props)
15608 (when (string= specific "CATEGORY") (throw 'exit props)))
15610 (append (get-text-property beg 'org-summaries) props))))))
15612 (defun org-entry-get (pom property &optional inherit literal-nil)
15613 "Get value of PROPERTY for entry or content at point-or-marker POM.
15615 If INHERIT is non-nil and the entry does not have the property,
15616 then also check higher levels of the hierarchy. If INHERIT is
15617 the symbol `selective', use inheritance only if the setting in
15618 `org-use-property-inheritance' selects PROPERTY for inheritance.
15620 If the property is present but empty, the return value is the
15621 empty string. If the property is not present at all, nil is
15622 returned. In any other case, return the value as a string.
15623 Search is case-insensitive.
15625 If LITERAL-NIL is set, return the string value \"nil\" as
15626 a string, do not interpret it as the list atom nil. This is used
15627 for inheritance when a \"nil\" value can supersede a non-nil
15628 value higher up the hierarchy."
15629 (org-with-point-at pom
15632 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15633 (org-entry-get-with-inheritance property literal-nil))
15634 ((member-ignore-case property org-special-properties)
15635 ;; We need a special property. Use `org-entry-properties' to
15636 ;; retrieve it, but specify the wanted property.
15637 (cdr (assoc-string property (org-entry-properties nil property))))
15639 (let ((range (org-get-property-block)))
15641 (let* ((case-fold-search t)
15645 (or (assoc-string property org-file-properties t)
15646 (assoc-string property org-global-properties t)
15648 property org-global-properties-fixed t))))
15649 ;; Make sure to not re-use GLOBAL as
15650 ;; `org--update-property-plist' would alter it by
15652 (and global (list (cons property (cdr global))))))
15655 (when (re-search-forward (org-re-property key nil t) end t)
15657 (org--update-property-plist
15658 key (org-match-string-no-properties 3) props))))))
15659 (goto-char (car range))
15660 ;; Find base value.
15661 (save-excursion (funcall find-value property))
15662 ;; Find additional values.
15663 (let ((property+ (concat property "+")))
15664 (while (funcall find-value property+)))
15665 ;; Return final value.
15666 (let ((val (cdr (assoc-string property props t))))
15667 (if literal-nil val (org-not-nil val))))))))))
15669 (defun org-property-or-variable-value (var &optional inherit)
15670 "Check if there is a property fixing the value of VAR.
15671 If yes, return this value. If not, return the current value of the variable."
15672 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15673 (if (and prop (stringp prop) (string-match "\\S-" prop))
15675 (symbol-value var))))
15677 (defun org-entry-delete (pom property)
15678 "Delete the property PROPERTY from entry at point-or-marker POM."
15679 (unless (member property org-special-properties)
15680 (org-with-point-at pom
15681 (let ((range (org-get-property-block)))
15683 (let ((begin (car range))
15684 (end (copy-marker (cdr range))))
15686 (when (re-search-forward (org-re-property property nil t) end t)
15687 (delete-region (match-beginning 0) (line-beginning-position 2))
15688 ;; If drawer is empty, remove it altogether.
15689 (when (= begin end)
15690 (delete-region (line-beginning-position 0)
15691 (line-beginning-position 2)))
15692 (set-marker end nil))))))))
15694 ;; Multi-values properties are properties that contain multiple values
15695 ;; These values are assumed to be single words, separated by whitespace.
15696 (defun org-entry-add-to-multivalued-property (pom property value)
15697 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15698 (let* ((old (org-entry-get pom property))
15699 (values (and old (org-split-string old "[ \t]"))))
15700 (setq value (org-entry-protect-space value))
15701 (unless (member value values)
15702 (setq values (append values (list value)))
15703 (org-entry-put pom property
15704 (mapconcat 'identity values " ")))))
15706 (defun org-entry-remove-from-multivalued-property (pom property value)
15707 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15708 (let* ((old (org-entry-get pom property))
15709 (values (and old (org-split-string old "[ \t]"))))
15710 (setq value (org-entry-protect-space value))
15711 (when (member value values)
15712 (setq values (delete value values))
15713 (org-entry-put pom property
15714 (mapconcat 'identity values " ")))))
15716 (defun org-entry-member-in-multivalued-property (pom property value)
15717 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15718 (let* ((old (org-entry-get pom property))
15719 (values (and old (org-split-string old "[ \t]"))))
15720 (setq value (org-entry-protect-space value))
15721 (member value values)))
15723 (defun org-entry-get-multivalued-property (pom property)
15724 "Return a list of values in a multivalued property."
15725 (let* ((value (org-entry-get pom property))
15726 (values (and value (org-split-string value "[ \t]"))))
15727 (mapcar 'org-entry-restore-space values)))
15729 (defun org-entry-put-multivalued-property (pom property &rest values)
15730 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15731 VALUES should be a list of strings. Spaces will be protected."
15732 (org-entry-put pom property
15733 (mapconcat 'org-entry-protect-space values " "))
15734 (let* ((value (org-entry-get pom property))
15735 (values (and value (org-split-string value "[ \t]"))))
15736 (mapcar 'org-entry-restore-space values)))
15738 (defun org-entry-protect-space (s)
15739 "Protect spaces and newline in string S."
15740 (while (string-match " " s)
15741 (setq s (replace-match "%20" t t s)))
15742 (while (string-match "\n" s)
15743 (setq s (replace-match "%0A" t t s)))
15746 (defun org-entry-restore-space (s)
15747 "Restore spaces and newline in string S."
15748 (while (string-match "%20" s)
15749 (setq s (replace-match " " t t s)))
15750 (while (string-match "%0A" s)
15751 (setq s (replace-match "\n" t t s)))
15754 (defvar org-entry-property-inherited-from (make-marker)
15755 "Marker pointing to the entry from where a property was inherited.
15756 Each call to `org-entry-get-with-inheritance' will set this marker to the
15757 location of the entry where the inheritance search matched. If there was
15758 no match, the marker will point nowhere.
15759 Note that also `org-entry-get' calls this function, if the INHERIT flag
15762 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15763 "Get PROPERTY of entry or content at point, search higher levels if needed.
15764 The search will stop at the first ancestor which has the property defined.
15765 If the value found is \"nil\", return nil to show that the property
15766 should be considered as undefined (this is the meaning of nil here).
15767 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15768 (move-marker org-entry-property-inherited-from nil)
15770 (org-with-wide-buffer
15773 (when (setq value (org-entry-get nil property nil literal-nil))
15774 (org-back-to-heading t)
15775 (move-marker org-entry-property-inherited-from (point))
15777 (or (org-up-heading-safe) (throw 'exit nil)))))
15780 (cdr (or (assoc-string property org-file-properties t)
15781 (assoc-string property org-global-properties t)
15782 (assoc-string property org-global-properties-fixed t)))))
15783 (if literal-nil value (org-not-nil value))))
15785 (defvar org-property-changed-functions nil
15786 "Hook called when the value of a property has changed.
15787 Each hook function should accept two arguments, the name of the property
15788 and the new value.")
15790 (defun org-entry-put (pom property value)
15791 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15793 If the value is `nil', it is converted to the empty string. If
15794 it is not a string, an error is raised.
15796 PROPERTY can be any regular property (see
15797 `org-special-properties'). It can also be \"TODO\",
15798 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15800 For the last two properties, VALUE may have any of the special
15801 values \"earlier\" and \"later\". The function then increases or
15802 decreases scheduled or deadline date by one day."
15803 (cond ((null value) (setq value ""))
15804 ((not (stringp value)) (error "Properties values should be strings")))
15805 (org-with-point-at pom
15806 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15807 (org-back-to-heading t)
15808 (org-with-limited-levels (org-back-to-heading t)))
15809 (let ((beg (point)))
15811 ((equal property "TODO")
15812 (cond ((not (org-string-nw-p value)) (setq value 'none))
15813 ((not (member value org-todo-keywords-1))
15814 (user-error "\"%s\" is not a valid TODO state" value)))
15816 (org-set-tags nil 'align))
15817 ((equal property "PRIORITY")
15818 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15819 (org-set-tags nil 'align))
15820 ((equal property "SCHEDULED")
15822 (if (and (org-looking-at-p org-planning-line-re)
15824 org-scheduled-time-regexp (line-end-position) t))
15825 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15826 ((string= value "later") (org-timestamp-change 1 'day))
15827 ((string= value "") (org-schedule '(4)))
15828 (t (org-schedule nil value)))
15829 (if (member value '("earlier" "later" ""))
15830 (call-interactively #'org-schedule)
15831 (org-schedule nil value))))
15832 ((equal property "DEADLINE")
15834 (if (and (org-looking-at-p org-planning-line-re)
15836 org-deadline-time-regexp (line-end-position) t))
15837 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15838 ((string= value "later") (org-timestamp-change 1 'day))
15839 ((string= value "") (org-deadline '(4)))
15840 (t (org-deadline nil value)))
15841 (if (member value '("earlier" "later" ""))
15842 (call-interactively #'org-deadline)
15843 (org-deadline nil value))))
15844 ((member property org-special-properties)
15845 (error "The %s property cannot be set with `org-entry-put'" property))
15847 (let* ((range (org-get-property-block beg 'force))
15849 (case-fold-search t))
15850 (goto-char (car range))
15851 (if (re-search-forward (org-re-property property nil t) end t)
15852 (progn (delete-region (match-beginning 0) (match-end 0))
15853 (goto-char (match-beginning 0)))
15857 (insert ":" property ":")
15858 (when value (insert " " value))
15859 (org-indent-line)))))
15860 (run-hook-with-args 'org-property-changed-functions property value)))
15862 (defun org-buffer-property-keys (&optional specials defaults columns)
15863 "Get all property keys in the current buffer.
15865 When SPECIALS is non-nil, also list the special properties that
15866 reflect things like tags and TODO state.
15868 When DEFAULTS is non-nil, also include properties that has
15869 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15870 DESCRIPTION, LOCATION, and LOGGING and others.
15872 When COLUMNS in non-nil, also include property names given in
15873 COLUMN formats in the current buffer."
15874 (let ((case-fold-search t)
15876 (and specials org-special-properties)
15877 (and defaults (cons org-effort-property org-default-properties))
15879 (org-with-wide-buffer
15880 (goto-char (point-min))
15881 (while (re-search-forward org-property-start-re nil t)
15882 (let ((range (org-get-property-block)))
15885 (when (and (not (org-before-first-heading-p))
15886 (y-or-n-p (format "Malformed drawer at %d, repair?"
15887 (line-beginning-position))))
15888 (org-get-property-block nil t))
15890 (goto-char (car range))
15891 (let ((begin (car range))
15893 ;; Make sure that found property block is not located
15894 ;; before current point, as it would generate an infloop.
15895 ;; It can happen, for example, in the following
15902 ;; *************** Inlinetask
15907 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
15908 (while (< (point) end)
15909 (let ((p (progn (looking-at org-property-re)
15910 (org-match-string-no-properties 2))))
15911 ;; Only add true property name, not extension symbol.
15912 (add-to-list 'props
15913 (if (not (org-string-match-p "\\+\\'" p)) p
15914 (substring p 0 -1))))
15916 (outline-next-heading)))
15918 (goto-char (point-min))
15919 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15920 (let ((element (org-element-at-point)))
15921 (when (memq (org-element-type element) '(keyword node-property))
15922 (let ((value (org-element-property :value element))
15924 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
15925 (setq start (match-end 0))
15926 (let ((p (org-match-string-no-properties 1 value)))
15927 (unless (member-ignore-case
15928 p (cons "ITEM" org-special-properties))
15929 (add-to-list 'props p))))))))))
15930 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
15932 (defun org-property-values (key)
15933 "List all non-nil values of property KEY in current buffer."
15934 (org-with-wide-buffer
15935 (goto-char (point-min))
15936 (let ((case-fold-search t)
15937 (re (org-re-property key))
15939 (while (re-search-forward re nil t)
15940 (add-to-list 'values (org-entry-get (point) key)))
15943 (defun org-insert-property-drawer ()
15944 "Insert a property drawer into the current entry."
15945 (org-with-wide-buffer
15946 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15947 (org-back-to-heading t)
15948 (org-with-limited-levels (org-back-to-heading t)))
15950 (when (org-looking-at-p org-planning-line-re) (forward-line))
15951 (unless (org-looking-at-p org-property-drawer-re)
15952 (let ((inhibit-read-only t))
15953 (unless (bolp) (insert "\n"))
15954 (let ((begin (point)))
15955 (insert ":PROPERTIES:\n:END:\n")
15956 (org-indent-region begin (point)))))))
15958 (defun org-insert-drawer (&optional arg drawer)
15959 "Insert a drawer at point.
15961 When optional argument ARG is non-nil, insert a property drawer.
15963 Optional argument DRAWER, when non-nil, is a string representing
15964 drawer's name. Otherwise, the user is prompted for a name.
15966 If a region is active, insert the drawer around that region
15969 Point is left between drawer's boundaries."
15971 (let* ((drawer (if arg "PROPERTIES"
15972 (or drawer (read-from-minibuffer "Drawer: ")))))
15974 ;; With C-u, fall back on `org-insert-property-drawer'
15975 (arg (org-insert-property-drawer))
15976 ;; Check validity of suggested drawer's name.
15977 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15978 (user-error "Invalid drawer name"))
15979 ;; With an active region, insert a drawer at point.
15980 ((not (org-region-active-p))
15982 (unless (bolp) (insert "\n"))
15983 (insert (format ":%s:\n\n:END:\n" drawer))
15984 (forward-line -2)))
15985 ;; Otherwise, insert the drawer at point
15987 (let ((rbeg (region-beginning))
15988 (rend (copy-marker (region-end))))
15992 (beginning-of-line)
15993 (when (save-excursion
15994 (re-search-forward org-outline-regexp-bol rend t))
15995 (user-error "Drawers cannot contain headlines"))
15996 ;; Position point at the beginning of the first
15997 ;; non-blank line in region. Insert drawer's opening
15998 ;; there, then indent it.
15999 (org-skip-whitespace)
16000 (beginning-of-line)
16001 (insert ":" drawer ":\n")
16003 (indent-for-tab-command)
16004 ;; Move point to the beginning of the first blank line
16005 ;; after the last non-blank line in region. Insert
16006 ;; drawer's closing, then indent it.
16008 (skip-chars-backward " \r\t\n")
16010 (deactivate-mark t)
16011 (indent-for-tab-command)
16012 (unless (eolp) (insert "\n")))
16013 ;; Clear marker, whatever the outcome of insertion is.
16014 (set-marker rend nil)))))))
16016 (defvar org-property-set-functions-alist nil
16017 "Property set function alist.
16018 Each entry should have the following format:
16020 (PROPERTY . READ-FUNCTION)
16022 The read function will be called with the same argument as
16023 `org-completing-read'.")
16025 (defun org-set-property-function (property)
16026 "Get the function that should be used to set PROPERTY.
16027 This is computed according to `org-property-set-functions-alist'."
16028 (or (cdr (assoc property org-property-set-functions-alist))
16029 'org-completing-read))
16031 (defun org-read-property-value (property)
16032 "Read PROPERTY value from user."
16033 (let* ((completion-ignore-case t)
16034 (allowed (org-property-get-allowed-values nil property 'table))
16035 (cur (org-entry-get nil property))
16036 (prompt (concat property " value"
16037 (if (and cur (string-match "\\S-" cur))
16038 (concat " [" cur "]") "") ": "))
16039 (set-function (org-set-property-function property))
16041 (funcall set-function prompt allowed nil
16042 (not (get-text-property 0 'org-unrestricted
16044 (let (org-completion-use-ido org-completion-use-iswitchb)
16045 (funcall set-function prompt
16046 (mapcar 'list (org-property-values property))
16047 nil nil "" nil cur)))))
16050 (defvar org-last-set-property nil)
16051 (defvar org-last-set-property-value nil)
16052 (defun org-read-property-name ()
16053 "Read a property name."
16054 (let* ((completion-ignore-case t)
16055 (keys (org-buffer-property-keys nil t t))
16056 (default-prop (or (save-excursion
16058 (beginning-of-line)
16059 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16060 (null (string= (match-string 1) "END"))
16061 (match-string 1))))
16062 org-last-set-property))
16063 (property (org-icompleting-read
16065 (if default-prop (concat " [" default-prop "]") "")
16067 (mapcar 'list keys)
16070 (if (member property keys)
16072 (or (cdr (assoc (downcase property)
16073 (mapcar (lambda (x) (cons (downcase x) x))
16077 (defun org-set-property-and-value (use-last)
16078 "Allow to set [PROPERTY]: [value] direction from prompt.
16079 When use-default, don't even ask, just use the last
16080 \"[PROPERTY]: [value]\" string from the history."
16082 (let* ((completion-ignore-case t)
16083 (pv (or (and use-last org-last-set-property-value)
16084 (org-completing-read
16085 "Enter a \"[Property]: [value]\" pair: "
16086 nil nil nil nil nil
16087 org-last-set-property-value)))
16089 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16090 (setq prop (match-string 1 pv)
16091 val (match-string 2 pv))
16092 (org-set-property prop val))))
16094 (defun org-set-property (property value)
16095 "In the current entry, set PROPERTY to VALUE.
16096 When called interactively, this will prompt for a property name, offering
16097 completion on existing and default properties. And then it will prompt
16098 for a value, offering completion either on allowed values (via an inherited
16099 xxx_ALL property) or on existing values in other instances of this property
16100 in the current file."
16101 (interactive (list nil nil))
16102 (let* ((property (or property (org-read-property-name)))
16103 (value (or value (org-read-property-value property)))
16104 (fn (cdr (assoc property org-properties-postprocess-alist))))
16105 (setq org-last-set-property property)
16106 (setq org-last-set-property-value (concat property ": " value))
16107 ;; Possibly postprocess the inserted value:
16108 (when fn (setq value (funcall fn value)))
16109 (unless (equal (org-entry-get nil property) value)
16110 (org-entry-put nil property value))))
16112 (defun org-delete-property (property)
16113 "In the current entry, delete PROPERTY."
16115 (let* ((completion-ignore-case t)
16116 (cat (org-entry-get (point) "CATEGORY"))
16117 (props0 (org-entry-properties nil 'standard))
16118 (props (if cat props0
16119 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16120 (prop (if (< 1 (length props))
16121 (org-icompleting-read "Property: " props nil t)
16125 (message "No property to delete in this entry")
16126 (org-entry-delete nil property)
16127 (message "Property \"%s\" deleted" property)))
16129 (defun org-delete-property-globally (property)
16130 "Remove PROPERTY globally, from all entries."
16132 (let* ((completion-ignore-case t)
16133 (prop (org-icompleting-read
16134 "Globally remove property: "
16135 (mapcar 'list (org-buffer-property-keys)))))
16140 (goto-char (point-min))
16142 (while (re-search-forward
16143 (org-re-property property)
16145 (setq cnt (1+ cnt))
16146 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16147 (message "Property \"%s\" removed from %d entries" property cnt)))))
16149 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16151 (defun org-compute-property-at-point ()
16152 "Compute the property at point.
16153 This looks for an enclosing column format, extracts the operator and
16154 then applies it to the property in the column format's scope."
16156 (unless (org-at-property-p)
16157 (user-error "Not at a property"))
16158 (let ((prop (org-match-string-no-properties 2)))
16159 (org-columns-get-format-and-top-level)
16160 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16161 (user-error "No operator defined for property %s" prop))
16162 (org-columns-compute prop)))
16164 (defvar org-property-allowed-value-functions nil
16165 "Hook for functions supplying allowed values for a specific property.
16166 The functions must take a single argument, the name of the property, and
16167 return a flat list of allowed values. If \":ETC\" is one of
16168 the values, this means that these values are intended as defaults for
16169 completion, but that other values should be allowed too.
16170 The functions must return nil if they are not responsible for this
16173 (defun org-property-get-allowed-values (pom property &optional table)
16174 "Get allowed values for the property PROPERTY.
16175 When TABLE is non-nil, return an alist that can directly be used for
16179 ((equal property "TODO")
16180 (setq vals (org-with-point-at pom
16181 (append org-todo-keywords-1 '("")))))
16182 ((equal property "PRIORITY")
16183 (let ((n org-lowest-priority))
16184 (while (>= n org-highest-priority)
16185 (push (char-to-string n) vals)
16187 ((member property org-special-properties))
16188 ((setq vals (run-hook-with-args-until-success
16189 'org-property-allowed-value-functions property)))
16191 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16192 (when (and vals (string-match "\\S-" vals))
16193 (setq vals (car (read-from-string (concat "(" vals ")"))))
16194 (setq vals (mapcar (lambda (x)
16195 (cond ((stringp x) x)
16196 ((numberp x) (number-to-string x))
16197 ((symbolp x) (symbol-name x))
16200 (when (member ":ETC" vals)
16201 (setq vals (remove ":ETC" vals))
16202 (org-add-props (car vals) '(org-unrestricted t)))
16203 (if table (mapcar 'list vals) vals)))
16205 (defun org-property-previous-allowed-value (&optional previous)
16206 "Switch to the next allowed value for this property."
16208 (org-property-next-allowed-value t))
16210 (defun org-property-next-allowed-value (&optional previous)
16211 "Switch to the next allowed value for this property."
16213 (unless (org-at-property-p)
16214 (user-error "Not at a property"))
16215 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16216 (key (match-string 2))
16217 (value (match-string 3))
16218 (allowed (or (org-property-get-allowed-values (point) key)
16219 (and (member value '("[ ]" "[-]" "[X]"))
16221 (heading (save-match-data (nth 4 (org-heading-components))))
16224 (user-error "Allowed values for this property have not been defined"))
16225 (if previous (setq allowed (reverse allowed)))
16226 (if (member value allowed)
16227 (setq nval (car (cdr (member value allowed)))))
16228 (setq nval (or nval (car allowed)))
16229 (if (equal nval value)
16230 (user-error "Only one allowed value for this property"))
16231 (org-at-property-p)
16232 (replace-match (concat " :" key ": " nval) t t)
16234 (beginning-of-line 1)
16235 (skip-chars-forward " \t")
16236 (when (equal prop org-effort-property)
16237 (org-refresh-property
16238 '((effort . identity)
16239 (effort-minutes . org-duration-string-to-minutes))
16241 (when (string= org-clock-current-task heading)
16242 (setq org-clock-effort nval)
16243 (org-clock-update-mode-line)))
16244 (run-hook-with-args 'org-property-changed-functions key nval)))
16246 (defun org-find-olp (path &optional this-buffer)
16247 "Return a marker pointing to the entry at outline path OLP.
16248 If anything goes wrong, throw an error.
16249 You can wrap this call to catch the error like this:
16251 (condition-case msg
16252 (org-mobile-locate-entry (match-string 4))
16253 (error (nth 1 msg)))
16255 The return value will then be either a string with the error message,
16256 or a marker if everything is OK.
16258 If THIS-BUFFER is set, the outline path does not contain a file,
16260 (let* ((file (if this-buffer buffer-file-name (pop path)))
16261 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16265 limit re end found pos heading cnt flevel)
16266 (unless buffer (error "File not found :%s" file))
16267 (with-current-buffer buffer
16271 (setq limit (point-max))
16272 (goto-char (point-min))
16273 (while (setq heading (pop path))
16274 (setq re (format org-complex-heading-regexp-format
16275 (regexp-quote heading)))
16276 (setq cnt 0 pos (point))
16277 (while (re-search-forward re end t)
16278 (setq level (- (match-end 1) (match-beginning 1)))
16279 (if (and (>= level lmin) (<= level lmax))
16280 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16281 (when (= cnt 0) (error "Heading not found on level %d: %s"
16283 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16286 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16287 (setq end (save-excursion (org-end-of-subtree t t))))
16288 (when (org-at-heading-p)
16289 (point-marker)))))))
16291 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16292 "Find node HEADING in BUFFER.
16293 Return a marker to the heading if it was found, or nil if not.
16294 If POS-ONLY is set, return just the position instead of a marker.
16296 The heading text must match exact, but it may have a TODO keyword,
16297 a priority cookie and tags in the standard locations."
16298 (with-current-buffer (or buffer (current-buffer))
16302 (goto-char (point-min))
16303 (let (case-fold-search)
16304 (if (re-search-forward
16305 (format org-complex-heading-regexp-format
16306 (regexp-quote heading)) nil t)
16308 (match-beginning 0)
16309 (move-marker (make-marker) (match-beginning 0)))))))))
16311 (defun org-find-exact-heading-in-directory (heading &optional dir)
16312 "Find Org node headline HEADING in all .org files in directory DIR.
16313 When the target headline is found, return a marker to this location."
16314 (let ((files (directory-files (or dir default-directory)
16315 t "\\`[^.#].*\\.org\\'"))
16316 file visiting m buffer)
16318 (while (setq file (pop files))
16319 (message "trying %s" file)
16320 (setq visiting (org-find-base-buffer-visiting file))
16321 (setq buffer (or visiting (find-file-noselect file)))
16322 (setq m (org-find-exact-headline-in-buffer
16324 (when (and (not m) (not visiting)) (kill-buffer buffer))
16325 (and m (throw 'found m))))))
16327 (defun org-find-entry-with-id (ident)
16328 "Locate the entry that contains the ID property with exact value IDENT.
16329 IDENT can be a string, a symbol or a number, this function will search for
16330 the string representation of it.
16331 Return the position where this entry starts, or nil if there is no such entry."
16332 (interactive "sID: ")
16334 ((stringp ident) ident)
16335 ((symbol-name ident) (symbol-name ident))
16336 ((numberp ident) (number-to-string ident))
16337 (t (error "IDENT %s must be a string, symbol or number" ident))))
16338 (case-fold-search nil))
16342 (goto-char (point-min))
16343 (when (re-search-forward
16344 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16346 (org-back-to-heading t)
16351 (defvar org-last-changed-timestamp nil)
16352 (defvar org-last-inserted-timestamp nil
16353 "The last time stamp inserted with `org-insert-time-stamp'.")
16354 (defvar org-ts-what) ; dynamically scoped parameter
16356 (defun org-time-stamp (arg &optional inactive)
16357 "Prompt for a date/time and insert a time stamp.
16358 If the user specifies a time like HH:MM or if this command is
16359 called with at least one prefix argument, the time stamp contains
16360 the date and the time. Otherwise, only the date is be included.
16362 All parts of a date not specified by the user is filled in from
16363 the current date/time. So if you just press return without
16364 typing anything, the time stamp will represent the current
16367 If there is already a timestamp at the cursor, it will be
16370 With two universal prefix arguments, insert an active timestamp
16371 with the current time without prompting the user.
16373 When called from lisp, the timestamp is inactive if INACTIVE is
16378 ;; Default time is either today, or, when entering a range,
16379 ;; the range start.
16380 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16382 (re-search-backward
16383 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16384 (- (point) 20) t)))
16385 (apply 'encode-time (org-parse-time-string (match-string 1)))
16387 (default-input (and ts (org-get-compact-tod ts)))
16388 (repeater (save-excursion
16390 (beginning-of-line)
16391 (when (re-search-forward
16392 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16393 (save-excursion (progn (end-of-line) (point))) t)
16394 (match-string 0)))))
16395 org-time-was-given org-end-time-was-given time)
16397 ((and (org-at-timestamp-p t)
16398 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16399 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16401 (setq time (let ((this-command this-command))
16402 (org-read-date arg 'totime nil nil
16403 default-time default-input inactive)))
16404 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16405 ((org-at-timestamp-p t)
16406 (setq time (let ((this-command this-command))
16407 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16408 (when (org-at-timestamp-p t) ; just to get the match data
16409 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16411 (setq org-last-changed-timestamp
16412 (org-insert-time-stamp
16413 time (or org-time-was-given arg)
16414 inactive nil nil (list org-end-time-was-given)))
16415 (when repeater (goto-char (1- (point))) (insert " " repeater)
16416 (setq org-last-changed-timestamp
16417 (concat (substring org-last-inserted-timestamp 0 -1)
16418 " " repeater ">"))))
16419 (message "Timestamp updated"))
16421 (org-insert-time-stamp (current-time) t inactive))
16423 (setq time (let ((this-command this-command))
16424 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16425 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16426 nil nil (list org-end-time-was-given))))))
16428 ;; FIXME: can we use this for something else, like computing time differences?
16429 (defun org-get-compact-tod (s)
16430 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16431 (let* ((t1 (match-string 1 s))
16432 (h1 (string-to-number (match-string 2 s)))
16433 (m1 (string-to-number (match-string 3 s)))
16434 (t2 (and (match-end 4) (match-string 5 s)))
16435 (h2 (and t2 (string-to-number (match-string 6 s))))
16436 (m2 (and t2 (string-to-number (match-string 7 s))))
16440 (setq dh (- h2 h1) dm (- m2 m1))
16441 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16442 (concat t1 "+" (number-to-string dh)
16443 (and (/= 0 dm) (format ":%02d" dm)))))))
16445 (defun org-time-stamp-inactive (&optional arg)
16446 "Insert an inactive time stamp.
16447 An inactive time stamp is enclosed in square brackets instead of angle
16448 brackets. It is inactive in the sense that it does not trigger agenda entries,
16449 does not link to the calendar and cannot be changed with the S-cursor keys.
16450 So these are more for recording a certain time/date."
16452 (org-time-stamp arg 'inactive))
16454 (defvar org-date-ovl (make-overlay 1 1))
16455 (overlay-put org-date-ovl 'face 'org-date-selected)
16456 (org-detach-overlay org-date-ovl)
16458 (defvar org-ans1) ; dynamically scoped parameter
16459 (defvar org-ans2) ; dynamically scoped parameter
16461 (defvar org-plain-time-of-day-regexp) ; defined below
16463 (defvar org-overriding-default-time nil) ; dynamically scoped
16464 (defvar org-read-date-overlay nil)
16465 (defvar org-dcst nil) ; dynamically scoped
16466 (defvar org-read-date-history nil)
16467 (defvar org-read-date-final-answer nil)
16468 (defvar org-read-date-analyze-futurep nil)
16469 (defvar org-read-date-analyze-forced-year nil)
16470 (defvar org-read-date-inactive)
16472 (defvar org-read-date-minibuffer-local-map
16473 (let* ((org-replace-disputed-keys nil)
16474 (map (make-sparse-keymap)))
16475 (set-keymap-parent map minibuffer-local-map)
16476 (org-defkey map (kbd ".")
16477 (lambda () (interactive)
16478 ;; Are we at the beginning of the prompt?
16479 (if (looking-back "^[^:]+: ")
16480 (org-eval-in-calendar '(calendar-goto-today))
16482 (org-defkey map (kbd "C-.")
16483 (lambda () (interactive)
16484 (org-eval-in-calendar '(calendar-goto-today))))
16485 (org-defkey map [(meta shift left)]
16486 (lambda () (interactive)
16487 (org-eval-in-calendar '(calendar-backward-month 1))))
16488 (org-defkey map [(meta shift right)]
16489 (lambda () (interactive)
16490 (org-eval-in-calendar '(calendar-forward-month 1))))
16491 (org-defkey map [(meta shift up)]
16492 (lambda () (interactive)
16493 (org-eval-in-calendar '(calendar-backward-year 1))))
16494 (org-defkey map [(meta shift down)]
16495 (lambda () (interactive)
16496 (org-eval-in-calendar '(calendar-forward-year 1))))
16497 (org-defkey map [?\e (shift left)]
16498 (lambda () (interactive)
16499 (org-eval-in-calendar '(calendar-backward-month 1))))
16500 (org-defkey map [?\e (shift right)]
16501 (lambda () (interactive)
16502 (org-eval-in-calendar '(calendar-forward-month 1))))
16503 (org-defkey map [?\e (shift up)]
16504 (lambda () (interactive)
16505 (org-eval-in-calendar '(calendar-backward-year 1))))
16506 (org-defkey map [?\e (shift down)]
16507 (lambda () (interactive)
16508 (org-eval-in-calendar '(calendar-forward-year 1))))
16509 (org-defkey map [(shift up)]
16510 (lambda () (interactive)
16511 (org-eval-in-calendar '(calendar-backward-week 1))))
16512 (org-defkey map [(shift down)]
16513 (lambda () (interactive)
16514 (org-eval-in-calendar '(calendar-forward-week 1))))
16515 (org-defkey map [(shift left)]
16516 (lambda () (interactive)
16517 (org-eval-in-calendar '(calendar-backward-day 1))))
16518 (org-defkey map [(shift right)]
16519 (lambda () (interactive)
16520 (org-eval-in-calendar '(calendar-forward-day 1))))
16521 (org-defkey map "!"
16522 (lambda () (interactive)
16523 (org-eval-in-calendar '(diary-view-entries))
16525 (org-defkey map ">"
16526 (lambda () (interactive)
16527 (org-eval-in-calendar '(calendar-scroll-left 1))))
16528 (org-defkey map "<"
16529 (lambda () (interactive)
16530 (org-eval-in-calendar '(calendar-scroll-right 1))))
16531 (org-defkey map "\C-v"
16532 (lambda () (interactive)
16533 (org-eval-in-calendar
16534 '(calendar-scroll-left-three-months 1))))
16535 (org-defkey map "\M-v"
16536 (lambda () (interactive)
16537 (org-eval-in-calendar
16538 '(calendar-scroll-right-three-months 1))))
16540 "Keymap for minibuffer commands when using `org-read-date'.")
16543 (defvar org-defdecode)
16544 (defvar org-with-time)
16546 (defun org-read-date (&optional org-with-time to-time from-string prompt
16547 default-time default-input inactive)
16548 "Read a date, possibly a time, and make things smooth for the user.
16549 The prompt will suggest to enter an ISO date, but you can also enter anything
16550 which will at least partially be understood by `parse-time-string'.
16551 Unrecognized parts of the date will default to the current day, month, year,
16552 hour and minute. If this command is called to replace a timestamp at point,
16553 or to enter the second timestamp of a range, the default time is taken
16554 from the existing stamp. Furthermore, the command prefers the future,
16555 so if you are giving a date where the year is not given, and the day-month
16556 combination is already past in the current year, it will assume you
16557 mean next year. For details, see the manual. A few examples:
16559 3-2-5 --> 2003-02-05
16560 feb 15 --> currentyear-02-15
16561 2/15 --> currentyear-02-15
16562 sep 12 9 --> 2009-09-12
16563 12:45 --> today 12:45
16564 22 sept 0:34 --> currentyear-09-22 0:34
16565 12 --> currentyear-currentmonth-12
16566 Fri --> nearest Friday after today
16567 -Tue --> last Tuesday
16570 Furthermore you can specify a relative date by giving, as the *first* thing
16571 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16572 change in days weeks, months, years.
16573 With a single plus or minus, the date is relative to today. With a double
16574 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16575 +4d --> four days from today
16576 +4 --> same as above
16577 +2w --> two weeks from today
16578 ++5 --> five days from default date
16580 The function understands only English month and weekday abbreviations.
16582 While prompting, a calendar is popped up - you can also select the
16583 date with the mouse (button 1). The calendar shows a period of three
16584 months. To scroll it to other months, use the keys `>' and `<'.
16585 If you don't like the calendar, turn it off with
16586 \(setq org-read-date-popup-calendar nil)
16588 With optional argument TO-TIME, the date will immediately be converted
16589 to an internal time.
16590 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16591 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16592 still enter a time, and this function will inform the calling routine
16593 about this change. The calling routine may then choose to change the
16594 format used to insert the time stamp into the buffer to include the time.
16595 With optional argument FROM-STRING, read from this string instead from
16596 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16597 the time/date that is used for everything that is not specified by the
16599 (require 'parse-time)
16600 (let* ((org-time-stamp-rounding-minutes
16601 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16602 (org-dcst org-display-custom-times)
16603 (ct (org-current-time))
16604 (org-def (or org-overriding-default-time default-time ct))
16605 (org-defdecode (decode-time org-def))
16607 (when (< (nth 2 org-defdecode) org-extend-today-until)
16608 (setcar (nthcdr 2 org-defdecode) -1)
16609 (setcar (nthcdr 1 org-defdecode) 59)
16610 (setq org-def (apply 'encode-time org-defdecode)
16611 org-defdecode (decode-time org-def)))))
16612 (mouse-autoselect-window nil) ; Don't let the mouse jump
16613 (calendar-frame-setup nil)
16614 (calendar-setup nil)
16615 (calendar-move-hook nil)
16616 (calendar-view-diary-initially-flag nil)
16617 (calendar-view-holidays-initially-flag nil)
16618 (timestr (format-time-string
16619 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16620 (prompt (concat (if prompt (concat prompt " ") "")
16621 (format "Date+time [%s]: " timestr)))
16622 ans (org-ans0 "") org-ans1 org-ans2 final)
16625 (from-string (setq ans from-string))
16626 (org-read-date-popup-calendar
16628 (save-window-excursion
16630 (org-eval-in-calendar '(setq cursor-type nil) t)
16633 (calendar-forward-day (- (time-to-days org-def)
16634 (calendar-absolute-from-gregorian
16635 (calendar-current-date))))
16636 (org-eval-in-calendar nil t)
16637 (let* ((old-map (current-local-map))
16638 (map (copy-keymap calendar-mode-map))
16639 (minibuffer-local-map
16640 (copy-keymap org-read-date-minibuffer-local-map)))
16641 (org-defkey map (kbd "RET") 'org-calendar-select)
16642 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16643 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16646 (use-local-map map)
16647 (setq org-read-date-inactive inactive)
16648 (add-hook 'post-command-hook 'org-read-date-display)
16649 (setq org-ans0 (read-string prompt default-input
16650 'org-read-date-history nil))
16651 ;; org-ans0: from prompt
16652 ;; org-ans1: from mouse click
16653 ;; org-ans2: from calendar motion
16654 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16655 (remove-hook 'post-command-hook 'org-read-date-display)
16656 (use-local-map old-map)
16657 (when org-read-date-overlay
16658 (delete-overlay org-read-date-overlay)
16659 (setq org-read-date-overlay nil)))))
16660 (bury-buffer "*Calendar*")))))
16662 (t ; Naked prompt only
16664 (setq ans (read-string prompt default-input
16665 'org-read-date-history timestr))
16666 (when org-read-date-overlay
16667 (delete-overlay org-read-date-overlay)
16668 (setq org-read-date-overlay nil)))))
16670 (setq final (org-read-date-analyze ans org-def org-defdecode))
16672 (when org-read-date-analyze-forced-year
16673 (message "Year was forced into %s"
16674 (if org-read-date-force-compatible-dates
16675 "compatible range (1970-2037)"
16676 "range representable on this machine"))
16679 ;; One round trip to get rid of 34th of August and stuff like that....
16680 (setq final (decode-time (apply 'encode-time final)))
16682 (setq org-read-date-final-answer ans)
16685 (apply 'encode-time final)
16686 (if (and (boundp 'org-time-was-given) org-time-was-given)
16687 (format "%04d-%02d-%02d %02d:%02d"
16688 (nth 5 final) (nth 4 final) (nth 3 final)
16689 (nth 2 final) (nth 1 final))
16690 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16692 (defun org-read-date-display ()
16693 "Display the current date prompt interpretation in the minibuffer."
16694 (when org-read-date-display-live
16695 (when org-read-date-overlay
16696 (delete-overlay org-read-date-overlay))
16697 (when (minibufferp (current-buffer))
16700 (while (not (equal (buffer-substring
16701 (max (point-min) (- (point) 4)) (point))
16704 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16705 " " (or org-ans1 org-ans2)))
16706 (org-end-time-was-given nil)
16707 (f (org-read-date-analyze ans org-def org-defdecode))
16709 org-time-stamp-custom-formats
16710 org-time-stamp-formats))
16711 (fmt (if (or org-with-time
16712 (and (boundp 'org-time-was-given) org-time-was-given))
16715 (txt (format-time-string fmt (apply 'encode-time f)))
16716 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16717 (txt (concat "=> " txt)))
16718 (when (and org-end-time-was-given
16719 (string-match org-plain-time-of-day-regexp txt))
16720 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16721 org-end-time-was-given
16722 (substring txt (match-end 0)))))
16723 (when org-read-date-analyze-futurep
16724 (setq txt (concat txt " (=>F)")))
16725 (setq org-read-date-overlay
16726 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16727 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16729 (defun org-read-date-analyze (ans org-def org-defdecode)
16730 "Analyze the combined answer of the date prompt."
16731 ;; FIXME: cleanup and comment
16732 (let ((nowdecode (decode-time (current-time)))
16733 delta deltan deltaw deltadef year month day
16734 hour minute second wday pm h2 m2 tl wday1
16735 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16736 (setq org-read-date-analyze-futurep nil
16737 org-read-date-analyze-forced-year nil)
16738 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16741 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16742 (setq ans (replace-match "" t t ans)
16744 deltaw (nth 1 delta)
16745 deltadef (nth 2 delta)))
16747 ;; Check if there is an iso week date in there. If yes, store the
16748 ;; info and postpone interpreting it until the rest of the parsing
16750 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16751 (setq iso-year (if (match-end 1)
16752 (org-small-year-to-year
16753 (string-to-number (match-string 1 ans))))
16754 iso-weekday (if (match-end 3)
16755 (string-to-number (match-string 3 ans)))
16756 iso-week (string-to-number (match-string 2 ans)))
16757 (setq ans (replace-match "" t t ans)))
16759 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16760 (when (string-match
16761 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16762 (setq year (if (match-end 2)
16763 (string-to-number (match-string 2 ans))
16764 (progn (setq kill-year t)
16765 (string-to-number (format-time-string "%Y"))))
16766 month (string-to-number (match-string 3 ans))
16767 day (string-to-number (match-string 4 ans)))
16768 (if (< year 100) (setq year (+ 2000 year)))
16769 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16772 ;; Help matching dotted european dates
16773 (when (string-match
16774 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16775 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16777 (string-to-number (format-time-string "%Y")))
16778 day (string-to-number (match-string 1 ans))
16779 month (string-to-number (match-string 2 ans))
16780 ans (replace-match (format "%04d-%02d-%02d" year month day)
16783 ;; Help matching american dates, like 5/30 or 5/30/7
16784 (when (string-match
16785 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16786 (setq year (if (match-end 4)
16787 (string-to-number (match-string 4 ans))
16788 (progn (setq kill-year t)
16789 (string-to-number (format-time-string "%Y"))))
16790 month (string-to-number (match-string 1 ans))
16791 day (string-to-number (match-string 2 ans)))
16792 (if (< year 100) (setq year (+ 2000 year)))
16793 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16795 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16796 ;; If there is a time with am/pm, and *no* time without it, we convert
16797 ;; so that matching will be successful.
16798 (loop for i from 1 to 2 do ; twice, for end time as well
16799 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16800 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16801 (setq hour (string-to-number (match-string 1 ans))
16802 minute (if (match-end 3)
16803 (string-to-number (match-string 3 ans))
16806 (string-to-char (downcase (match-string 4 ans)))))
16807 (if (and (= hour 12) (not pm))
16809 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16810 (setq ans (replace-match (format "%02d:%02d" hour minute)
16813 ;; Check if a time range is given as a duration
16814 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16815 (setq hour (string-to-number (match-string 1 ans))
16816 h2 (+ hour (string-to-number (match-string 3 ans)))
16817 minute (string-to-number (match-string 2 ans))
16818 m2 (+ minute (if (match-end 5) (string-to-number
16819 (match-string 5 ans))0)))
16820 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16821 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16824 ;; Check if there is a time range
16825 (when (boundp 'org-end-time-was-given)
16826 (setq org-time-was-given nil)
16827 (when (and (string-match org-plain-time-of-day-regexp ans)
16829 (setq org-end-time-was-given (match-string 8 ans))
16830 (setq ans (concat (substring ans 0 (match-beginning 7))
16831 (substring ans (match-end 7))))))
16833 (setq tl (parse-time-string ans)
16834 day (or (nth 3 tl) (nth 3 org-defdecode))
16835 month (or (nth 4 tl)
16836 (if (and org-read-date-prefer-future
16837 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16838 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16839 (nth 4 org-defdecode)))
16840 year (or (and (not kill-year) (nth 5 tl))
16841 (if (and org-read-date-prefer-future
16842 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16843 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16844 (nth 5 org-defdecode)))
16845 hour (or (nth 2 tl) (nth 2 org-defdecode))
16846 minute (or (nth 1 tl) (nth 1 org-defdecode))
16847 second (or (nth 0 tl) 0)
16850 (when (and (eq org-read-date-prefer-future 'time)
16851 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16852 (equal day (nth 3 nowdecode))
16853 (equal month (nth 4 nowdecode))
16854 (equal year (nth 5 nowdecode))
16856 (or (< (nth 2 tl) (nth 2 nowdecode))
16857 (and (= (nth 2 tl) (nth 2 nowdecode))
16859 (< (nth 1 tl) (nth 1 nowdecode)))))
16863 ;; Special date definitions below
16866 ;; There was an iso week
16869 (setq year (or iso-year year)
16870 day (or iso-weekday wday 1)
16871 wday nil ; to make sure that the trigger below does not match
16872 iso-date (calendar-gregorian-from-absolute
16873 (calendar-absolute-from-iso
16874 (list iso-week day year))))
16875 ; FIXME: Should we also push ISO weeks into the future?
16876 ; (when (and org-read-date-prefer-future
16878 ; (< (calendar-absolute-from-gregorian iso-date)
16879 ; (time-to-days (current-time))))
16880 ; (setq year (1+ year)
16881 ; iso-date (calendar-gregorian-from-absolute
16882 ; (calendar-absolute-from-iso
16883 ; (list iso-week day year)))))
16884 (setq month (car iso-date)
16885 year (nth 2 iso-date)
16886 day (nth 1 iso-date)))
16890 (let ((now (decode-time (current-time))))
16891 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16892 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16893 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16894 ((equal deltaw "m") (setq month (+ month deltan)))
16895 ((equal deltaw "y") (setq year (+ year deltan)))))
16896 ((and wday (not (nth 3 tl)))
16897 ;; Weekday was given, but no day, so pick that day in the week
16898 ;; on or after the derived date.
16899 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16900 (unless (equal wday wday1)
16901 (setq day (+ day (% (- wday wday1 -7) 7))))))
16902 (if (and (boundp 'org-time-was-given)
16904 (setq org-time-was-given t))
16905 (if (< year 100) (setq year (+ 2000 year)))
16906 ;; Check of the date is representable
16907 (if org-read-date-force-compatible-dates
16910 (setq year 1970 org-read-date-analyze-forced-year t))
16912 (setq year 2037 org-read-date-analyze-forced-year t)))
16913 (condition-case nil
16914 (ignore (encode-time second minute hour day month year))
16916 (setq year (nth 5 org-defdecode))
16917 (setq org-read-date-analyze-forced-year t))))
16918 (setq org-read-date-analyze-futurep futurep)
16919 (list second minute hour day month year)))
16921 (defvar parse-time-weekdays)
16922 (defun org-read-date-get-relative (s today default)
16923 "Check string S for special relative date string.
16924 TODAY and DEFAULT are internal times, for today and for a default.
16925 Return shift list (N what def-flag)
16926 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16927 N is the number of WHATs to shift.
16928 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16929 the DEFAULT date rather than TODAY."
16930 (require 'parse-time)
16934 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16936 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16937 "\\([ \t]\\|$\\)") s)
16938 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16939 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16940 (string-to-char (substring (match-string 1 s) -1))
16942 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16943 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16944 (what (if (match-end 3) (match-string 3 s) "d"))
16945 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16946 (date (if rel default today))
16947 (wday (nth 6 (decode-time date)))
16951 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16952 (if (= delta 0) (setq delta 7))
16955 (setq delta (- delta 7))
16956 (if (= delta 0) (setq delta -7))))
16957 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16958 (list delta "d" rel))
16959 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16961 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16962 "Turn a user-specified date into the internal representation.
16963 The internal representation needed by the calendar is (month day year).
16964 This is a wrapper to handle the brain-dead convention in calendar that
16965 user function argument order change dependent on argument order."
16966 (if (boundp 'calendar-date-style)
16968 ((eq calendar-date-style 'american)
16969 (list arg1 arg2 arg3))
16970 ((eq calendar-date-style 'european)
16971 (list arg2 arg1 arg3))
16972 ((eq calendar-date-style 'iso)
16973 (list arg2 arg3 arg1)))
16974 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16975 (if (org-bound-and-true-p european-calendar-style)
16976 (list arg2 arg1 arg3)
16977 (list arg1 arg2 arg3)))))
16979 (defun org-eval-in-calendar (form &optional keepdate)
16980 "Eval FORM in the calendar window and return to current window.
16981 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16982 otherwise stick to the current value of `org-ans2'."
16983 (let ((sf (selected-frame))
16984 (sw (selected-window)))
16985 (select-window (get-buffer-window "*Calendar*" t))
16987 (when (and (not keepdate) (calendar-cursor-to-date))
16988 (let* ((date (calendar-cursor-to-date))
16989 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16990 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16991 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16993 (org-select-frame-set-input-focus sf)))
16995 (defun org-calendar-select ()
16996 "Return to `org-read-date' with the date currently selected.
16997 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16999 (when (calendar-cursor-to-date)
17000 (let* ((date (calendar-cursor-to-date))
17001 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17002 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17003 (if (active-minibuffer-window) (exit-minibuffer))))
17005 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17006 "Insert a date stamp for the date given by the internal TIME.
17007 WITH-HM means use the stamp format that includes the time of the day.
17008 INACTIVE means use square brackets instead of angular ones, so that the
17009 stamp will not contribute to the agenda.
17010 PRE and POST are optional strings to be inserted before and after the
17012 The command returns the inserted time stamp."
17013 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17015 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17016 (insert-before-markers (or pre ""))
17017 (when (listp extra)
17018 (setq extra (car extra))
17019 (if (and (stringp extra)
17020 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17021 (setq extra (format "-%02d:%02d"
17022 (string-to-number (match-string 1 extra))
17023 (string-to-number (match-string 2 extra))))
17026 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17027 (insert-before-markers (setq stamp (format-time-string fmt time)))
17028 (insert-before-markers (or post ""))
17029 (setq org-last-inserted-timestamp stamp)))
17031 (defun org-toggle-time-stamp-overlays ()
17032 "Toggle the use of custom time stamp formats."
17034 (setq org-display-custom-times (not org-display-custom-times))
17035 (unless org-display-custom-times
17036 (let ((p (point-min)) (bmp (buffer-modified-p)))
17037 (while (setq p (next-single-property-change p 'display))
17038 (if (and (get-text-property p 'display)
17039 (eq (get-text-property p 'face) 'org-date))
17040 (remove-text-properties
17041 p (setq p (next-single-property-change p 'display))
17043 (set-buffer-modified-p bmp)))
17044 (if (featurep 'xemacs)
17045 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17046 (org-restart-font-lock)
17047 (setq org-table-may-need-update t)
17048 (if org-display-custom-times
17049 (message "Time stamps are overlaid with custom format")
17050 (message "Time stamp overlays removed")))
17052 (defun org-display-custom-time (beg end)
17053 "Overlay modified time stamp format over timestamp between BEG and END."
17054 (let* ((ts (buffer-substring beg end))
17055 t1 w1 with-hm tf time str w2 (off 0))
17057 (setq t1 (org-parse-time-string ts t))
17058 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17059 (setq off (- (match-end 0) (match-beginning 0)))))
17060 (setq end (- end off))
17061 (setq w1 (- end beg)
17062 with-hm (and (nth 1 t1) (nth 2 t1))
17063 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17064 time (org-fix-decoded-time t1)
17066 (format-time-string
17067 (substring tf 1 -1) (apply 'encode-time time))
17068 nil 'mouse-face 'highlight)
17070 (if (not (= w2 w1))
17071 (add-text-properties (1+ beg) (+ 2 beg)
17072 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17073 (if (featurep 'xemacs)
17075 (put-text-property beg end 'invisible t)
17076 (put-text-property beg end 'end-glyph (make-glyph str)))
17077 (put-text-property beg end 'display str))))
17079 (defun org-translate-time (string)
17080 "Translate all timestamps in STRING to custom format.
17081 But do this only if the variable `org-display-custom-times' is set."
17082 (when org-display-custom-times
17085 (re org-ts-regexp-both)
17086 t1 with-hm inactive tf time str beg end)
17087 (while (setq start (string-match re string start))
17088 (setq beg (match-beginning 0)
17090 t1 (save-match-data
17091 (org-parse-time-string (substring string beg end) t))
17092 with-hm (and (nth 1 t1) (nth 2 t1))
17093 inactive (equal (substring string beg (1+ beg)) "[")
17094 tf (funcall (if with-hm 'cdr 'car)
17095 org-time-stamp-custom-formats)
17096 time (org-fix-decoded-time t1)
17097 str (format-time-string
17099 (if inactive "[" "<") (substring tf 1 -1)
17100 (if inactive "]" ">"))
17101 (apply 'encode-time time))
17102 string (replace-match str t t string)
17103 start (+ start (length str)))))))
17106 (defun org-fix-decoded-time (time)
17107 "Set 0 instead of nil for the first 6 elements of time.
17108 Don't touch the rest."
17110 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17112 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17114 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17115 "Difference between TIMESTAMP-STRING and now in days.
17116 If SECONDS is non-nil, return the difference in seconds."
17117 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17118 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17119 (funcall fdiff (current-time)))))
17121 (defun org-deadline-close (timestamp-string &optional ndays)
17122 "Is the time in TIMESTAMP-STRING close to the current date?"
17123 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17124 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17125 (not (org-entry-is-done-p))))
17127 (defun org-get-wdays (ts &optional delay zero-delay)
17128 "Get the deadline lead time appropriate for timestring TS.
17129 When DELAY is non-nil, get the delay time for scheduled items
17130 instead of the deadline lead time. When ZERO-DELAY is non-nil
17131 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17132 don't try to find the delay cookie in the scheduled timestamp."
17133 (let ((tv (if delay org-scheduled-delay-days
17134 org-deadline-warning-days)))
17136 ((or (and delay (< tv 0))
17137 (and delay zero-delay (<= tv 0))
17138 (and (not delay) (<= tv 0)))
17139 ;; Enforce this value no matter what
17141 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17142 ;; lead time is specified.
17143 (floor (* (string-to-number (match-string 1 ts))
17144 (cdr (assoc (match-string 2 ts)
17145 '(("d" . 1) ("w" . 7)
17146 ("m" . 30.4) ("y" . 365.25)
17147 ("h" . 0.041667)))))))
17148 ;; go for the default.
17151 (defun org-calendar-select-mouse (ev)
17152 "Return to `org-read-date' with the date currently selected.
17153 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17155 (mouse-set-point ev)
17156 (when (calendar-cursor-to-date)
17157 (let* ((date (calendar-cursor-to-date))
17158 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17159 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17160 (if (active-minibuffer-window) (exit-minibuffer))))
17162 (defun org-check-deadlines (ndays)
17163 "Check if there are any deadlines due or past due.
17164 A deadline is considered due if it happens within `org-deadline-warning-days'
17165 days from today's date. If the deadline appears in an entry marked DONE,
17166 it is not shown. The prefix arg NDAYS can be used to test that many
17167 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17169 (let* ((org-warn-days
17171 ((equal ndays '(4)) 100000)
17172 (ndays (prefix-numeric-value ndays))
17173 (t (abs org-deadline-warning-days))))
17174 (case-fold-search nil)
17175 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17177 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17179 (message "%d deadlines past-due or due within %d days"
17180 (org-occur regexp nil callback)
17183 (defsubst org-re-timestamp (type)
17184 "Return a regexp for timestamp TYPE.
17185 Allowed values for TYPE are:
17187 all: all timestamps
17188 active: only active timestamps (<...>)
17189 inactive: only inactive timestamps ([...])
17190 scheduled: only scheduled timestamps
17191 deadline: only deadline timestamps
17192 closed: only closed time-stamps
17194 When TYPE is nil, fall back on returning a regexp that matches
17195 both scheduled and deadline timestamps."
17196 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9>
\n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17197 ((eq type 'active) org-ts-regexp)
17198 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^
\n>]*?\\)\\]")
17199 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17200 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17201 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^
\n>]*?\\)\\]"))
17202 ((eq type 'scheduled-or-deadline)
17203 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17205 (defun org-check-before-date (date)
17206 "Check if there are deadlines or scheduled entries before DATE."
17207 (interactive (list (org-read-date)))
17208 (let ((case-fold-search nil)
17209 (regexp (org-re-timestamp org-ts-type))
17211 (lambda () (time-less-p
17212 (org-time-string-to-time (match-string 1))
17213 (org-time-string-to-time date)))))
17214 (message "%d entries before %s"
17215 (org-occur regexp nil callback) date)))
17217 (defun org-check-after-date (date)
17218 "Check if there are deadlines or scheduled entries after DATE."
17219 (interactive (list (org-read-date)))
17220 (let ((case-fold-search nil)
17221 (regexp (org-re-timestamp org-ts-type))
17225 (org-time-string-to-time (match-string 1))
17226 (org-time-string-to-time date))))))
17227 (message "%d entries after %s"
17228 (org-occur regexp nil callback) date)))
17230 (defun org-check-dates-range (start-date end-date)
17231 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17232 (interactive (list (org-read-date nil nil nil "Range starts")
17233 (org-read-date nil nil nil "Range end")))
17234 (let ((case-fold-search nil)
17235 (regexp (org-re-timestamp org-ts-type))
17238 (let ((match (match-string 1)))
17241 (org-time-string-to-time match)
17242 (org-time-string-to-time start-date)))
17244 (org-time-string-to-time match)
17245 (org-time-string-to-time end-date)))))))
17246 (message "%d entries between %s and %s"
17247 (org-occur regexp nil callback) start-date end-date)))
17249 (defun org-evaluate-time-range (&optional to-buffer)
17250 "Evaluate a time range by computing the difference between start and end.
17251 Normally the result is just printed in the echo area, but with prefix arg
17252 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17253 If the time range is actually in a table, the result is inserted into the
17255 For time difference computation, a year is assumed to be exactly 365
17256 days in order to avoid rounding problems."
17259 (org-clock-update-time-maybe)
17261 (unless (org-at-date-range-p t)
17262 (goto-char (point-at-bol))
17263 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17264 (if (not (org-at-date-range-p t))
17265 (user-error "Not at a time-stamp range, and none found in current line")))
17266 (let* ((ts1 (match-string 1))
17267 (ts2 (match-string 2))
17268 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17269 (match-end (match-end 0))
17270 (time1 (org-time-string-to-time ts1))
17271 (time2 (org-time-string-to-time ts2))
17272 (t1 (org-float-time time1))
17273 (t2 (org-float-time time2))
17274 (diff (abs (- t2 t1)))
17275 (negative (< (- t2 t1) 0))
17276 ;; (ys (floor (* 365 24 60 60)))
17279 (fy "%dy %dd %02d:%02d")
17281 (fd "%dd %02d:%02d")
17286 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17288 d (floor (/ diff ds)) diff (mod diff ds)
17289 h (floor (/ diff hs)) diff (mod diff hs)
17290 m (floor (/ diff 60)))
17291 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17293 d (floor (+ (/ diff ds) 0.5))
17295 (if (not to-buffer)
17296 (message "%s" (org-make-tdiff-string y d h m))
17297 (if (org-at-table-p)
17299 (goto-char match-end)
17301 (and (looking-at " *|") (goto-char (match-end 0))))
17302 (goto-char match-end))
17304 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17305 (replace-match ""))
17306 (if negative (insert " -"))
17307 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17308 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17309 (insert " " (format fh h m))))
17310 (if align (org-table-align))
17311 (message "Time difference inserted")))))
17313 (defun org-make-tdiff-string (y d h m)
17316 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17318 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17320 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17322 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17324 (apply 'format fmt (nreverse l))))
17326 (defun org-time-string-to-time (s &optional buffer pos)
17327 "Convert a timestamp string into internal time."
17328 (condition-case errdata
17329 (apply 'encode-time (org-parse-time-string s))
17330 (error (error "Bad timestamp `%s'%s\nError was: %s"
17331 s (if (not (and buffer pos))
17333 (format " at %d in buffer `%s'" pos buffer))
17336 (defun org-time-string-to-seconds (s)
17337 "Convert a timestamp string to a number of seconds."
17338 (org-float-time (org-time-string-to-time s)))
17340 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17341 "Convert a time stamp to an absolute day number.
17342 If there is a specifier for a cyclic time stamp, get the closest
17344 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17345 The variable `date' is bound by the calendar when this is called."
17347 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17348 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17351 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17352 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17353 (time-to-days (current-time))) (match-string 0 s)
17356 (condition-case errdata
17357 (apply 'encode-time (org-parse-time-string s))
17358 (error (error "Bad timestamp `%s'%s\nError was: %s"
17359 s (if (not (and buffer pos))
17361 (format " at %d in buffer `%s'" pos buffer))
17362 (cdr errdata))))))))
17364 (defun org-days-to-iso-week (days)
17365 "Return the iso week number."
17367 (car (calendar-iso-from-absolute days)))
17369 (defun org-small-year-to-year (year)
17370 "Convert 2-digit years into 4-digit years.
17371 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17372 The year 2000 cannot be abbreviated. Any year larger than 99
17373 is returned unchanged."
17375 (setq year (+ 2000 year))
17377 (setq year (+ 1900 year))))
17380 (defun org-time-from-absolute (d)
17381 "Return the time corresponding to date D.
17382 D may be an absolute day number, or a calendar-type list (month day year)."
17383 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17384 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17386 (defun org-calendar-holiday ()
17387 "List of holidays, for Diary display in Org-mode."
17388 (require 'holidays)
17390 (if (fboundp 'calendar-check-holidays)
17391 'calendar-check-holidays 'check-calendar-holidays) date)))
17392 (if hl (mapconcat 'identity hl "; "))))
17394 (defun org-diary-sexp-entry (sexp entry date)
17395 "Process a SEXP diary ENTRY for DATE."
17396 (require 'diary-lib)
17397 (let ((result (if calendar-debug-sexp
17398 (let ((stack-trace-on-error t))
17399 (eval (car (read-from-string sexp))))
17400 (condition-case nil
17401 (eval (car (read-from-string sexp)))
17404 (message "Bad sexp at line %d in %s: %s"
17406 (buffer-file-name) sexp)
17408 (cond ((stringp result) (split-string result "; "))
17409 ((and (consp result)
17410 (not (consp (cdr result)))
17411 (stringp (cdr result))) (cdr result))
17412 ((and (consp result)
17413 (stringp (car result))) result)
17416 (defun org-diary-to-ical-string (frombuf)
17417 "Get iCalendar entries from diary entries in buffer FROMBUF.
17418 This uses the icalendar.el library."
17419 (let* ((tmpdir (if (featurep 'xemacs)
17421 temporary-file-directory))
17422 (tmpfile (make-temp-name
17423 (expand-file-name "orgics" tmpdir)))
17425 (with-current-buffer frombuf
17426 (icalendar-export-region (point-min) (point-max) tmpfile)
17427 (setq buf (find-buffer-visiting tmpfile))
17429 (goto-char (point-min))
17430 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17431 (setq b (match-beginning 0)))
17432 (goto-char (point-max))
17433 (if (re-search-backward "^END:VEVENT" nil t)
17434 (setq e (match-end 0)))
17435 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17437 (delete-file tmpfile)
17440 (defun org-closest-date (start current change prefer show-all)
17441 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17442 When PREFER is `past', return a date that is either CURRENT or past.
17443 When PREFER is `future', return a date that is either CURRENT or future.
17444 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17445 ;; Make the proper lists from the dates
17447 (let ((a1 '(("h" . hour)
17452 (shour (nth 2 (org-parse-time-string start)))
17453 dn dw sday cday n1 n2 n0
17454 d m y y1 y2 date1 date2 nmonths nm ny m2)
17456 (setq start (org-date-to-gregorian start)
17457 current (org-date-to-gregorian
17460 (time-to-days (current-time))))
17461 sday (calendar-absolute-from-gregorian start)
17462 cday (calendar-absolute-from-gregorian current))
17464 (if (<= cday sday) (throw 'exit sday))
17466 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17467 (setq dn (string-to-number (match-string 1 change))
17468 dw (cdr (assoc (match-string 2 change) a1)))
17469 (user-error "Invalid change specifier: %s" change))
17470 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17473 (let ((missing-hours
17474 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17476 (setq n1 (if (zerop missing-hours) cday
17477 (- cday (1+ (floor (/ missing-hours 24)))))
17478 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17480 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17483 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17484 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17485 (setq date1 (list m d y1)
17486 n1 (calendar-absolute-from-gregorian date1)
17487 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17488 n2 (calendar-absolute-from-gregorian date2)))
17490 ;; approx number of month between the two dates
17491 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17492 ;; How often does dn fit in there?
17493 (setq d (nth 1 start) m (car start) y (nth 2 start)
17494 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17496 ny (floor (/ m 12))
17499 (while (> m 12) (setq m (- m 12) y (1+ y)))
17500 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17501 (setq m2 (+ m dn) y2 y)
17502 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17503 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17504 (while (<= n2 cday)
17505 (setq n1 n2 m m2 y y2)
17506 (setq m2 (+ m dn) y2 y)
17507 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17508 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17509 ;; Make sure n1 is the earlier date
17510 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17513 ((eq prefer 'past) (if (= cday n2) n2 n1))
17514 ((eq prefer 'future) (if (= cday n1) n1 n2))
17515 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17517 ((eq prefer 'past) (if (= cday n2) n2 n1))
17518 ((eq prefer 'future) (if (= cday n1) n1 n2))
17519 (t (if (= cday n1) n1 n2)))))))
17521 (defun org-date-to-gregorian (date)
17522 "Turn any specification of DATE into a Gregorian date for the calendar."
17523 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17524 ((and (listp date) (= (length date) 3)) date)
17526 (setq date (org-parse-time-string date))
17527 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17529 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17531 (defun org-parse-time-string (s &optional nodefault)
17532 "Parse the standard Org-mode time string.
17533 This should be a lot faster than the normal `parse-time-string'.
17534 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17535 hour and minute fields will be nil if not given."
17536 (cond ((string-match org-ts-regexp0 s)
17538 (if (or (match-beginning 8) (not nodefault))
17539 (string-to-number (or (match-string 8 s) "0")))
17540 (if (or (match-beginning 7) (not nodefault))
17541 (string-to-number (or (match-string 7 s) "0")))
17542 (string-to-number (match-string 4 s))
17543 (string-to-number (match-string 3 s))
17544 (string-to-number (match-string 2 s))
17546 ((string-match "^<[^>]+>$" s)
17547 (decode-time (seconds-to-time (org-matcher-time s))))
17548 (t (error "Not a standard Org-mode time string: %s" s))))
17550 (defun org-timestamp-up (&optional arg)
17551 "Increase the date item at the cursor by one.
17552 If the cursor is on the year, change the year. If it is on the month,
17553 the day or the time, change that.
17554 With prefix ARG, change by that many units."
17556 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17558 (defun org-timestamp-down (&optional arg)
17559 "Decrease the date item at the cursor by one.
17560 If the cursor is on the year, change the year. If it is on the month,
17561 the day or the time, change that.
17562 With prefix ARG, change by that many units."
17564 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17566 (defun org-timestamp-up-day (&optional arg)
17567 "Increase the date in the time stamp by one day.
17568 With prefix ARG, change that many days."
17570 (if (and (not (org-at-timestamp-p t))
17571 (org-at-heading-p))
17573 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17575 (defun org-timestamp-down-day (&optional arg)
17576 "Decrease the date in the time stamp by one day.
17577 With prefix ARG, change that many days."
17579 (if (and (not (org-at-timestamp-p t))
17580 (org-at-heading-p))
17582 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17584 (defun org-at-timestamp-p (&optional inactive-ok)
17585 "Determine if the cursor is in or at a timestamp."
17587 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17589 (ans (or (looking-at tsr)
17591 (skip-chars-backward "^[<\n\r\t")
17592 (if (> (point) (point-min)) (backward-char 1))
17593 (and (looking-at tsr)
17594 (> (- (match-end 0) pos) -1))))))
17596 (boundp 'org-ts-what)
17599 ((= pos (match-beginning 0)) 'bracket)
17600 ;; Point is considered to be "on the bracket" whether
17601 ;; it's really on it or right after it.
17602 ((= pos (1- (match-end 0))) 'bracket)
17603 ((= pos (match-end 0)) 'after)
17604 ((org-pos-in-match-range pos 2) 'year)
17605 ((org-pos-in-match-range pos 3) 'month)
17606 ((org-pos-in-match-range pos 7) 'hour)
17607 ((org-pos-in-match-range pos 8) 'minute)
17608 ((or (org-pos-in-match-range pos 4)
17609 (org-pos-in-match-range pos 5)) 'day)
17610 ((and (> pos (or (match-end 8) (match-end 5)))
17611 (< pos (match-end 0)))
17612 (- pos (or (match-end 8) (match-end 5))))
17616 (defun org-toggle-timestamp-type ()
17617 "Toggle the type (<active> or [inactive]) of a time stamp."
17619 (when (org-at-timestamp-p t)
17620 (let ((beg (match-beginning 0)) (end (match-end 0))
17621 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17624 (while (re-search-forward "[][<>]" end t)
17625 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17627 (message "Timestamp is now %sactive"
17628 (if (equal (char-after beg) ?<) "" "in")))))
17630 (defun org-at-clock-log-p nil
17631 "Is the cursor on the clock log line?"
17633 (move-beginning-of-line 1)
17634 (looking-at org-clock-line-re)))
17636 (defvar org-clock-history) ; defined in org-clock.el
17637 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17638 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17639 "Change the date in the time stamp at point.
17640 The date will be changed by N times WHAT. WHAT can be `day', `month',
17641 `year', `minute', `second'. If WHAT is not given, the cursor position
17642 in the timestamp determines what will be changed.
17643 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17644 (let ((origin (point)) origin-cat
17646 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17649 ts time time0 fixnext clrgx)
17650 (if (not (org-at-timestamp-p t))
17651 (user-error "Not at a timestamp"))
17652 (if (and (not what) (eq org-ts-what 'bracket))
17653 (org-toggle-timestamp-type)
17654 ;; Point isn't on brackets. Remember the part of the time-stamp
17655 ;; the point was in. Indeed, size of time-stamps may change,
17656 ;; but point must be kept in the same category nonetheless.
17657 (setq origin-cat org-ts-what)
17658 (if (and (not what) (not (eq org-ts-what 'day))
17659 org-display-custom-times
17660 (get-text-property (point) 'display)
17661 (not (get-text-property (1- (point)) 'display)))
17662 (setq org-ts-what 'day))
17663 (setq org-ts-what (or what org-ts-what)
17664 inactive (= (char-after (match-beginning 0)) ?\[)
17665 ts (match-string 0))
17667 (when (string-match
17668 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17670 (setq extra (match-string 1 ts))
17671 (if suppress-tmp-delay
17672 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17673 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17675 (setq time0 (org-parse-time-string ts))
17677 (eq org-ts-what 'minute)
17678 (not current-prefix-arg))
17679 ;; This looks like s-up and s-down. Change by one rounding step.
17680 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17681 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17682 (setcar (cdr time0) (+ (nth 1 time0)
17683 (if (> n 0) (- rem) (- dm rem))))))
17685 (encode-time (or (car time0) 0)
17686 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17687 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17688 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17689 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17690 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17692 (when (and (member org-ts-what '(hour minute))
17694 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17695 (setq extra (org-modify-ts-extra
17697 (if (eq org-ts-what 'hour) 2 5)
17699 (when (integerp org-ts-what)
17700 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17701 (if (eq what 'calendar)
17702 (let ((cal-date (org-get-date-from-calendar)))
17703 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17704 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17705 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17706 (setcar time0 (or (car time0) 0))
17707 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17708 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17709 (setq time (apply 'encode-time time0))))
17710 ;; Insert the new time-stamp, and ensure point stays in the same
17711 ;; category as before (i.e. not after the last position in that
17713 (let ((pos (point)))
17714 ;; Stay before inserted string. `save-excursion' is of no use.
17715 (setq org-last-changed-timestamp
17716 (org-insert-time-stamp time with-hm inactive nil nil extra))
17719 (looking-at org-ts-regexp3)
17721 ;; `day' category ends before `hour' if any, or at
17722 ;; the end of the day name.
17723 ((eq origin-cat 'day)
17724 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17725 ((eq origin-cat 'hour) (min (match-end 7) origin))
17726 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17727 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17728 ;; `year' and `month' have both fixed size: point
17729 ;; couldn't have moved into another part.
17731 ;; Update clock if on a CLOCK line.
17732 (org-clock-update-time-maybe)
17733 ;; Maybe adjust the closest clock in `org-clock-history'
17734 (when org-clock-adjust-closest
17735 (if (not (and (org-at-clock-log-p)
17736 (< 1 (length (delq nil (mapcar 'marker-position
17737 org-clock-history))))))
17738 (message "No clock to adjust")
17739 (cond ((save-excursion ; fix previous clock?
17740 (re-search-backward org-ts-regexp0 nil t)
17741 (org-looking-back (concat org-clock-string " \\[")))
17742 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17743 ((save-excursion ; fix next clock?
17744 (re-search-backward org-ts-regexp0 nil t)
17745 (looking-at (concat org-ts-regexp0 "\\] =>")))
17746 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17747 (save-window-excursion
17748 ;; Find closest clock to point, adjust the previous/next one in history
17749 (let* ((p (save-excursion (org-back-to-heading t)))
17750 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17752 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17753 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17755 (message "No clock to adjust")
17757 (org-goto-marker-or-bmk clfixpos)
17759 (when (re-search-forward clrgx nil t)
17760 (goto-char (match-beginning 1))
17761 (let (org-clock-adjust-closest)
17762 (org-timestamp-change n org-ts-what updown))
17763 (message "Clock adjusted in %s for heading: %s"
17764 (file-name-nondirectory (buffer-file-name))
17765 (org-get-heading t t)))))))))
17766 ;; Try to recenter the calendar window, if any.
17767 (if (and org-calendar-follow-timestamp-change
17768 (get-buffer-window "*Calendar*" t)
17769 (memq org-ts-what '(day month year)))
17770 (org-recenter-calendar (time-to-days time))))))
17772 (defun org-modify-ts-extra (s pos n dm)
17773 "Change the different parts of the lead-time and repeat fields in timestamp."
17774 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17776 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17778 ((or (org-pos-in-match-range pos 2)
17779 (org-pos-in-match-range pos 3))
17780 (setq m (string-to-number (match-string 3 s))
17781 h (string-to-number (match-string 2 s)))
17782 (if (org-pos-in-match-range pos 2)
17784 (setq n (* dm (org-no-warnings (signum n))))
17785 (when (not (= 0 (setq rem (% m dm))))
17786 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17788 (if (< m 0) (setq m (+ m 60) h (1- h)))
17789 (if (> m 59) (setq m (- m 60) h (1+ h)))
17790 (setq h (min 24 (max 0 h)))
17791 (setq ng 1 new (format "-%02d:%02d" h m)))
17792 ((org-pos-in-match-range pos 6)
17793 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17794 ((org-pos-in-match-range pos 5)
17795 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17797 ((org-pos-in-match-range pos 9)
17798 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17799 ((org-pos-in-match-range pos 8)
17800 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17804 (substring s 0 (match-beginning ng))
17806 (substring s (match-end ng))))))
17809 (defun org-recenter-calendar (date)
17810 "If the calendar is visible, recenter it to DATE."
17811 (let ((cwin (get-buffer-window "*Calendar*" t)))
17813 (let ((calendar-move-hook nil))
17814 (with-selected-window cwin
17815 (calendar-goto-date (if (listp date) date
17816 (calendar-gregorian-from-absolute date))))))))
17818 (defun org-goto-calendar (&optional arg)
17819 "Go to the Emacs calendar at the current date.
17820 If there is a time stamp in the current line, go to that date.
17821 A prefix ARG can be used to force the current date."
17823 (let ((tsr org-ts-regexp) diff
17824 (calendar-move-hook nil)
17825 (calendar-view-holidays-initially-flag nil)
17826 (calendar-view-diary-initially-flag nil))
17827 (if (or (org-at-timestamp-p)
17829 (beginning-of-line 1)
17830 (looking-at (concat ".*" tsr))))
17831 (let ((d1 (time-to-days (current-time)))
17833 (org-time-string-to-time (match-string 1)))))
17834 (setq diff (- d2 d1))))
17836 (calendar-goto-today)
17837 (if (and diff (not arg)) (calendar-forward-day diff))))
17839 (defun org-get-date-from-calendar ()
17840 "Return a list (month day year) of date at point in calendar."
17841 (with-current-buffer "*Calendar*"
17843 (calendar-cursor-to-date))))
17845 (defun org-date-from-calendar ()
17846 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17847 If there is already a time stamp at the cursor position, update it."
17849 (if (org-at-timestamp-p t)
17850 (org-timestamp-change 0 'calendar)
17851 (let ((cal-date (org-get-date-from-calendar)))
17852 (org-insert-time-stamp
17853 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17855 (defcustom org-effort-durations
17858 ("w" . ,(* 60 8 5))
17859 ("m" . ,(* 60 8 5 4))
17860 ("y" . ,(* 60 8 5 40)))
17861 "Conversion factor to minutes for an effort modifier.
17863 Each entry has the form (MODIFIER . MINUTES).
17865 In an effort string, a number followed by MODIFIER is multiplied
17866 by the specified number of MINUTES to obtain an effort in
17869 For example, if the value of this variable is ((\"hours\" . 60)), then an
17870 effort string \"2hours\" is equivalent to 120 minutes."
17873 :type '(alist :key-type (string :tag "Modifier")
17874 :value-type (number :tag "Minutes")))
17876 (defun org-minutes-to-clocksum-string (m)
17877 "Format number of minutes as a clocksum string.
17878 The format is determined by `org-time-clocksum-format',
17879 `org-time-clocksum-use-fractional' and
17880 `org-time-clocksum-fractional-format' and
17881 `org-time-clocksum-use-effort-durations'."
17882 (let ((clocksum "")
17883 (m (round m)) ; Don't allow fractions of minutes
17885 (setq h (if org-time-clocksum-use-effort-durations
17886 (cdr (assoc "h" org-effort-durations)) 60)
17887 d (if org-time-clocksum-use-effort-durations
17888 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17889 w (if org-time-clocksum-use-effort-durations
17890 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17891 mo (if org-time-clocksum-use-effort-durations
17892 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17893 y (if org-time-clocksum-use-effort-durations
17894 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17895 ;; fractional format
17896 (if org-time-clocksum-use-fractional
17898 ;; single format string
17899 ((stringp org-time-clocksum-fractional-format)
17900 (format org-time-clocksum-fractional-format (/ m (float h))))
17901 ;; choice of fractional formats for different time units
17902 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17903 (> (/ (truncate m) (* y d h)) 0))
17904 (format fmt (/ m (* y d (float h)))))
17905 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17906 (> (/ (truncate m) (* mo d h)) 0))
17907 (format fmt (/ m (* mo d (float h)))))
17908 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17909 (> (/ (truncate m) (* w d h)) 0))
17910 (format fmt (/ m (* w d (float h)))))
17911 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17912 (> (/ (truncate m) (* d h)) 0))
17913 (format fmt (/ m (* d (float h)))))
17914 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17915 (> (/ (truncate m) h) 0))
17916 (format fmt (/ m (float h))))
17917 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17919 ;; fall back to smallest time unit with a format
17920 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17921 (format fmt (/ m (float h))))
17922 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17923 (format fmt (/ m (* d (float h)))))
17924 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17925 (format fmt (/ m (* w d (float h)))))
17926 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17927 (format fmt (/ m (* mo d (float h)))))
17928 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17929 (format fmt (/ m (* y d (float h))))))
17930 ;; standard (non-fractional) format, with single format string
17931 (if (stringp org-time-clocksum-format)
17932 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17933 ;; separate formats components
17934 (and (setq fmt (plist-get org-time-clocksum-format :years))
17935 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17936 (plist-get org-time-clocksum-format :require-years))
17937 (setq clocksum (concat clocksum (format fmt n))
17938 m (- m (* n y d h))))
17939 (and (setq fmt (plist-get org-time-clocksum-format :months))
17940 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17941 (plist-get org-time-clocksum-format :require-months))
17942 (setq clocksum (concat clocksum (format fmt n))
17943 m (- m (* n mo d h))))
17944 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17945 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17946 (plist-get org-time-clocksum-format :require-weeks))
17947 (setq clocksum (concat clocksum (format fmt n))
17948 m (- m (* n w d h))))
17949 (and (setq fmt (plist-get org-time-clocksum-format :days))
17950 (or (> (setq n (/ (truncate m) (* d h))) 0)
17951 (plist-get org-time-clocksum-format :require-days))
17952 (setq clocksum (concat clocksum (format fmt n))
17953 m (- m (* n d h))))
17954 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17955 (or (> (setq n (/ (truncate m) h)) 0)
17956 (plist-get org-time-clocksum-format :require-hours))
17957 (setq clocksum (concat clocksum (format fmt n))
17959 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17960 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17961 (setq clocksum (concat clocksum (format fmt m))))
17962 ;; return formatted time duration
17965 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17966 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17967 "Org mode version 8.0")
17969 (defun org-hours-to-clocksum-string (n)
17970 (org-minutes-to-clocksum-string (* n 60)))
17972 (defun org-hh:mm-string-to-minutes (s)
17973 "Convert a string H:MM to a number of minutes.
17974 If the string is just a number, interpret it as minutes.
17975 In fact, the first hh:mm or number in the string will be taken,
17976 there can be extra stuff in the string.
17977 If no number is found, the return value is 0."
17980 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17981 (+ (* (string-to-number (match-string 1 s)) 60)
17982 (string-to-number (match-string 2 s))))
17983 ((string-match "\\([0-9]+\\)" s)
17984 (string-to-number (match-string 1 s)))
17987 (defcustom org-image-actual-width t
17988 "Should we use the actual width of images when inlining them?
17990 When set to `t', always use the image width.
17992 When set to a number, use imagemagick (when available) to set
17993 the image's width to this value.
17995 When set to a number in a list, try to get the width from any
17996 #+ATTR.* keyword if it matches a width specification like
17998 #+ATTR_HTML: :width 300px
18000 and fall back on that number if none is found.
18002 When set to nil, try to get the width from an #+ATTR.* keyword
18003 and fall back on the original width if none is found.
18005 This requires Emacs >= 24.1, build with imagemagick support."
18006 :group 'org-appearance
18008 :package-version '(Org . "8.0")
18010 (const :tag "Use the image width" t)
18011 (integer :tag "Use a number of pixels")
18012 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18013 (const :tag "Use #+ATTR* or don't resize" nil)))
18015 (defcustom org-agenda-inhibit-startup nil
18016 "Inhibit startup when preparing agenda buffers.
18017 When this variable is `t', the initialization of the Org agenda
18018 buffers is inhibited: e.g. the visibility state is not set, the
18019 tables are not re-aligned, etc."
18022 :group 'org-agenda)
18024 (define-obsolete-variable-alias
18025 'org-agenda-ignore-drawer-properties
18026 'org-agenda-ignore-properties "25.1")
18028 (defcustom org-agenda-ignore-properties nil
18029 "Avoid updating text properties when building the agenda.
18030 Properties are used to prepare buffers for effort estimates,
18031 appointments, statistics and subtree-local categories.
18032 If you don't use these in the agenda, you can add them to this
18033 list and agenda building will be a bit faster.
18034 The value is a list, with zero or more of the symbols `effort', `appt',
18035 `stats' or `category'."
18036 :type '(set :greedy t
18042 :package-version '(Org . "8.3")
18043 :group 'org-agenda)
18045 (defun org-duration-string-to-minutes (s &optional output-to-string)
18046 "Convert a duration string S to minutes.
18048 A bare number is interpreted as minutes, modifiers can be set by
18049 customizing `org-effort-durations' (which see).
18051 Entries containing a colon are interpreted as H:MM by
18052 `org-hh:mm-string-to-minutes'."
18054 (re (concat "\\([0-9.]+\\) *\\("
18055 (regexp-opt (mapcar 'car org-effort-durations))
18057 (while (string-match re s)
18058 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18059 (string-to-number (match-string 1 s))))
18060 (setq s (replace-match "" nil t s)))
18061 (setq result (floor result))
18062 (incf result (org-hh:mm-string-to-minutes s))
18063 (if output-to-string (number-to-string result) result)))
18067 (defun org-save-all-org-buffers ()
18068 "Save all Org-mode buffers without user confirmation."
18070 (message "Saving all Org-mode buffers...")
18071 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18072 (when (featurep 'org-id) (org-id-locations-save))
18073 (message "Saving all Org-mode buffers... done"))
18075 (defun org-revert-all-org-buffers ()
18076 "Revert all Org-mode buffers.
18077 Prompt for confirmation when there are unsaved changes.
18078 Be sure you know what you are doing before letting this function
18079 overwrite your changes.
18081 This function is useful in a setup where one tracks org files
18082 with a version control system, to revert on one machine after pulling
18083 changes from another. I believe the procedure must be like this:
18085 1. M-x org-save-all-org-buffers
18086 2. Pull changes from the other machine, resolve conflicts
18087 3. M-x org-revert-all-org-buffers"
18089 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18090 (user-error "Abort"))
18092 (save-window-excursion
18095 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18096 (with-current-buffer b buffer-file-name))
18097 (org-pop-to-buffer-same-window b)
18098 (revert-buffer t 'no-confirm)))
18100 (when (and (featurep 'org-id) org-id-track-globally)
18101 (org-id-locations-load)))))
18106 (defun org-switchb (&optional arg)
18107 "Switch between Org buffers.
18108 With one prefix argument, restrict available buffers to files.
18109 With two prefix arguments, restrict available buffers to agenda files.
18111 Defaults to `iswitchb' for buffer name completion.
18112 Set `org-completion-use-ido' to make it use ido instead."
18114 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18115 ((equal arg '(16)) (org-buffer-list 'agenda))
18116 (t (org-buffer-list))))
18117 (org-completion-use-iswitchb org-completion-use-iswitchb)
18118 (org-completion-use-ido org-completion-use-ido))
18119 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18120 (setq org-completion-use-iswitchb t))
18121 (org-pop-to-buffer-same-window
18122 (org-icompleting-read "Org buffer: "
18123 (mapcar 'list (mapcar 'buffer-name blist))
18126 ;;; Define some older names previously used for this functionality
18128 (defalias 'org-ido-switchb 'org-switchb)
18130 (defalias 'org-iswitchb 'org-switchb)
18132 (defun org-buffer-list (&optional predicate exclude-tmp)
18133 "Return a list of Org buffers.
18134 PREDICATE can be `export', `files' or `agenda'.
18136 export restrict the list to Export buffers.
18137 files restrict the list to buffers visiting Org files.
18138 agenda restrict the list to buffers visiting agenda files.
18140 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18142 (agenda-files (and (eq predicate 'agenda)
18143 (mapcar 'file-truename (org-agenda-files t))))
18146 ((eq predicate 'files)
18147 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18148 ((eq predicate 'export)
18149 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18150 ((eq predicate 'agenda)
18152 (with-current-buffer b
18153 (and (derived-mode-p 'org-mode)
18154 (setq bfn (buffer-file-name b))
18155 (member (file-truename bfn) agenda-files)))))
18156 (t (lambda (b) (with-current-buffer b
18157 (or (derived-mode-p 'org-mode)
18158 (string-match "\*Org .*Export"
18159 (buffer-name b)))))))))
18163 (if (and (funcall filter b)
18164 (or (not exclude-tmp)
18165 (not (string-match "tmp" (buffer-name b)))))
18170 (defun org-agenda-files (&optional unrestricted archives)
18171 "Get the list of agenda files.
18172 Optional UNRESTRICTED means return the full list even if a restriction
18173 is currently in place.
18174 When ARCHIVES is t, include all archive files that are really being
18175 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18176 `org-agenda-archives-mode' is t."
18179 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18180 ((stringp org-agenda-files) (org-read-agenda-file-list))
18181 ((listp org-agenda-files) org-agenda-files)
18182 (t (error "Invalid value of `org-agenda-files'")))))
18183 (setq files (apply 'append
18184 (mapcar (lambda (f)
18185 (if (file-directory-p f)
18187 f t org-agenda-file-regexp)
18190 (when org-agenda-skip-unavailable-files
18191 (setq files (delq nil
18194 (and (file-readable-p file) file)))
18196 (when (or (eq archives t)
18197 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18198 (setq files (org-add-archive-files files)))
18201 (defun org-agenda-file-p (&optional file)
18202 "Return non-nil, if FILE is an agenda file.
18203 If FILE is omitted, use the file associated with the current
18205 (let ((fname (or file (buffer-file-name))))
18207 (member (file-truename fname)
18208 (mapcar #'file-truename (org-agenda-files t))))))
18210 (defun org-edit-agenda-file-list ()
18211 "Edit the list of agenda files.
18212 Depending on setup, this either uses customize to edit the variable
18213 `org-agenda-files', or it visits the file that is holding the list. In the
18214 latter case, the buffer is set up in a way that saving it automatically kills
18215 the buffer and restores the previous window configuration."
18217 (if (stringp org-agenda-files)
18218 (let ((cw (current-window-configuration)))
18219 (find-file org-agenda-files)
18220 (org-set-local 'org-window-configuration cw)
18221 (org-add-hook 'after-save-hook
18223 (set-window-configuration
18224 (prog1 org-window-configuration
18225 (kill-buffer (current-buffer))))
18226 (org-install-agenda-files-menu)
18227 (message "New agenda file list installed"))
18229 (message "%s" (substitute-command-keys
18230 "Edit list and finish with \\[save-buffer]")))
18231 (customize-variable 'org-agenda-files)))
18233 (defun org-store-new-agenda-file-list (list)
18234 "Set new value for the agenda file list and save it correctly."
18235 (if (stringp org-agenda-files)
18236 (let ((fe (org-read-agenda-file-list t)) b u)
18237 (while (setq b (find-buffer-visiting org-agenda-files))
18239 (with-temp-file org-agenda-files
18242 (lambda (f) ;; Keep un-expanded entries.
18243 (if (setq u (assoc f fe))
18248 (let ((org-mode-hook nil) (org-inhibit-startup t)
18249 (org-insert-mode-line-in-empty-file nil))
18250 (setq org-agenda-files list)
18251 (customize-save-variable 'org-agenda-files org-agenda-files))))
18253 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18254 "Read the list of agenda files from a file.
18255 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18256 filenames, used by `org-store-new-agenda-file-list' to write back
18257 un-expanded file names."
18258 (when (file-directory-p org-agenda-files)
18259 (error "`org-agenda-files' cannot be a single directory"))
18260 (when (stringp org-agenda-files)
18262 (insert-file-contents org-agenda-files)
18265 (let ((e (expand-file-name (substitute-in-file-name f)
18267 (if pair-with-expansion
18270 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18273 (defun org-cycle-agenda-files ()
18274 "Cycle through the files in `org-agenda-files'.
18275 If the current buffer visits an agenda file, find the next one in the list.
18276 If the current buffer does not, find the first agenda file."
18278 (let* ((fs (org-agenda-files t))
18279 (files (append fs (list (car fs))))
18280 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18282 (unless files (user-error "No agenda files"))
18284 (while (setq file (pop files))
18285 (if (equal (file-truename file) tcf)
18287 (find-file (car files))
18289 (find-file (car fs)))
18290 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18292 (defun org-agenda-file-to-front (&optional to-end)
18293 "Move/add the current file to the top of the agenda file list.
18294 If the file is not present in the list, it is added to the front. If it is
18295 present, it is moved there. With optional argument TO-END, add/move to the
18298 (let ((org-agenda-skip-unavailable-files nil)
18299 (file-alist (mapcar (lambda (x)
18300 (cons (file-truename x) x))
18301 (org-agenda-files t)))
18302 (ctf (file-truename
18303 (or buffer-file-name
18304 (user-error "Please save the current buffer to a file"))))
18306 (setq x (assoc ctf file-alist) had x)
18308 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18310 (setq file-alist (append (delq x file-alist) (list x)))
18311 (setq file-alist (cons x (delq x file-alist))))
18312 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18313 (org-install-agenda-files-menu)
18314 (message "File %s to %s of agenda file list"
18315 (if had "moved" "added") (if to-end "end" "front"))))
18317 (defun org-remove-file (&optional file)
18318 "Remove current file from the list of files in variable `org-agenda-files'.
18319 These are the files which are being checked for agenda entries.
18320 Optional argument FILE means use this file instead of the current."
18322 (let* ((org-agenda-skip-unavailable-files nil)
18323 (file (or file buffer-file-name
18324 (user-error "Current buffer does not visit a file")))
18325 (true-file (file-truename file))
18326 (afile (abbreviate-file-name file))
18327 (files (delq nil (mapcar
18329 (if (equal true-file
18332 (org-agenda-files t)))))
18333 (if (not (= (length files) (length (org-agenda-files t))))
18335 (org-store-new-agenda-file-list files)
18336 (org-install-agenda-files-menu)
18337 (message "Removed file: %s" afile))
18338 (message "File was not in list: %s (not removed)" afile))))
18340 (defun org-file-menu-entry (file)
18341 (vector file (list 'find-file file) t))
18343 (defun org-check-agenda-file (file)
18344 "Make sure FILE exists. If not, ask user what to do."
18345 (when (not (file-exists-p file))
18346 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18347 (abbreviate-file-name file))
18348 (let ((r (downcase (read-char-exclusive))))
18351 (org-remove-file file)
18352 (throw 'nextfile t))
18353 (t (user-error "Abort"))))))
18355 (defun org-get-agenda-file-buffer (file)
18356 "Get an agenda buffer visiting FILE.
18357 If the buffer needs to be created, add it to the list of buffers
18358 which might be released later."
18359 (let ((buf (org-find-base-buffer-visiting file)))
18361 buf ; just return it
18362 ;; Make a new buffer and remember it
18363 (setq buf (find-file-noselect file))
18364 (if buf (push buf org-agenda-new-buffers))
18367 (defun org-release-buffers (blist)
18368 "Release all buffers in list, asking the user for confirmation when needed.
18369 When a buffer is unmodified, it is just killed. When modified, it is saved
18370 \(if the user agrees) and then killed."
18372 (while (setq buf (pop blist))
18373 (setq file (buffer-file-name buf))
18374 (when (and (buffer-modified-p buf)
18376 (y-or-n-p (format "Save file %s? " file)))
18377 (with-current-buffer buf (save-buffer)))
18378 (kill-buffer buf))))
18380 (defun org-agenda-prepare-buffers (files)
18381 "Create buffers for all agenda files, protect archived trees and comments."
18383 (let ((pa '(:org-archived t))
18384 (pc '(:org-comment t))
18385 (pall '(:org-archived t :org-comment t))
18386 (inhibit-read-only t)
18387 (org-inhibit-startup org-agenda-inhibit-startup)
18388 (rea (concat ":" org-archive-tag ":"))
18390 (setq org-tag-alist-for-agenda nil
18391 org-tag-groups-alist-for-agenda nil)
18394 (while (setq file (pop files))
18398 (org-check-agenda-file file)
18399 (set-buffer (org-get-agenda-file-buffer file)))
18401 (org-set-regexps-and-options 'tags-only)
18403 (or (memq 'category org-agenda-ignore-properties)
18404 (org-refresh-category-properties))
18405 (or (memq 'stats org-agenda-ignore-properties)
18406 (org-refresh-stats-properties))
18407 (or (memq 'effort org-agenda-ignore-properties)
18408 (org-refresh-effort-properties))
18409 (or (memq 'appt org-agenda-ignore-properties)
18410 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18411 (setq org-todo-keywords-for-agenda
18412 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18413 (setq org-done-keywords-for-agenda
18414 (append org-done-keywords-for-agenda org-done-keywords))
18415 (setq org-todo-keyword-alist-for-agenda
18416 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18417 (setq org-tag-alist-for-agenda
18419 (append org-tag-alist-for-agenda
18421 org-tag-persistent-alist)))
18423 (setq org-tag-groups-alist-for-agenda
18424 (org-uniquify-alist
18425 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18426 (org-with-silent-modifications
18428 (remove-text-properties (point-min) (point-max) pall)
18429 (when org-agenda-skip-archived-trees
18430 (goto-char (point-min))
18431 (while (re-search-forward rea nil t)
18432 (if (org-at-heading-p t)
18433 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18434 (goto-char (point-min))
18435 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18436 (while (re-search-forward re nil t)
18437 (when (save-match-data (org-in-commented-heading-p t))
18438 (add-text-properties
18439 (match-beginning 0) (org-end-of-subtree t) pc)))))
18440 (goto-char pos)))))
18441 (setq org-todo-keywords-for-agenda
18442 (org-uniquify org-todo-keywords-for-agenda))
18443 (setq org-todo-keyword-alist-for-agenda
18444 (org-uniquify org-todo-keyword-alist-for-agenda))))
18447 ;;;; CDLaTeX minor mode
18449 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18450 "Keymap for the minor `org-cdlatex-mode'.")
18452 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18453 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18454 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18455 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18456 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18458 (defvar org-cdlatex-texmathp-advice-is-done nil
18459 "Flag remembering if we have applied the advice to texmathp already.")
18461 (define-minor-mode org-cdlatex-mode
18462 "Toggle the minor `org-cdlatex-mode'.
18463 This mode supports entering LaTeX environment and math in LaTeX fragments
18465 \\{org-cdlatex-mode-map}"
18467 (when org-cdlatex-mode
18469 (run-hooks 'cdlatex-mode-hook)
18470 (cdlatex-compute-tables))
18471 (unless org-cdlatex-texmathp-advice-is-done
18472 (setq org-cdlatex-texmathp-advice-is-done t)
18473 (defadvice texmathp (around org-math-always-on activate)
18474 "Always return t in org-mode buffers.
18475 This is because we want to insert math symbols without dollars even outside
18476 the LaTeX math segments. If Orgmode thinks that point is actually inside
18477 an embedded LaTeX fragment, let texmathp do its job.
18478 \\[org-cdlatex-mode-map]"
18482 ((not (derived-mode-p 'org-mode)) ad-do-it)
18483 ((eq this-command 'cdlatex-math-symbol)
18484 (setq ad-return-value t
18485 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18487 (let ((p (org-inside-LaTeX-fragment-p)))
18488 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18489 (setq ad-return-value t
18490 texmathp-why '("Org-mode embedded math" . 0))
18491 (if p ad-do-it)))))))))
18493 (defun turn-on-org-cdlatex ()
18494 "Unconditionally turn on `org-cdlatex-mode'."
18495 (org-cdlatex-mode 1))
18497 (defun org-try-cdlatex-tab ()
18498 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18499 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18500 - inside a LaTeX fragment, or
18501 - after the first word in a line, where an abbreviation expansion could
18502 insert a LaTeX environment."
18503 (when org-cdlatex-mode
18505 ;; Before any word on the line: No expansion possible.
18506 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18507 ;; Just after first word on the line: Expand it. Make sure it
18508 ;; cannot happen on headlines, though.
18510 (skip-chars-backward "a-zA-Z0-9*")
18511 (skip-chars-backward " \t")
18512 (and (bolp) (not (org-at-heading-p))))
18514 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18516 (defun org-cdlatex-underscore-caret (&optional arg)
18517 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18518 Revert to the normal definition outside of these fragments."
18520 (if (org-inside-LaTeX-fragment-p)
18521 (call-interactively 'cdlatex-sub-superscript)
18522 (let (org-cdlatex-mode)
18523 (call-interactively (key-binding (vector last-input-event))))))
18525 (defun org-cdlatex-math-modify (&optional arg)
18526 "Execute `cdlatex-math-modify' in LaTeX fragments.
18527 Revert to the normal definition outside of these fragments."
18529 (if (org-inside-LaTeX-fragment-p)
18530 (call-interactively 'cdlatex-math-modify)
18531 (let (org-cdlatex-mode)
18532 (call-interactively (key-binding (vector last-input-event))))))
18534 (defun org-cdlatex-environment-indent (&optional environment item)
18535 "Execute `cdlatex-environment' and indent the inserted environment."
18537 (cdlatex-environment environment item)
18538 (let ((element (org-element-at-point)))
18539 (org-indent-region (org-element-property :begin element)
18540 (org-element-property :end element))))
18543 ;;;; LaTeX fragments
18545 (defun org-inside-LaTeX-fragment-p ()
18546 "Test if point is inside a LaTeX fragment.
18547 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18548 sequence appearing also before point.
18549 Even though the matchers for math are configurable, this function assumes
18550 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18551 delimiters are skipped when they have been removed by customization.
18552 The return value is nil, or a cons cell with the delimiter and the
18553 position of this delimiter.
18555 This function does a reasonably good job, but can locally be fooled by
18556 for example currency specifications. For example it will assume being in
18557 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18558 fragments that are properly closed, but during editing, we have to live
18559 with the uncertainty caused by missing closing delimiters. This function
18560 looks only before point, not after."
18562 (let ((pos (point))
18563 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18565 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18567 dd-on str (start 0) m re)
18570 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18571 re (nth 1 (assoc "$" org-latex-regexps)))
18572 (while (string-match re str start)
18574 ((= (match-end 0) (length str))
18575 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18576 ((= (match-end 0) (- (length str) 5))
18578 (t (setq start (match-end 0))))))
18579 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18581 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18582 (and (match-beginning 2) (throw 'exit nil))
18584 (while (re-search-backward "\\$\\$" lim t)
18585 (setq dd-on (not dd-on)))
18587 (if dd-on (cons "$$" m))))))
18589 (defun org-inside-latex-macro-p ()
18590 "Is point inside a LaTeX macro or its arguments?"
18593 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18595 (defvar org-latex-fragment-image-overlays nil
18596 "List of overlays carrying the images of latex fragments.")
18597 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18599 (defun org-remove-latex-fragment-image-overlays ()
18600 "Remove all overlays with LaTeX fragment images in current buffer."
18601 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18602 (setq org-latex-fragment-image-overlays nil))
18604 (define-obsolete-function-alias
18605 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18606 (defun org-toggle-latex-fragment (&optional subtree)
18607 "Preview the LaTeX fragment at point, or all locally or globally.
18608 If the cursor is in a LaTeX fragment, create the image and overlay
18609 it over the source code. If there is no fragment at point, display
18610 all fragments in the current text, from one headline to the next. With
18611 prefix SUBTREE, display all fragments in the current subtree. With a
18612 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18613 the cursor is before the first headline,
18614 display all fragments in the buffer.
18615 The images can be removed again with \\[org-toggle-latex-fragment]."
18617 (unless buffer-file-name
18618 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18619 (if org-latex-fragment-image-overlays
18620 (progn (org-remove-latex-fragment-image-overlays)
18621 (message "LaTeX fragments images removed"))
18622 (when (display-graphic-p)
18623 (org-remove-latex-fragment-image-overlays)
18626 (let (beg end at msg)
18628 ((or (equal subtree '(16))
18629 (not (save-excursion
18630 (re-search-backward org-outline-regexp-bol nil t))))
18631 (setq beg (point-min) end (point-max)
18632 msg "Creating images for buffer...%s"))
18633 ((equal subtree '(4))
18634 (org-back-to-heading)
18635 (setq beg (point) end (org-end-of-subtree t)
18636 msg "Creating images for subtree...%s"))
18638 (if (setq at (org-inside-LaTeX-fragment-p))
18639 (goto-char (max (point-min) (- (cdr at) 2)))
18640 (org-back-to-heading))
18641 (setq beg (point) end (progn (outline-next-heading) (point))
18642 msg (if at "Creating image...%s"
18643 "Creating images for entry...%s"))))
18645 (narrow-to-region beg end)
18648 (concat org-latex-preview-ltxpng-directory
18649 (file-name-sans-extension
18650 (file-name-nondirectory buffer-file-name)))
18651 default-directory 'overlays msg at 'forbuffer
18652 org-latex-create-formula-image-program)
18653 (message msg "done. Use `C-c C-x C-l' to remove images.")))))))
18655 (defun org-format-latex (prefix &optional dir overlays msg at
18656 forbuffer processing-type)
18657 "Replace LaTeX fragments with links to an image, and produce images.
18658 Some of the options can be changed using the variable
18659 `org-format-latex-options'."
18660 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18661 (let* ((prefixnodir (file-name-nondirectory prefix))
18662 (absprefix (expand-file-name prefix dir))
18663 (todir (file-name-directory absprefix))
18664 (opt org-format-latex-options)
18665 (optnew org-format-latex-options)
18666 (matchers (plist-get opt :matchers))
18667 (re-list org-latex-regexps)
18668 (cnt 0) txt hash link beg end re e checkdir
18670 m n block-type block linkfile movefile ov)
18671 ;; Check the different regular expressions
18672 (while (setq e (pop re-list))
18673 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18674 block (if block-type "\n\n" ""))
18675 (when (member m matchers)
18676 (goto-char (point-min))
18677 (while (re-search-forward re nil t)
18678 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18680 (not (eq (get-char-property (match-beginning n)
18682 'org-latex-overlay))))
18684 ((eq processing-type 'verbatim))
18685 ((eq processing-type 'mathjax)
18686 ;; Prepare for MathJax processing.
18687 (setq string (match-string n))
18688 (when (member m '("$" "$1"))
18690 (delete-region (match-beginning n) (match-end n))
18691 (goto-char (match-beginning n))
18692 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18693 ((or (eq processing-type 'dvipng)
18694 (eq processing-type 'imagemagick))
18695 ;; Process to an image.
18696 (setq txt (match-string n)
18697 beg (match-beginning n) end (match-end n)
18699 (let ((face (face-at-point))
18700 (fg (plist-get opt :foreground))
18701 (bg (plist-get opt :background))
18702 ;; Ensure full list is printed.
18703 print-length print-level)
18705 ;; Get the colors from the face at point.
18707 (when (eq fg 'auto)
18708 (setq fg (face-attribute face :foreground nil 'default)))
18709 (when (eq bg 'auto)
18710 (setq bg (face-attribute face :background nil 'default)))
18711 (setq optnew (copy-sequence opt))
18712 (plist-put optnew :foreground fg)
18713 (plist-put optnew :background bg))
18714 (setq hash (sha1 (prin1-to-string
18715 (list org-format-latex-header
18716 org-latex-default-packages-alist
18717 org-latex-packages-alist
18718 org-format-latex-options
18719 forbuffer txt fg bg)))
18720 linkfile (format "%s_%s.png" prefix hash)
18721 movefile (format "%s_%s.png" absprefix hash)))
18722 (setq link (concat block "[[file:" linkfile "]]" block))
18723 (if msg (message msg cnt))
18725 (unless checkdir ; Ensure the directory exists.
18727 (or (file-directory-p todir) (make-directory todir t)))
18728 (unless (file-exists-p movefile)
18729 (org-create-formula-image
18730 txt movefile optnew forbuffer processing-type))
18734 (if (eq (overlay-get o 'org-overlay-type)
18735 'org-latex-overlay)
18736 (delete-overlay o)))
18737 (overlays-in beg end))
18738 (setq ov (make-overlay beg end))
18739 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18740 (if (featurep 'xemacs)
18742 (overlay-put ov 'invisible t)
18745 (make-glyph (vector 'png :file movefile))))
18748 (list 'image :type 'png :file movefile :ascent 'center)))
18749 (push ov org-latex-fragment-image-overlays)
18751 (delete-region beg end)
18752 (insert (org-add-props link
18753 (list 'org-latex-src
18754 (replace-regexp-in-string
18756 'org-latex-src-embed-type
18757 (if block-type 'paragraph 'character))))))
18758 ((eq processing-type 'mathml)
18759 ;; Process to MathML
18760 (unless (save-match-data (org-format-latex-mathml-available-p))
18761 (user-error "LaTeX to MathML converter not configured"))
18762 (setq txt (match-string n)
18763 beg (match-beginning n) end (match-end n)
18765 (if msg (message msg cnt))
18767 (delete-region beg end)
18768 (insert (org-format-latex-as-mathml
18769 txt block-type prefix dir)))
18771 (error "Unknown conversion type %s for LaTeX fragments"
18772 processing-type)))))))))
18774 (defun org-create-math-formula (latex-frag &optional mathml-file)
18775 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18776 Use `org-latex-to-mathml-convert-command'. If the conversion is
18777 sucessful, return the portion between \"<math...> </math>\"
18778 elements otherwise return nil. When MATHML-FILE is specified,
18779 write the results in to that file. When invoked as an
18780 interactive command, prompt for LATEX-FRAG, with initial value
18781 set to the current active region and echo the results for user
18783 (interactive (list (let ((frag (when (org-region-active-p)
18784 (buffer-substring-no-properties
18785 (region-beginning) (region-end)))))
18786 (read-string "LaTeX Fragment: " frag nil frag))))
18787 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18788 (let* ((tmp-in-file (file-relative-name
18789 (make-temp-name (expand-file-name "ltxmathml-in"))))
18790 (ignore (write-region latex-frag nil tmp-in-file))
18791 (tmp-out-file (file-relative-name
18792 (make-temp-name (expand-file-name "ltxmathml-out"))))
18794 org-latex-to-mathml-convert-command
18795 `((?j . ,(shell-quote-argument
18796 (expand-file-name org-latex-to-mathml-jar-file)))
18797 (?I . ,(shell-quote-argument tmp-in-file))
18798 (?o . ,(shell-quote-argument tmp-out-file)))))
18799 mathml shell-command-output)
18800 (when (org-called-interactively-p 'any)
18801 (unless (org-format-latex-mathml-available-p)
18802 (user-error "LaTeX to MathML converter not configured")))
18803 (message "Running %s" cmd)
18804 (setq shell-command-output (shell-command-to-string cmd))
18806 (when (file-readable-p tmp-out-file)
18807 (with-current-buffer (find-file-noselect tmp-out-file t)
18808 (goto-char (point-min))
18809 (when (re-search-forward
18812 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18814 (regexp-quote "</math>")) nil t)
18815 (prog1 (match-string 0) (kill-buffer))))))
18819 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18821 (write-region mathml nil mathml-file))
18822 (when (org-called-interactively-p 'any)
18824 ((message "LaTeX to MathML conversion failed")
18825 (message shell-command-output)))
18826 (delete-file tmp-in-file)
18827 (when (file-exists-p tmp-out-file)
18828 (delete-file tmp-out-file))
18831 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18832 prefix &optional dir)
18833 "Use `org-create-math-formula' but check local cache first."
18834 (let* ((absprefix (expand-file-name prefix dir))
18835 (print-length nil) (print-level nil)
18836 (formula-id (concat
18841 org-latex-to-mathml-convert-command)))))
18842 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18843 (formula-cache-dir (file-name-directory formula-cache)))
18845 (unless (file-directory-p formula-cache-dir)
18846 (make-directory formula-cache-dir t))
18848 (unless (file-exists-p formula-cache)
18849 (org-create-math-formula latex-frag formula-cache))
18851 (if (file-exists-p formula-cache)
18852 ;; Successful conversion. Return the link to MathML file.
18854 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18855 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18856 'org-latex-src-embed-type (if latex-frag-type
18857 'paragraph 'character)))
18858 ;; Failed conversion. Return the LaTeX fragment verbatim
18861 (defun org-create-formula-image (string tofile options buffer &optional type)
18862 "Create an image from LaTeX source using dvipng or convert.
18863 This function calls either `org-create-formula-image-with-dvipng'
18864 or `org-create-formula-image-with-imagemagick' depending on the
18865 value of `org-latex-create-formula-image-program' or on the value
18866 of the optional TYPE variable.
18868 Note: ultimately these two function should be combined as they
18869 share a good deal of logic."
18870 (org-check-external-command
18871 "latex" "needed to convert LaTeX fragments to images")
18873 (case (or type org-latex-create-formula-image-program)
18875 (org-check-external-command
18876 "dvipng" "needed to convert LaTeX fragments to images")
18877 'org-create-formula-image-with-dvipng)
18879 (org-check-external-command
18880 "convert" "you need to install imagemagick")
18881 'org-create-formula-image-with-imagemagick)
18883 "Invalid value of `org-latex-create-formula-image-program'")))
18884 string tofile options buffer))
18886 (declare-function org-export-get-backend "ox" (name))
18887 (declare-function org-export--get-global-options "ox" (&optional backend))
18888 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18889 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18890 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18891 (defun org-create-formula--latex-header ()
18892 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18893 (let ((info (org-combine-plists (org-export--get-global-options
18894 (org-export-get-backend 'latex))
18895 (org-export--get-inbuffer-options
18896 (org-export-get-backend 'latex)))))
18897 (org-latex-guess-babel-language
18898 (org-latex-guess-inputenc
18899 (org-splice-latex-header
18900 org-format-latex-header
18901 org-latex-default-packages-alist
18902 org-latex-packages-alist t
18903 (plist-get info :latex-header)))
18906 ;; This function borrows from Ganesh Swami's latex2png.el
18907 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18908 "This calls dvipng."
18909 (require 'ox-latex)
18910 (let* ((tmpdir (if (featurep 'xemacs)
18912 temporary-file-directory))
18913 (texfilebase (make-temp-name
18914 (expand-file-name "orgtex" tmpdir)))
18915 (texfile (concat texfilebase ".tex"))
18916 (dvifile (concat texfilebase ".dvi"))
18917 (pngfile (concat texfilebase ".png"))
18918 (fnh (if (featurep 'xemacs)
18919 (font-height (face-font 'default))
18920 (face-attribute 'default :height nil)))
18921 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18922 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18923 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18925 (bg (or (plist-get options (if buffer :background :html-background))
18927 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18928 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18929 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18930 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18931 (let ((latex-header (org-create-formula--latex-header)))
18932 (with-temp-file texfile
18933 (insert latex-header)
18934 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18935 (let ((dir default-directory))
18938 (call-process "latex" nil nil nil texfile))
18940 (if (not (file-exists-p dvifile))
18941 (progn (message "Failed to create dvi file from %s" texfile) nil)
18943 (if (featurep 'xemacs)
18944 (call-process "dvipng" nil nil nil
18949 (call-process "dvipng" nil nil nil
18952 ;;"-x" scale "-y" scale
18956 (if (not (file-exists-p pngfile))
18957 (if org-format-latex-signal-error
18958 (error "Failed to create png file from %s" texfile)
18959 (message "Failed to create png file from %s" texfile)
18961 ;; Use the requested file name and clean up
18962 (copy-file pngfile tofile 'replace)
18963 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18964 (if (file-exists-p (concat texfilebase e))
18965 (delete-file (concat texfilebase e))))
18968 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18969 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18970 "This calls convert, which is included into imagemagick."
18971 (require 'ox-latex)
18972 (let* ((tmpdir (if (featurep 'xemacs)
18974 temporary-file-directory))
18975 (texfilebase (make-temp-name
18976 (expand-file-name "orgtex" tmpdir)))
18977 (texfile (concat texfilebase ".tex"))
18978 (pdffile (concat texfilebase ".pdf"))
18979 (pngfile (concat texfilebase ".png"))
18980 (fnh (if (featurep 'xemacs)
18981 (font-height (face-font 'default))
18982 (face-attribute 'default :height nil)))
18983 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18984 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18985 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18987 (bg (or (plist-get options (if buffer :background :html-background))
18989 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18990 (setq fg (org-latex-color-format fg)))
18991 (if (eq bg 'default) (setq bg (org-latex-color :background))
18992 (setq bg (org-latex-color-format
18993 (if (string= bg "Transparent") "white" bg))))
18994 (let ((latex-header (org-create-formula--latex-header)))
18995 (with-temp-file texfile
18996 (insert latex-header)
18997 (insert "\n\\begin{document}\n"
18998 "\\definecolor{fg}{rgb}{" fg "}\n"
18999 "\\definecolor{bg}{rgb}{" bg "}\n"
19000 "\n\\pagecolor{bg}\n"
19004 "\n\\end{document}\n")))
19005 (org-latex-compile texfile t)
19006 (if (not (file-exists-p pdffile))
19007 (progn (message "Failed to create pdf file from %s" texfile) nil)
19009 (if (featurep 'xemacs)
19010 (call-process "convert" nil nil nil
19016 ;; "-sharpen" "0x1.0"
19018 (call-process "convert" nil nil nil
19024 ;; "-sharpen" "0x1.0"
19026 (if (not (file-exists-p pngfile))
19027 (if org-format-latex-signal-error
19028 (error "Failed to create png file from %s" texfile)
19029 (message "Failed to create png file from %s" texfile)
19031 ;; Use the requested file name and clean up
19032 (copy-file pngfile tofile 'replace)
19033 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19034 (if (file-exists-p (concat texfilebase e))
19035 (delete-file (concat texfilebase e))))
19038 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19039 "Fill a LaTeX header template TPL.
19040 In the template, the following place holders will be recognized:
19042 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19043 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19044 [PACKAGES] \\usepackage statements for PKG
19045 [NO-PACKAGES] do not include PKG
19046 [EXTRA] the string EXTRA
19047 [NO-EXTRA] do not include EXTRA
19049 For backward compatibility, if both the positive and the negative place
19050 holder is missing, the positive one (without the \"NO-\") will be
19051 assumed to be present at the end of the template.
19052 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19054 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19055 (let (rpl (end ""))
19056 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19057 (setq rpl (if (or (match-end 1) (not def-pkg))
19058 "" (org-latex-packages-to-string def-pkg snippets-p t))
19059 tpl (replace-match rpl t t tpl))
19060 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19062 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19063 (setq rpl (if (or (match-end 1) (not pkg))
19064 "" (org-latex-packages-to-string pkg snippets-p t))
19065 tpl (replace-match rpl t t tpl))
19068 (org-latex-packages-to-string pkg snippets-p)))))
19070 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19071 (setq rpl (if (or (match-end 1) (not extra))
19072 "" (concat extra "\n"))
19073 tpl (replace-match rpl t t tpl))
19074 (if (and extra (string-match "\\S-" extra))
19075 (setq end (concat end "\n" extra))))
19077 (if (string-match "\\S-" end)
19078 (concat tpl "\n" end)
19081 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19082 "Turn an alist of packages into a string with the \\usepackage macros."
19083 (setq pkg (mapconcat (lambda(p)
19086 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19087 (format "%% Package %s omitted" (cadr p)))
19088 ((equal "" (car p))
19089 (format "\\usepackage{%s}" (cadr p)))
19091 (format "\\usepackage[%s]{%s}"
19092 (car p) (cadr p)))))
19095 (if newline (concat pkg "\n") pkg))
19097 (defun org-dvipng-color (attr)
19098 "Return a RGB color specification for dvipng."
19099 (apply 'format "rgb %s %s %s"
19100 (mapcar 'org-normalize-color
19101 (if (featurep 'xemacs)
19102 (color-rgb-components
19103 (face-property 'default
19104 (cond ((eq attr :foreground) 'foreground)
19105 ((eq attr :background) 'background))))
19106 (color-values (face-attribute 'default attr nil))))))
19108 (defun org-dvipng-color-format (color-name)
19109 "Convert COLOR-NAME to a RGB color value for dvipng."
19110 (apply 'format "rgb %s %s %s"
19111 (mapcar 'org-normalize-color
19112 (color-values color-name))))
19114 (defun org-latex-color (attr)
19115 "Return a RGB color for the LaTeX color package."
19116 (apply 'format "%s,%s,%s"
19117 (mapcar 'org-normalize-color
19118 (if (featurep 'xemacs)
19119 (color-rgb-components
19120 (face-property 'default
19121 (cond ((eq attr :foreground) 'foreground)
19122 ((eq attr :background) 'background))))
19123 (color-values (face-attribute 'default attr nil))))))
19125 (defun org-latex-color-format (color-name)
19126 "Convert COLOR-NAME to a RGB color value."
19127 (apply 'format "%s,%s,%s"
19128 (mapcar 'org-normalize-color
19129 (color-values color-name))))
19131 (defun org-normalize-color (value)
19132 "Return string to be used as color value for an RGB component."
19133 (format "%g" (/ value 65535.0)))
19139 (defvar org-inline-image-overlays nil)
19140 (make-variable-buffer-local 'org-inline-image-overlays)
19142 (defun org-toggle-inline-images (&optional include-linked)
19143 "Toggle the display of inline images.
19144 INCLUDE-LINKED is passed to `org-display-inline-images'."
19146 (if org-inline-image-overlays
19148 (org-remove-inline-images)
19149 (message "Inline image display turned off"))
19150 (org-display-inline-images include-linked)
19151 (if (and (org-called-interactively-p)
19152 org-inline-image-overlays)
19153 (message "%d images displayed inline"
19154 (length org-inline-image-overlays))
19155 (message "No images to display inline"))))
19157 (defun org-redisplay-inline-images ()
19158 "Refresh the display of inline images."
19160 (if (not org-inline-image-overlays)
19161 (org-toggle-inline-images)
19162 (org-toggle-inline-images)
19163 (org-toggle-inline-images)))
19165 (defun org-display-inline-images (&optional include-linked refresh beg end)
19166 "Display inline images.
19168 An inline image is a link which follows either of these
19171 1. Its path is a file with an extension matching return value
19172 from `image-file-name-regexp' and it has no contents.
19174 2. Its description consists in a single link of the previous
19177 When optional argument INCLUDE-LINKED is non-nil, also links with
19178 a text description part will be inlined. This can be nice for
19179 a quick look at those images, but it does not reflect what
19180 exported files will look like.
19182 When optional argument REFRESH is non-nil, refresh existing
19183 images between BEG and END. This will create new image displays
19184 only if necessary. BEG and END default to the buffer
19187 (when (display-graphic-p)
19189 (org-remove-inline-images)
19190 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19191 (org-with-wide-buffer
19192 (goto-char (or beg (point-min)))
19193 (let ((case-fold-search t)
19194 (file-extension-re (org-image-file-name-regexp)))
19195 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19196 (let ((link (save-match-data (org-element-context))))
19197 ;; Check if we're at an inline image.
19198 (when (and (equal (org-element-property :type link) "file")
19200 (not (org-element-property :contents-begin link)))
19201 (let ((parent (org-element-property :parent link)))
19202 (or (not (eq (org-element-type parent) 'link))
19203 (not (cdr (org-element-contents parent)))))
19204 (org-string-match-p file-extension-re
19205 (org-element-property :path link)))
19206 (let ((file (expand-file-name (org-element-property :path link))))
19207 (when (file-exists-p file)
19209 ;; Apply `org-image-actual-width' specifications.
19211 ((not (image-type-available-p 'imagemagick)) nil)
19212 ((eq org-image-actual-width t) nil)
19213 ((listp org-image-actual-width)
19215 ;; First try to find a width among
19216 ;; attributes associated to the paragraph
19217 ;; containing link.
19220 (while (and (setq e (org-element-property
19222 (not (eq (org-element-type e)
19227 (goto-char (org-element-property :begin paragraph))
19230 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19231 (org-element-property
19232 :post-affiliated paragraph)
19234 (string-to-number (match-string 1))))))
19235 ;; Otherwise, fall-back to provided number.
19236 (car org-image-actual-width)))
19237 ((numberp org-image-actual-width)
19238 org-image-actual-width)))
19239 (old (get-char-property-and-overlay
19240 (org-element-property :begin link)
19241 'org-image-overlay)))
19242 (if (and (car-safe old) refresh)
19243 (image-refresh (overlay-get (cdr old) 'display))
19244 (let ((image (create-image file
19245 (and width 'imagemagick)
19250 ;; If inline image is the description
19251 ;; of another link, be sure to
19252 ;; consider the latter as the one to
19253 ;; apply the overlay on.
19255 (org-element-property :parent link)))
19256 (if (eq (org-element-type parent) 'link)
19260 (org-element-property :begin link)
19263 (org-element-property :end link))
19264 (skip-chars-backward " \t")
19266 (overlay-put ov 'display image)
19267 (overlay-put ov 'face 'default)
19268 (overlay-put ov 'org-image-overlay t)
19270 ov 'modification-hooks
19271 (list 'org-display-inline-remove-overlay))
19272 (push ov org-inline-image-overlays)))))))))))))))
19274 (define-obsolete-function-alias
19275 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19277 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19278 "Remove inline-display overlay if a corresponding region is modified."
19279 (let ((inhibit-modification-hooks t))
19280 (when (and ov after)
19281 (delete ov org-inline-image-overlays)
19282 (delete-overlay ov))))
19284 (defun org-remove-inline-images ()
19285 "Remove inline display of images."
19287 (mapc 'delete-overlay org-inline-image-overlays)
19288 (setq org-inline-image-overlays nil))
19292 ;; Outline functions from `outline-mode-prefix-map'
19293 ;; that can be remapped in Org:
19294 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19295 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19296 (define-key org-mode-map [remap outline-forward-same-level]
19297 'org-forward-heading-same-level)
19298 (define-key org-mode-map [remap outline-backward-same-level]
19299 'org-backward-heading-same-level)
19300 (define-key org-mode-map [remap show-branches]
19301 'org-kill-note-or-show-branches)
19302 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19303 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19304 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19306 ;; Outline functions from `outline-mode-prefix-map' that can not
19307 ;; be remapped in Org:
19309 ;; - the column "key binding" shows whether the Outline function is still
19310 ;; available in Org mode on the same key that it has been bound to in
19312 ;; - "overridden": key used for a different functionality in Org mode
19313 ;; - else: key still bound to the same Outline function in Org mode
19315 ;; | Outline function | key binding | Org replacement |
19316 ;; |------------------------------------+-------------+-----------------------|
19317 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19318 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19319 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19320 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19321 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19322 ;; | `show-entry' | overridden | no replacement |
19323 ;; | `show-children' | `C-c C-i' | visibility cycling |
19324 ;; | `show-branches' | `C-c C-k' | still same function |
19325 ;; | `show-subtree' | overridden | visibility cycling |
19326 ;; | `show-all' | overridden | no replacement |
19327 ;; | `hide-subtree' | overridden | visibility cycling |
19328 ;; | `hide-body' | overridden | no replacement |
19329 ;; | `hide-entry' | overridden | visibility cycling |
19330 ;; | `hide-leaves' | overridden | no replacement |
19331 ;; | `hide-sublevels' | overridden | no replacement |
19332 ;; | `hide-other' | overridden | no replacement |
19334 ;; Make `C-c C-x' a prefix key
19335 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19337 ;; TAB key with modifiers
19338 (org-defkey org-mode-map "\C-i" 'org-cycle)
19339 (org-defkey org-mode-map [(tab)] 'org-cycle)
19340 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19341 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19342 ;; The following line is necessary under Suse GNU/Linux
19343 (unless (featurep 'xemacs)
19344 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19345 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19346 (define-key org-mode-map [backtab] 'org-shifttab)
19348 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19349 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19350 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19352 ;; Cursor keys with modifiers
19353 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19354 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19355 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19356 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19358 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19359 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19360 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19361 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19362 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19363 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19365 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19366 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19367 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19368 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19370 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19371 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19372 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19373 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19376 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19377 (mapc (lambda (pair)
19378 (define-key org-babel-map (car pair) (cdr pair)))
19379 org-babel-key-bindings)
19381 ;;; Extra keys for tty access.
19382 ;; We only set them when really needed because otherwise the
19383 ;; menus don't show the simple keys
19385 (when (or org-use-extra-keys
19386 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19387 (not window-system))
19388 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19389 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19390 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19391 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19392 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19393 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19394 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19395 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19396 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19397 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19398 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19399 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19400 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19401 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19402 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19403 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19404 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19405 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19406 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19407 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19408 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19409 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19410 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19411 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19412 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19413 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19414 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19415 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19417 ;; All the other keys
19419 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19420 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19421 (if (boundp 'narrow-map)
19422 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19423 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19424 (if (boundp 'narrow-map)
19425 (org-defkey narrow-map "b" 'org-narrow-to-block)
19426 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19427 (if (boundp 'narrow-map)
19428 (org-defkey narrow-map "e" 'org-narrow-to-element)
19429 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19430 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19431 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19432 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19433 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19434 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19435 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19436 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19437 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19438 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19439 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19440 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19441 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19442 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19443 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19444 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19445 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19446 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19447 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19448 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19449 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19450 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19451 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19452 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19453 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19454 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19455 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19456 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19457 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19458 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19459 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19460 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19461 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19462 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19463 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19464 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19465 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19466 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19467 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19468 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19469 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19470 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19471 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19472 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19473 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19474 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19475 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19476 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19477 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19478 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19479 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19480 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19481 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19482 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19483 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19484 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19485 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19486 (org-defkey org-mode-map "\C-c^" 'org-sort)
19487 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19488 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19489 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19490 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19491 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19492 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19493 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19494 (org-defkey org-mode-map "\C-m" 'org-return)
19495 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19496 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19497 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19498 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19499 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19500 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19501 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19502 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19503 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19504 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19505 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19506 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19507 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19508 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19509 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19510 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19511 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19512 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19513 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19514 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19515 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19516 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19517 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19518 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19519 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19521 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19522 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19523 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19525 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19526 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19527 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19528 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19529 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19530 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19531 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19532 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19533 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19534 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19535 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19536 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19537 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19538 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19539 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19540 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19541 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19542 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19543 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19544 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19545 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19546 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19547 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19549 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19550 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19551 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19552 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19553 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19555 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19557 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19559 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19560 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19562 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19565 (when (featurep 'xemacs)
19566 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19569 (defconst org-speed-commands-default
19571 ("Outline Navigation")
19572 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19573 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19574 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19575 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19576 ("F" . org-next-block)
19577 ("B" . org-previous-block)
19578 ("u" . (org-speed-move-safe 'outline-up-heading))
19580 ("g" . (org-refile t))
19581 ("Outline Visibility")
19583 ("C" . org-shifttab)
19584 (" " . org-display-outline-path)
19585 ("s" . org-narrow-to-subtree)
19586 ("=" . org-columns)
19587 ("Outline Structure Editing")
19589 ("D" . org-metadown)
19590 ("r" . org-metaright)
19591 ("l" . org-metaleft)
19592 ("R" . org-shiftmetaright)
19593 ("L" . org-shiftmetaleft)
19594 ("i" . (progn (forward-char 1) (call-interactively
19595 'org-insert-heading-respect-content)))
19598 ("a" . org-archive-subtree-default-with-confirmation)
19599 ("@" . org-mark-subtree)
19600 ("#" . org-toggle-comment)
19602 ("I" . org-clock-in)
19603 ("O" . org-clock-out)
19604 ("Meta Data Editing")
19606 ("," . (org-priority))
19607 ("0" . (org-priority ?\ ))
19608 ("1" . (org-priority ?A))
19609 ("2" . (org-priority ?B))
19610 ("3" . (org-priority ?C))
19611 (":" . org-set-tags-command)
19612 ("e" . org-set-effort)
19613 ("E" . org-inc-effort)
19614 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19615 (org-entry-put (point) "APPT_WARNTIME" m)))
19616 ("Agenda Views etc")
19618 ("/" . org-sparse-tree)
19620 ("o" . org-open-at-point)
19621 ("?" . org-speed-command-help)
19622 ("<" . (org-agenda-set-restriction-lock 'subtree))
19623 (">" . (org-agenda-remove-restriction-lock))
19625 "The default speed commands.")
19627 (defun org-print-speed-command (e)
19628 (if (> (length (car e)) 1)
19633 (princ (make-string (length (car e)) ?-))
19637 (if (symbolp (cdr e))
19638 (princ (symbol-name (cdr e)))
19642 (defun org-speed-command-help ()
19643 "Show the available speed commands."
19645 (if (not org-use-speed-commands)
19646 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19647 (with-output-to-temp-buffer "*Help*"
19648 (princ "User-defined Speed commands\n===========================\n")
19649 (mapc 'org-print-speed-command org-speed-commands-user)
19651 (princ "Built-in Speed commands\n=======================\n")
19652 (mapc 'org-print-speed-command org-speed-commands-default))
19653 (with-current-buffer "*Help*"
19654 (setq truncate-lines t))))
19656 (defun org-speed-move-safe (cmd)
19657 "Execute CMD, but make sure that the cursor always ends up in a headline.
19658 If not, return to the original position and throw an error."
19660 (let ((pos (point)))
19661 (call-interactively cmd)
19662 (unless (and (bolp) (org-at-heading-p))
19664 (error "Boundary reached while executing %s" cmd))))
19666 (defvar org-self-insert-command-undo-counter 0)
19668 (defvar org-table-auto-blank-field) ; defined in org-table.el
19669 (defvar org-speed-command nil)
19671 (define-obsolete-function-alias
19672 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19674 (defun org-speed-command-activate (keys)
19675 "Hook for activating single-letter speed commands.
19676 `org-speed-commands-default' specifies a minimal command set.
19677 Use `org-speed-commands-user' for further customization."
19678 (when (or (and (bolp) (looking-at org-outline-regexp))
19679 (and (functionp org-use-speed-commands)
19680 (funcall org-use-speed-commands)))
19681 (cdr (assoc keys (append org-speed-commands-user
19682 org-speed-commands-default)))))
19684 (define-obsolete-function-alias
19685 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19687 (defun org-babel-speed-command-activate (keys)
19688 "Hook for activating single-letter code block commands."
19689 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19690 (cdr (assoc keys org-babel-key-bindings))))
19692 (defcustom org-speed-command-hook
19693 '(org-speed-command-default-hook org-babel-speed-command-hook)
19694 "Hook for activating speed commands at strategic locations.
19695 Hook functions are called in sequence until a valid handler is
19698 Each hook takes a single argument, a user-pressed command key
19699 which is also a `self-insert-command' from the global map.
19701 Within the hook, examine the cursor position and the command key
19702 and return nil or a valid handler as appropriate. Handler could
19703 be one of an interactive command, a function, or a form.
19705 Set `org-use-speed-commands' to non-nil value to enable this
19706 hook. The default setting is `org-speed-command-activate'."
19707 :group 'org-structure
19711 (defun org-self-insert-command (N)
19712 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19713 If the cursor is in a table looking at whitespace, the whitespace is
19714 overwritten, and the table is not marked as requiring realignment."
19716 (org-check-before-invisible-edit 'insert)
19718 ((and org-use-speed-commands
19719 (let ((kv (this-command-keys-vector)))
19720 (setq org-speed-command
19721 (run-hook-with-args-until-success
19722 'org-speed-command-hook
19723 (make-string 1 (aref kv (1- (length kv))))))))
19725 ((commandp org-speed-command)
19726 (setq this-command org-speed-command)
19727 (call-interactively org-speed-command))
19728 ((functionp org-speed-command)
19729 (funcall org-speed-command))
19730 ((and org-speed-command (listp org-speed-command))
19731 (eval org-speed-command))
19732 (t (let (org-use-speed-commands)
19733 (call-interactively 'org-self-insert-command)))))
19737 ;; check if we blank the field, and if that triggers align
19738 (and (featurep 'org-table) org-table-auto-blank-field
19739 (member last-command
19740 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas-expand))
19741 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19742 ;; got extra space, this field does not determine column width
19743 (let (org-table-may-need-update) (org-table-blank-field))
19744 ;; no extra space, this field may determine column width
19745 (org-table-blank-field)))
19748 (looking-at "[^|\n]* |"))
19749 (let (org-table-may-need-update)
19750 (goto-char (1- (match-end 0)))
19751 (backward-delete-char 1)
19752 (goto-char (match-beginning 0))
19753 (self-insert-command N)))
19755 (setq org-table-may-need-update t)
19756 (self-insert-command N)
19757 (org-fix-tags-on-the-fly)
19758 (if org-self-insert-cluster-for-undo
19759 (if (not (eq last-command 'org-self-insert-command))
19760 (setq org-self-insert-command-undo-counter 1)
19761 (if (>= org-self-insert-command-undo-counter 20)
19762 (setq org-self-insert-command-undo-counter 1)
19763 (and (> org-self-insert-command-undo-counter 0)
19764 buffer-undo-list (listp buffer-undo-list)
19765 (not (cadr buffer-undo-list)) ; remove nil entry
19766 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19767 (setq org-self-insert-command-undo-counter
19768 (1+ org-self-insert-command-undo-counter))))))))
19770 (defun org-check-before-invisible-edit (kind)
19771 "Check is editing if kind KIND would be dangerous with invisible text around.
19772 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19773 ;; First, try to get out of here as quickly as possible, to reduce overhead
19774 (if (and org-catch-invisible-edits
19775 (or (not (boundp 'visible-mode)) (not visible-mode))
19776 (or (get-char-property (point) 'invisible)
19777 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19778 ;; OK, we need to take a closer look
19779 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19780 (invisible-before-point (if (bobp) nil (get-char-property
19781 (1- (point)) 'invisible)))
19782 (border-and-ok-direction
19784 ;; Check if we are acting predictably before invisible text
19785 (and invisible-at-point (not invisible-before-point)
19786 (memq kind '(insert delete-backward)))
19787 ;; Check if we are acting predictably after invisible text
19788 ;; This works not well, and I have turned it off. It seems
19789 ;; better to always show and stop after invisible text.
19790 ;; (and (not invisible-at-point) invisible-before-point
19791 ;; (memq kind '(insert delete)))
19793 (when (or (memq invisible-at-point '(outline org-hide-block t))
19794 (memq invisible-before-point '(outline org-hide-block t)))
19795 (if (eq org-catch-invisible-edits 'error)
19796 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19797 (if (and org-custom-properties-overlays
19798 (y-or-n-p "Display invisible properties in this buffer? "))
19799 (org-toggle-custom-properties-visibility)
19800 ;; Make the area visible
19802 (if invisible-before-point
19803 (goto-char (previous-single-char-property-change
19804 (point) 'invisible)))
19807 ((eq org-catch-invisible-edits 'show)
19808 ;; That's it, we do the edit after showing
19810 "Unfolding invisible region around point before editing")
19812 ((and (eq org-catch-invisible-edits 'smart)
19813 border-and-ok-direction)
19814 (message "Unfolding invisible region around point before editing"))
19816 ;; Don't do the edit, make the user repeat it in full visibility
19817 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19819 (defun org-fix-tags-on-the-fly ()
19820 (when (and (equal (char-after (point-at-bol)) ?*)
19821 (org-at-heading-p))
19822 (org-align-tags-here org-tags-column)))
19824 (defun org-delete-backward-char (N)
19825 "Like `delete-backward-char', insert whitespace at field end in tables.
19826 When deleting backwards, in tables this function will insert whitespace in
19827 front of the next \"|\" separator, to keep the table aligned. The table will
19828 still be marked for re-alignment if the field did fill the entire column,
19829 because, in this case the deletion might narrow the column."
19832 (org-check-before-invisible-edit 'delete-backward)
19833 (if (and (org-table-p)
19835 (string-match "|" (buffer-substring (point-at-bol) (point)))
19836 (looking-at ".*?|"))
19837 (let ((pos (point))
19838 (noalign (looking-at "[^|\n\r]* |"))
19839 (c org-table-may-need-update))
19840 (backward-delete-char N)
19841 (if (not overwrite-mode)
19843 (skip-chars-forward "^|")
19845 (goto-char (1- pos))))
19846 ;; noalign: if there were two spaces at the end, this field
19847 ;; does not determine the width of the column.
19848 (if noalign (setq org-table-may-need-update c)))
19849 (backward-delete-char N)
19850 (org-fix-tags-on-the-fly))))
19852 (defun org-delete-char (N)
19853 "Like `delete-char', but insert whitespace at field end in tables.
19854 When deleting characters, in tables this function will insert whitespace in
19855 front of the next \"|\" separator, to keep the table aligned. The table will
19856 still be marked for re-alignment if the field did fill the entire column,
19857 because, in this case the deletion might narrow the column."
19860 (org-check-before-invisible-edit 'delete)
19861 (if (and (org-table-p)
19863 (not (= (char-after) ?|))
19865 (if (looking-at ".*?|")
19866 (let ((pos (point))
19867 (noalign (looking-at "[^|\n\r]* |"))
19868 (c org-table-may-need-update))
19870 (concat (substring (match-string 0) 1 -1) " |") nil t)
19872 ;; noalign: if there were two spaces at the end, this field
19873 ;; does not determine the width of the column.
19874 (if noalign (setq org-table-may-need-update c)))
19877 (org-fix-tags-on-the-fly))))
19879 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19880 (put 'org-self-insert-command 'delete-selection
19882 (not (run-hook-with-args-until-success
19883 'self-insert-uses-region-functions))))
19884 (put 'orgtbl-self-insert-command 'delete-selection
19886 (not (run-hook-with-args-until-success
19887 'self-insert-uses-region-functions))))
19888 (put 'org-delete-char 'delete-selection 'supersede)
19889 (put 'org-delete-backward-char 'delete-selection 'supersede)
19890 (put 'org-yank 'delete-selection 'yank)
19892 ;; Make `flyspell-mode' delay after some commands
19893 (put 'org-self-insert-command 'flyspell-delayed t)
19894 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19895 (put 'org-delete-char 'flyspell-delayed t)
19896 (put 'org-delete-backward-char 'flyspell-delayed t)
19898 ;; Make pabbrev-mode expand after org-mode commands
19899 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19900 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19902 (defun org-remap (map &rest commands)
19903 "In MAP, remap the functions given in COMMANDS.
19904 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19907 (setq old (pop commands) new (pop commands))
19908 (if (fboundp 'command-remapping)
19909 (org-defkey map (vector 'remap old) new)
19910 (substitute-key-definition old new map global-map)))))
19912 (defun org-transpose-words ()
19913 "Transpose words for Org.
19914 This uses the `org-mode-transpose-word-syntax-table' syntax
19915 table, which interprets characters in `org-emphasis-alist' as
19916 word constituents."
19918 (with-syntax-table org-mode-transpose-word-syntax-table
19919 (call-interactively 'transpose-words)))
19920 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19922 (when (eq org-enable-table-editor 'optimized)
19923 ;; If the user wants maximum table support, we need to hijack
19924 ;; some standard editing functions
19925 (org-remap org-mode-map
19926 'self-insert-command 'org-self-insert-command
19927 'delete-char 'org-delete-char
19928 'delete-backward-char 'org-delete-backward-char)
19929 (org-defkey org-mode-map "|" 'org-force-self-insert))
19931 (defvar org-ctrl-c-ctrl-c-hook nil
19932 "Hook for functions attaching themselves to `C-c C-c'.
19934 This can be used to add additional functionality to the C-c C-c
19935 key which executes context-dependent commands. This hook is run
19936 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19937 run after the last test.
19939 Each function will be called with no arguments. The function
19940 must check if the context is appropriate for it to act. If yes,
19941 it should do its thing and then return a non-nil value. If the
19942 context is wrong, just do nothing and return nil.")
19944 (defvar org-ctrl-c-ctrl-c-final-hook nil
19945 "Hook for functions attaching themselves to `C-c C-c'.
19947 This can be used to add additional functionality to the C-c C-c
19948 key which executes context-dependent commands. This hook is run
19949 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19950 before the first test.
19952 Each function will be called with no arguments. The function
19953 must check if the context is appropriate for it to act. If yes,
19954 it should do its thing and then return a non-nil value. If the
19955 context is wrong, just do nothing and return nil.")
19957 (defvar org-tab-first-hook nil
19958 "Hook for functions to attach themselves to TAB.
19959 See `org-ctrl-c-ctrl-c-hook' for more information.
19960 This hook runs as the first action when TAB is pressed, even before
19961 `org-cycle' messes around with the `outline-regexp' to cater for
19962 inline tasks and plain list item folding.
19963 If any function in this hook returns t, any other actions that
19964 would have been caused by TAB (such as table field motion or visibility
19965 cycling) will not occur.")
19967 (defvar org-tab-after-check-for-table-hook nil
19968 "Hook for functions to attach themselves to TAB.
19969 See `org-ctrl-c-ctrl-c-hook' for more information.
19970 This hook runs after it has been established that the cursor is not in a
19971 table, but before checking if the cursor is in a headline or if global cycling
19973 If any function in this hook returns t, not other actions like visibility
19974 cycling will be done.")
19976 (defvar org-tab-after-check-for-cycling-hook nil
19977 "Hook for functions to attach themselves to TAB.
19978 See `org-ctrl-c-ctrl-c-hook' for more information.
19979 This hook runs after it has been established that not table field motion and
19980 not visibility should be done because of current context. This is probably
19981 the place where a package like yasnippets can hook in.")
19983 (defvar org-tab-before-tab-emulation-hook nil
19984 "Hook for functions to attach themselves to TAB.
19985 See `org-ctrl-c-ctrl-c-hook' for more information.
19986 This hook runs after every other options for TAB have been exhausted, but
19987 before indentation and \t insertion takes place.")
19989 (defvar org-metaleft-hook nil
19990 "Hook for functions attaching themselves to `M-left'.
19991 See `org-ctrl-c-ctrl-c-hook' for more information.")
19992 (defvar org-metaright-hook nil
19993 "Hook for functions attaching themselves to `M-right'.
19994 See `org-ctrl-c-ctrl-c-hook' for more information.")
19995 (defvar org-metaup-hook nil
19996 "Hook for functions attaching themselves to `M-up'.
19997 See `org-ctrl-c-ctrl-c-hook' for more information.")
19998 (defvar org-metadown-hook nil
19999 "Hook for functions attaching themselves to `M-down'.
20000 See `org-ctrl-c-ctrl-c-hook' for more information.")
20001 (defvar org-shiftmetaleft-hook nil
20002 "Hook for functions attaching themselves to `M-S-left'.
20003 See `org-ctrl-c-ctrl-c-hook' for more information.")
20004 (defvar org-shiftmetaright-hook nil
20005 "Hook for functions attaching themselves to `M-S-right'.
20006 See `org-ctrl-c-ctrl-c-hook' for more information.")
20007 (defvar org-shiftmetaup-hook nil
20008 "Hook for functions attaching themselves to `M-S-up'.
20009 See `org-ctrl-c-ctrl-c-hook' for more information.")
20010 (defvar org-shiftmetadown-hook nil
20011 "Hook for functions attaching themselves to `M-S-down'.
20012 See `org-ctrl-c-ctrl-c-hook' for more information.")
20013 (defvar org-metareturn-hook nil
20014 "Hook for functions attaching themselves to `M-RET'.
20015 See `org-ctrl-c-ctrl-c-hook' for more information.")
20016 (defvar org-shiftup-hook nil
20017 "Hook for functions attaching themselves to `S-up'.
20018 See `org-ctrl-c-ctrl-c-hook' for more information.")
20019 (defvar org-shiftup-final-hook nil
20020 "Hook for functions attaching themselves to `S-up'.
20021 This one runs after all other options except shift-select have been excluded.
20022 See `org-ctrl-c-ctrl-c-hook' for more information.")
20023 (defvar org-shiftdown-hook nil
20024 "Hook for functions attaching themselves to `S-down'.
20025 See `org-ctrl-c-ctrl-c-hook' for more information.")
20026 (defvar org-shiftdown-final-hook nil
20027 "Hook for functions attaching themselves to `S-down'.
20028 This one runs after all other options except shift-select have been excluded.
20029 See `org-ctrl-c-ctrl-c-hook' for more information.")
20030 (defvar org-shiftleft-hook nil
20031 "Hook for functions attaching themselves to `S-left'.
20032 See `org-ctrl-c-ctrl-c-hook' for more information.")
20033 (defvar org-shiftleft-final-hook nil
20034 "Hook for functions attaching themselves to `S-left'.
20035 This one runs after all other options except shift-select have been excluded.
20036 See `org-ctrl-c-ctrl-c-hook' for more information.")
20037 (defvar org-shiftright-hook nil
20038 "Hook for functions attaching themselves to `S-right'.
20039 See `org-ctrl-c-ctrl-c-hook' for more information.")
20040 (defvar org-shiftright-final-hook nil
20041 "Hook for functions attaching themselves to `S-right'.
20042 This one runs after all other options except shift-select have been excluded.
20043 See `org-ctrl-c-ctrl-c-hook' for more information.")
20045 (defun org-modifier-cursor-error ()
20046 "Throw an error, a modified cursor command was applied in wrong context."
20047 (user-error "This command is active in special context like tables, headlines or items"))
20049 (defun org-shiftselect-error ()
20050 "Throw an error because Shift-Cursor command was applied in wrong context."
20051 (if (and (boundp 'shift-select-mode) shift-select-mode)
20052 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20053 (user-error "This command works only in special context like headlines or timestamps")))
20055 (defun org-call-for-shift-select (cmd)
20056 (let ((this-command-keys-shift-translated t))
20057 (call-interactively cmd)))
20059 (defun org-shifttab (&optional arg)
20060 "Global visibility cycling or move to previous table field.
20061 Call `org-table-previous-field' within a table.
20062 When ARG is nil, cycle globally through visibility states.
20063 When ARG is a numeric prefix, show contents of this level."
20066 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20068 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20069 (message "Content view to level: %d" arg)
20070 (org-content (prefix-numeric-value arg2))
20071 (org-cycle-show-empty-lines t)
20072 (setq org-cycle-global-status 'overview)))
20073 (t (call-interactively 'org-global-cycle))))
20075 (defun org-shiftmetaleft ()
20076 "Promote subtree or delete table column.
20077 Calls `org-promote-subtree', `org-outdent-item-tree', or
20078 `org-table-delete-column', depending on context. See the
20079 individual commands for more information."
20082 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20083 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20084 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20085 ((if (not (org-region-active-p)) (org-at-item-p)
20086 (save-excursion (goto-char (region-beginning))
20088 (call-interactively 'org-outdent-item-tree))
20089 (t (org-modifier-cursor-error))))
20091 (defun org-shiftmetaright ()
20092 "Demote subtree or insert table column.
20093 Calls `org-demote-subtree', `org-indent-item-tree', or
20094 `org-table-insert-column', depending on context. See the
20095 individual commands for more information."
20098 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20099 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20100 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20101 ((if (not (org-region-active-p)) (org-at-item-p)
20102 (save-excursion (goto-char (region-beginning))
20104 (call-interactively 'org-indent-item-tree))
20105 (t (org-modifier-cursor-error))))
20107 (defun org-shiftmetaup (&optional arg)
20108 "Drag the line at point up.
20109 In a table, kill the current row.
20110 On a clock timestamp, update the value of the timestamp like `S-<up>'
20111 but also adjust the previous clocked item in the clock history.
20112 Everywhere else, drag the line at point up."
20115 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20116 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20117 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20118 (call-interactively 'org-timestamp-up)))
20119 (t (call-interactively 'org-drag-line-backward))))
20121 (defun org-shiftmetadown (&optional arg)
20122 "Drag the line at point down.
20123 In a table, insert an empty row at the current line.
20124 On a clock timestamp, update the value of the timestamp like `S-<down>'
20125 but also adjust the previous clocked item in the clock history.
20126 Everywhere else, drag the line at point down."
20129 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20130 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20131 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20132 (call-interactively 'org-timestamp-down)))
20133 (t (call-interactively 'org-drag-line-forward))))
20135 (defsubst org-hidden-tree-error ()
20137 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20139 (defun org-metaleft (&optional arg)
20140 "Promote heading or move table column to left.
20141 Calls `org-do-promote' or `org-table-move-column', depending on context.
20142 With no specific context, calls the Emacs default `backward-word'.
20143 See the individual commands for more information."
20146 ((run-hook-with-args-until-success 'org-metaleft-hook))
20147 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20148 ((org-with-limited-levels
20149 (or (org-at-heading-p)
20150 (and (org-region-active-p)
20152 (goto-char (region-beginning))
20153 (org-at-heading-p)))))
20154 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20155 (call-interactively 'org-do-promote))
20156 ;; At an inline task.
20157 ((org-at-heading-p)
20158 (call-interactively 'org-inlinetask-promote))
20159 ((or (org-at-item-p)
20160 (and (org-region-active-p)
20162 (goto-char (region-beginning))
20164 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20165 (call-interactively 'org-outdent-item))
20166 (t (call-interactively 'backward-word))))
20168 (defun org-metaright (&optional arg)
20169 "Demote a subtree, a list item or move table column to right.
20170 In front of a drawer or a block keyword, indent it correctly.
20171 With no specific context, calls the Emacs default `forward-word'.
20172 See the individual commands for more information."
20175 ((run-hook-with-args-until-success 'org-metaright-hook))
20176 ((org-at-table-p) (call-interactively 'org-table-move-column))
20177 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20178 ((org-at-block-p) (call-interactively 'org-indent-block))
20179 ((org-with-limited-levels
20180 (or (org-at-heading-p)
20181 (and (org-region-active-p)
20183 (goto-char (region-beginning))
20184 (org-at-heading-p)))))
20185 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20186 (call-interactively 'org-do-demote))
20187 ;; At an inline task.
20188 ((org-at-heading-p)
20189 (call-interactively 'org-inlinetask-demote))
20190 ((or (org-at-item-p)
20191 (and (org-region-active-p)
20193 (goto-char (region-beginning))
20195 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20196 (call-interactively 'org-indent-item))
20197 (t (call-interactively 'forward-word))))
20199 (defun org-check-for-hidden (what)
20200 "Check if there are hidden headlines/items in the current visual line.
20201 WHAT can be either `headlines' or `items'. If the current line is
20202 an outline or item heading and it has a folded subtree below it,
20203 this function returns t, nil otherwise."
20205 ((eq what 'headlines) org-outline-regexp-bol)
20206 ((eq what 'items) (org-item-beginning-re))
20207 (t (error "This should not happen"))))
20211 (unless (org-region-active-p)
20212 (setq beg (point-at-bol))
20213 (beginning-of-line 2)
20214 (while (and (not (eobp)) ;; this is like `next-line'
20215 (get-char-property (1- (point)) 'invisible))
20216 (beginning-of-line 2))
20219 (goto-char (point-at-eol))
20220 (setq end (max end (point)))
20221 (while (re-search-forward re end t)
20222 (if (get-char-property (match-beginning 0) 'invisible)
20226 (defun org-metaup (&optional arg)
20227 "Move subtree up or move table row up.
20228 Calls `org-move-subtree-up' or `org-table-move-row' or
20229 `org-move-item-up', depending on context. See the individual commands
20230 for more information."
20233 ((run-hook-with-args-until-success 'org-metaup-hook))
20234 ((org-region-active-p)
20235 (let* ((a (min (region-beginning) (region-end)))
20236 (b (1- (max (region-beginning) (region-end))))
20237 (c (save-excursion (goto-char a)
20238 (move-beginning-of-line 0)))
20239 (d (save-excursion (goto-char a)
20240 (move-end-of-line 0) (point))))
20241 (transpose-regions a b c d)
20243 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20244 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20245 ((org-at-item-p) (call-interactively 'org-move-item-up))
20246 (t (org-drag-element-backward))))
20248 (defun org-metadown (&optional arg)
20249 "Move subtree down or move table row down.
20250 Calls `org-move-subtree-down' or `org-table-move-row' or
20251 `org-move-item-down', depending on context. See the individual
20252 commands for more information."
20255 ((run-hook-with-args-until-success 'org-metadown-hook))
20256 ((org-region-active-p)
20257 (let* ((a (min (region-beginning) (region-end)))
20258 (b (max (region-beginning) (region-end)))
20259 (c (save-excursion (goto-char b)
20260 (move-beginning-of-line 1)))
20261 (d (save-excursion (goto-char b)
20262 (move-end-of-line 1) (1+ (point)))))
20263 (transpose-regions a b c d)
20265 ((org-at-table-p) (call-interactively 'org-table-move-row))
20266 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20267 ((org-at-item-p) (call-interactively 'org-move-item-down))
20268 (t (org-drag-element-forward))))
20270 (defun org-shiftup (&optional arg)
20271 "Increase item in timestamp or increase priority of current headline.
20272 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20273 depending on context. See the individual commands for more information."
20276 ((run-hook-with-args-until-success 'org-shiftup-hook))
20277 ((and org-support-shift-select (org-region-active-p))
20278 (org-call-for-shift-select 'previous-line))
20279 ((org-at-timestamp-p t)
20280 (call-interactively (if org-edit-timestamp-down-means-later
20281 'org-timestamp-down 'org-timestamp-up)))
20282 ((and (not (eq org-support-shift-select 'always))
20283 org-enable-priority-commands
20284 (org-at-heading-p))
20285 (call-interactively 'org-priority-up))
20286 ((and (not org-support-shift-select) (org-at-item-p))
20287 (call-interactively 'org-previous-item))
20288 ((org-clocktable-try-shift 'up arg))
20289 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20290 (org-support-shift-select
20291 (org-call-for-shift-select 'previous-line))
20292 (t (org-shiftselect-error))))
20294 (defun org-shiftdown (&optional arg)
20295 "Decrease item in timestamp or decrease priority of current headline.
20296 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20297 depending on context. See the individual commands for more information."
20300 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20301 ((and org-support-shift-select (org-region-active-p))
20302 (org-call-for-shift-select 'next-line))
20303 ((org-at-timestamp-p t)
20304 (call-interactively (if org-edit-timestamp-down-means-later
20305 'org-timestamp-up 'org-timestamp-down)))
20306 ((and (not (eq org-support-shift-select 'always))
20307 org-enable-priority-commands
20308 (org-at-heading-p))
20309 (call-interactively 'org-priority-down))
20310 ((and (not org-support-shift-select) (org-at-item-p))
20311 (call-interactively 'org-next-item))
20312 ((org-clocktable-try-shift 'down arg))
20313 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20314 (org-support-shift-select
20315 (org-call-for-shift-select 'next-line))
20316 (t (org-shiftselect-error))))
20318 (defun org-shiftright (&optional arg)
20319 "Cycle the thing at point or in the current line, depending on context.
20320 Depending on context, this does one of the following:
20322 - switch a timestamp at point one day into the future
20323 - on a headline, switch to the next TODO keyword.
20324 - on an item, switch entire list to the next bullet type
20325 - on a property line, switch to the next allowed value
20326 - on a clocktable definition line, move time block into the future"
20329 ((run-hook-with-args-until-success 'org-shiftright-hook))
20330 ((and org-support-shift-select (org-region-active-p))
20331 (org-call-for-shift-select 'forward-char))
20332 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20333 ((and (not (eq org-support-shift-select 'always))
20334 (org-at-heading-p))
20335 (let ((org-inhibit-logging
20336 (not org-treat-S-cursor-todo-selection-as-state-change))
20337 (org-inhibit-blocking
20338 (not org-treat-S-cursor-todo-selection-as-state-change)))
20339 (org-call-with-arg 'org-todo 'right)))
20340 ((or (and org-support-shift-select
20341 (not (eq org-support-shift-select 'always))
20342 (org-at-item-bullet-p))
20343 (and (not org-support-shift-select) (org-at-item-p)))
20344 (org-call-with-arg 'org-cycle-list-bullet nil))
20345 ((and (not (eq org-support-shift-select 'always))
20346 (org-at-property-p))
20347 (call-interactively 'org-property-next-allowed-value))
20348 ((org-clocktable-try-shift 'right arg))
20349 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20350 (org-support-shift-select
20351 (org-call-for-shift-select 'forward-char))
20352 (t (org-shiftselect-error))))
20354 (defun org-shiftleft (&optional arg)
20355 "Cycle the thing at point or in the current line, depending on context.
20356 Depending on context, this does one of the following:
20358 - switch a timestamp at point one day into the past
20359 - on a headline, switch to the previous TODO keyword.
20360 - on an item, switch entire list to the previous bullet type
20361 - on a property line, switch to the previous allowed value
20362 - on a clocktable definition line, move time block into the past"
20365 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20366 ((and org-support-shift-select (org-region-active-p))
20367 (org-call-for-shift-select 'backward-char))
20368 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20369 ((and (not (eq org-support-shift-select 'always))
20370 (org-at-heading-p))
20371 (let ((org-inhibit-logging
20372 (not org-treat-S-cursor-todo-selection-as-state-change))
20373 (org-inhibit-blocking
20374 (not org-treat-S-cursor-todo-selection-as-state-change)))
20375 (org-call-with-arg 'org-todo 'left)))
20376 ((or (and org-support-shift-select
20377 (not (eq org-support-shift-select 'always))
20378 (org-at-item-bullet-p))
20379 (and (not org-support-shift-select) (org-at-item-p)))
20380 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20381 ((and (not (eq org-support-shift-select 'always))
20382 (org-at-property-p))
20383 (call-interactively 'org-property-previous-allowed-value))
20384 ((org-clocktable-try-shift 'left arg))
20385 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20386 (org-support-shift-select
20387 (org-call-for-shift-select 'backward-char))
20388 (t (org-shiftselect-error))))
20390 (defun org-shiftcontrolright ()
20391 "Switch to next TODO set."
20394 ((and org-support-shift-select (org-region-active-p))
20395 (org-call-for-shift-select 'forward-word))
20396 ((and (not (eq org-support-shift-select 'always))
20397 (org-at-heading-p))
20398 (org-call-with-arg 'org-todo 'nextset))
20399 (org-support-shift-select
20400 (org-call-for-shift-select 'forward-word))
20401 (t (org-shiftselect-error))))
20403 (defun org-shiftcontrolleft ()
20404 "Switch to previous TODO set."
20407 ((and org-support-shift-select (org-region-active-p))
20408 (org-call-for-shift-select 'backward-word))
20409 ((and (not (eq org-support-shift-select 'always))
20410 (org-at-heading-p))
20411 (org-call-with-arg 'org-todo 'previousset))
20412 (org-support-shift-select
20413 (org-call-for-shift-select 'backward-word))
20414 (t (org-shiftselect-error))))
20416 (defun org-shiftcontrolup (&optional n)
20417 "Change timestamps synchronously up in CLOCK log lines.
20418 Optional argument N tells to change by that many units."
20420 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20421 (let (org-support-shift-select)
20422 (org-clock-timestamps-up n))
20423 (user-error "Not at a clock log")))
20425 (defun org-shiftcontroldown (&optional n)
20426 "Change timestamps synchronously down in CLOCK log lines.
20427 Optional argument N tells to change by that many units."
20429 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20430 (let (org-support-shift-select)
20431 (org-clock-timestamps-down n))
20432 (user-error "Not at a clock log")))
20434 (defun org-increase-number-at-point (&optional inc)
20435 "Increment the number at point.
20436 With an optional prefix numeric argument INC, increment using
20437 this numeric value."
20439 (if (not (number-at-point))
20440 (user-error "Not on a number")
20441 (unless inc (setq inc 1))
20442 (let ((pos (point))
20443 (beg (skip-chars-backward "-+^/*0-9eE."))
20444 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20445 (setq nap (buffer-substring-no-properties
20446 (+ pos beg) (+ pos beg end)))
20447 (delete-region (+ pos beg) (+ pos beg end))
20448 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20449 (when (org-at-table-p)
20451 (org-table-end-of-field 1))))
20453 (defun org-decrease-number-at-point (&optional inc)
20454 "Decrement the number at point.
20455 With an optional prefix numeric argument INC, decrement using
20456 this numeric value."
20458 (org-increase-number-at-point (- inc)))
20460 (defun org-ctrl-c-ret ()
20461 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20464 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20465 (t (call-interactively 'org-insert-heading))))
20467 (defun org-find-visible ()
20469 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20470 (get-char-property s 'invisible)))
20472 (defun org-find-invisible ()
20474 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20475 (not (get-char-property s 'invisible))))
20478 (defun org-copy-visible (beg end)
20479 "Copy the visible parts of the region."
20484 (narrow-to-region beg end)
20485 (setq s (goto-char (point-min)))
20486 (while (not (= (point) (point-max)))
20487 (goto-char (org-find-invisible))
20488 (push (buffer-substring s (point)) snippets)
20489 (setq s (goto-char (org-find-visible))))))
20490 (kill-new (apply 'concat (nreverse snippets)))))
20492 (defun org-copy-special ()
20493 "Copy region in table or copy current subtree.
20494 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20495 See the individual commands for more information."
20497 (call-interactively
20498 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20500 (defun org-cut-special ()
20501 "Cut region in table or cut current subtree.
20502 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20503 See the individual commands for more information."
20505 (call-interactively
20506 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20508 (defun org-paste-special (arg)
20509 "Paste rectangular region into table, or past subtree relative to level.
20510 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20511 See the individual commands for more information."
20513 (if (org-at-table-p)
20514 (org-table-paste-rectangle)
20515 (org-paste-subtree arg)))
20517 (defsubst org-in-fixed-width-region-p ()
20518 "Is point in a fixed-width region?"
20520 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20522 (defun org-edit-special (&optional arg)
20523 "Call a special editor for the element at point.
20524 When at a table, call the formula editor with `org-table-edit-formulas'.
20525 When in a source code block, call `org-edit-src-code'.
20526 When in a fixed-width region, call `org-edit-fixed-width-region'.
20527 When at an #+INCLUDE keyword, visit the included file.
20528 On a link, call `ffap' to visit the link at point.
20529 Otherwise, return a user error."
20531 (let ((element (org-element-at-point)))
20532 (assert (not buffer-read-only) nil
20533 "Buffer is read-only: %s" (buffer-name))
20534 (case (org-element-type element)
20536 (if (not arg) (org-edit-src-code)
20537 (let* ((info (org-babel-get-src-block-info))
20538 (lang (nth 0 info))
20539 (params (nth 2 info))
20540 (session (cdr (assq :session params))))
20541 (if (not session) (org-edit-src-code)
20542 ;; At a src-block with a session and function called with
20543 ;; an ARG: switch to the buffer related to the inferior
20546 (funcall (intern (concat "org-babel-prep-session:" lang))
20547 session params))))))
20549 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20550 (org-open-link-from-string
20553 (let ((value (org-element-property :value element)))
20554 (cond ((not (org-string-nw-p value))
20555 (user-error "No file to edit"))
20556 ((string-match "\\`\"\\(.*?\\)\"" value)
20557 (match-string 1 value))
20558 ((string-match "\\`[^ \t\"]\\S-*" value)
20559 (match-string 0 value))
20560 (t (user-error "No valid file specified")))))))
20561 (user-error "No special environment to edit here")))
20563 (if (eq (org-element-property :type element) 'table.el)
20564 (org-edit-src-code)
20565 (call-interactively 'org-table-edit-formulas)))
20566 ;; Only Org tables contain `table-row' type elements.
20567 (table-row (call-interactively 'org-table-edit-formulas))
20568 ((example-block export-block) (org-edit-src-code))
20569 (fixed-width (org-edit-fixed-width-region))
20571 ;; No notable element at point. Though, we may be at a link,
20572 ;; which is an object. Thus, scan deeper.
20573 (if (eq (org-element-type (org-element-context element)) 'link)
20574 (call-interactively 'ffap)
20575 (user-error "No special environment to edit here"))))))
20577 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20578 (defun org-ctrl-c-ctrl-c (&optional arg)
20579 "Set tags in headline, or update according to changed information at point.
20581 This command does many different things, depending on context:
20583 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20584 this is what we do.
20586 - If the cursor is on a statistics cookie, update it.
20588 - If the cursor is in a headline, prompt for tags and insert them
20589 into the current line, aligned to `org-tags-column'. When called
20590 with prefix arg, realign all tags in the current buffer.
20592 - If the cursor is in one of the special #+KEYWORD lines, this
20593 triggers scanning the buffer for these lines and updating the
20596 - If the cursor is inside a table, realign the table. This command
20597 works even if the automatic table editor has been turned off.
20599 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20602 - If the cursor is at a footnote reference or definition, jump to
20603 the corresponding definition or references, respectively.
20605 - If the cursor is a the beginning of a dynamic block, update it.
20607 - If the current buffer is a capture buffer, close note and file it.
20609 - If the cursor is on a <<<target>>>, update radio targets and
20610 corresponding links in this buffer.
20612 - If the cursor is on a numbered item in a plain list, renumber the
20615 - If the cursor is on a checkbox, toggle it.
20617 - If the cursor is on a code block, evaluate it. The variable
20618 `org-confirm-babel-evaluate' can be used to control prompting
20619 before code block evaluation, by default every code block
20620 evaluation requires confirmation. Code block evaluation can be
20621 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20624 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20625 org-occur-highlights)
20626 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20627 (org-remove-occur-highlights)
20628 (message "Temporary highlights/overlays removed from current buffer"))
20629 ((and (local-variable-p 'org-finish-function (current-buffer))
20630 (fboundp org-finish-function))
20631 (funcall org-finish-function))
20632 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20634 (let* ((context (org-element-context)) (type (org-element-type context)))
20635 ;; Test if point is within a blank line.
20636 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20637 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20638 (user-error "C-c C-c can do nothing useful at this location"))
20640 ;; When at a link, act according to the parent instead.
20641 (link (setq context (org-element-property :parent context))
20642 (setq type (org-element-type context)))
20643 ;; Unsupported object types: refer to the first supported
20644 ;; element or object containing it.
20645 ((bold code entity export-snippet inline-babel-call inline-src-block
20646 italic latex-fragment line-break macro strike-through subscript
20647 superscript underline verbatim)
20648 (while (and (setq context (org-element-property :parent context))
20649 (not (memq (setq type (org-element-type context))
20650 '(radio-target paragraph verse-block
20652 ;; For convenience: at the first line of a paragraph on the
20653 ;; same line as an item, apply function on that item instead.
20654 (when (eq type 'paragraph)
20655 (let ((parent (org-element-property :parent context)))
20656 (when (and (eq (org-element-type parent) 'item)
20657 (= (point-at-bol) (org-element-property :begin parent)))
20658 (setq context parent type 'item))))
20659 ;; Act according to type of element or object at point.
20661 (clock (org-clock-update-time-maybe))
20664 (goto-char (org-element-property :post-affiliated context))
20665 (org-update-dblock)))
20666 (footnote-definition
20667 (goto-char (org-element-property :post-affiliated context))
20668 (call-interactively 'org-footnote-action))
20669 (footnote-reference (call-interactively 'org-footnote-action))
20670 ((headline inlinetask)
20671 (save-excursion (goto-char (org-element-property :begin context))
20672 (call-interactively 'org-set-tags)))
20674 ;; At an item: a double C-u set checkbox to "[-]"
20675 ;; unconditionally, whereas a single one will toggle its
20676 ;; presence. Without an universal argument, if the item
20677 ;; has a checkbox, toggle it. Otherwise repair the list.
20678 (let* ((box (org-element-property :checkbox context))
20679 (struct (org-element-property :structure context))
20680 (old-struct (copy-tree struct))
20681 (parents (org-list-parents-alist struct))
20682 (prevs (org-list-prevs-alist struct))
20683 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20684 (org-list-set-checkbox
20685 (org-element-property :begin context) struct
20686 (cond ((equal arg '(16)) "[-]")
20687 ((and (not box) (equal arg '(4))) "[ ]")
20688 ((or (not box) (equal arg '(4))) nil)
20689 ((eq box 'on) "[ ]")
20691 ;; Mimic `org-list-write-struct' but with grabbing
20692 ;; a return value from `org-list-struct-fix-box'.
20693 (org-list-struct-fix-ind struct parents 2)
20694 (org-list-struct-fix-item-end struct)
20695 (org-list-struct-fix-bul struct prevs)
20696 (org-list-struct-fix-ind struct parents)
20698 (org-list-struct-fix-box struct parents prevs orderedp)))
20699 (if (and box (equal struct old-struct))
20700 (if (equal arg '(16))
20701 (message "Checkboxes already reset")
20702 (user-error "Cannot toggle this checkbox: %s"
20704 "all subitems checked"
20705 "unchecked subitems")))
20706 (org-list-struct-apply-struct struct old-struct)
20707 (org-update-checkbox-count-maybe))
20709 (message "Checkboxes were removed due to empty box at line %d"
20710 (org-current-line block-item))))))
20712 (let ((org-inhibit-startup-visibility-stuff t)
20713 (org-startup-align-all-tables nil))
20714 (when (boundp 'org-table-coordinate-overlays)
20715 (mapc 'delete-overlay org-table-coordinate-overlays)
20716 (setq org-table-coordinate-overlays nil))
20717 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20718 (message "Local setup has been refreshed"))
20720 ;; At a plain list, with a double C-u argument, set
20721 ;; checkboxes of each item to "[-]", whereas a single one
20722 ;; will toggle their presence according to the state of the
20723 ;; first item in the list. Without an argument, repair the
20725 (let* ((begin (org-element-property :contents-begin context))
20726 (beginm (move-marker (make-marker) begin))
20727 (struct (org-element-property :structure context))
20728 (old-struct (copy-tree struct))
20729 (first-box (save-excursion
20731 (looking-at org-list-full-item-re)
20732 (match-string-no-properties 3)))
20733 (new-box (cond ((equal arg '(16)) "[-]")
20734 ((equal arg '(4)) (unless first-box "[ ]"))
20735 ((equal first-box "[X]") "[ ]")
20739 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20740 (org-list-get-all-items
20741 begin struct (org-list-prevs-alist struct))))
20742 ((and first-box (eq (point) begin))
20743 ;; For convenience, when point is at bol on the first
20744 ;; item of the list and no argument is provided, simply
20745 ;; toggle checkbox of that item, if any.
20746 (org-list-set-checkbox begin struct new-box)))
20747 (org-list-write-struct
20748 struct (org-list-parents-alist struct) old-struct)
20749 (org-update-checkbox-count-maybe)
20750 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20751 ((property-drawer node-property)
20752 (call-interactively 'org-property-action))
20753 ((radio-target target)
20754 (call-interactively 'org-update-radio-target-regexp))
20756 (call-interactively 'org-update-statistics-cookies))
20757 ((table table-cell table-row)
20758 ;; At a table, recalculate every field and align it. Also
20759 ;; send the table if necessary. If the table has
20760 ;; a `table.el' type, just give up. At a table row or
20761 ;; cell, maybe recalculate line but always align table.
20762 (if (eq (org-element-property :type context) 'table.el)
20763 (message "Use C-c ' to edit table.el tables")
20764 (let ((org-enable-table-editor t))
20765 (if (or (eq type 'table)
20766 ;; Check if point is at a TBLFM line.
20767 (and (eq type 'table-row)
20768 (= (point) (org-element-property :end context))))
20770 (if (org-at-TBLFM-p)
20771 (progn (require 'org-table)
20772 (org-table-calc-current-TBLFM))
20773 (goto-char (org-element-property :contents-begin context))
20774 (org-call-with-arg 'org-table-recalculate (or arg t))
20775 (orgtbl-send-table 'maybe)))
20776 (org-table-maybe-eval-formula)
20777 (cond (arg (call-interactively 'org-table-recalculate))
20778 ((org-table-maybe-recalculate-line))
20779 (t (org-table-align)))))))
20780 (timestamp (org-timestamp-change 0 'day))
20782 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20784 "C-c C-c can do nothing useful at this location")))))))))
20786 (defun org-mode-restart ()
20788 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20789 (funcall major-mode)
20790 (hack-local-variables)
20791 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20792 (org-indent-mode -1)))
20793 (message "%s restarted" major-mode))
20795 (defun org-kill-note-or-show-branches ()
20796 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20798 (if (not org-finish-function)
20801 (call-interactively 'show-branches))
20802 (let ((org-note-abort t))
20803 (funcall org-finish-function))))
20805 (defun org-open-line (n)
20806 "Insert a new row in tables, call `open-line' elsewhere.
20807 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20810 ((not org-special-ctrl-o)
20813 (org-table-insert-row))
20817 (defun org-return (&optional indent)
20818 "Goto next table row or insert a newline.
20819 Calls `org-table-next-row' or `newline', depending on context.
20820 See the individual commands for more information."
20824 ((or (bobp) (org-in-src-block-p))
20825 (if indent (newline-and-indent) (newline)))
20827 (org-table-justify-field-maybe)
20828 (call-interactively 'org-table-next-row))
20829 ;; when `newline-and-indent' is called within a list, make sure
20830 ;; text moved stays inside the item.
20831 ((and (org-in-item-p) indent)
20832 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20834 (save-match-data (newline))
20835 (org-indent-line-to (length (match-string 0))))
20836 (let ((ind (org-get-indentation)))
20838 (if (org-looking-back org-list-end-re)
20840 (org-indent-line-to ind)))))
20841 ((and org-return-follows-link
20842 (org-at-timestamp-p t)
20843 (not (eq org-ts-what 'after)))
20844 (org-follow-timestamp-link))
20845 ((and org-return-follows-link
20846 (let ((tprop (get-text-property (point) 'face)))
20847 (or (eq tprop 'org-link)
20848 (and (listp tprop) (memq 'org-link tprop)))))
20849 (call-interactively 'org-open-at-point))
20850 ((and (org-at-heading-p)
20852 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20856 (t (if indent (newline-and-indent) (newline))))))
20858 (defun org-return-indent ()
20859 "Goto next table row or insert a newline and indent.
20860 Calls `org-table-next-row' or `newline-and-indent', depending on
20861 context. See the individual commands for more information."
20865 (defun org-ctrl-c-star ()
20866 "Compute table, or change heading status of lines.
20867 Calls `org-table-recalculate' or `org-toggle-heading',
20868 depending on context."
20872 (call-interactively 'org-table-recalculate))
20874 ;; Convert all lines in region to list items
20875 (call-interactively 'org-toggle-heading))))
20877 (defun org-ctrl-c-minus ()
20878 "Insert separator line in table or modify bullet status of line.
20879 Also turns a plain line or a region of lines into list items.
20880 Calls `org-table-insert-hline', `org-toggle-item', or
20881 `org-cycle-list-bullet', depending on context."
20885 (call-interactively 'org-table-insert-hline))
20886 ((org-region-active-p)
20887 (call-interactively 'org-toggle-item))
20889 (call-interactively 'org-cycle-list-bullet))
20891 (call-interactively 'org-toggle-item))))
20893 (defun org-toggle-item (arg)
20894 "Convert headings or normal lines to items, items to normal lines.
20895 If there is no active region, only the current line is considered.
20897 If the first non blank line in the region is a headline, convert
20898 all headlines to items, shifting text accordingly.
20900 If it is an item, convert all items to normal lines.
20902 If it is normal text, change region into a list of items.
20903 With a prefix argument ARG, change the region in a single item."
20907 ;; Shift text in current section to IND, from point to END.
20908 ;; The function leaves point to END line.
20910 (let ((min-i 1000) (end (copy-marker end)))
20911 ;; First determine the minimum indentation (MIN-I) of
20915 (while (< (point) end)
20916 (let ((i (org-get-indentation)))
20918 ;; Skip blank lines and inline tasks.
20919 ((looking-at "^[ \t]*$"))
20920 ((looking-at org-outline-regexp-bol))
20921 ;; We can't find less than 0 indentation.
20922 ((zerop i) (throw 'exit (setq min-i 0)))
20923 ((< i min-i) (setq min-i i))))
20925 ;; Then indent each line so that a line indented to
20926 ;; MIN-I becomes indented to IND. Ignore blank lines
20927 ;; and inline tasks in the process.
20928 (let ((delta (- ind min-i)))
20929 (while (< (point) end)
20930 (unless (or (looking-at "^[ \t]*$")
20931 (looking-at org-outline-regexp-bol))
20932 (org-indent-line-to (+ (org-get-indentation) delta)))
20933 (forward-line)))))))
20936 ;; Return beginning of first non-blank line, starting from
20941 (skip-chars-forward " \r\t\n")
20944 ;; Determine boundaries of changes.
20945 (if (org-region-active-p)
20946 (setq beg (funcall skip-blanks (region-beginning))
20947 end (copy-marker (region-end)))
20948 (setq beg (funcall skip-blanks (point-at-bol))
20949 end (copy-marker (point-at-eol))))
20950 ;; Depending on the starting line, choose an action on the text
20951 ;; between BEG and END.
20952 (org-with-limited-levels
20956 ;; Case 1. Start at an item: de-itemize. Note that it only
20957 ;; happens when a region is active: `org-ctrl-c-minus'
20958 ;; would call `org-cycle-list-bullet' otherwise.
20960 (while (< (point) end)
20961 (when (org-at-item-p)
20962 (skip-chars-forward " \t")
20963 (delete-region (point) (match-end 0)))
20965 ;; Case 2. Start at an heading: convert to items.
20966 ((org-at-heading-p)
20967 (let* ((bul (org-list-bullet-string "-"))
20968 (bul-len (length bul))
20969 (done (org-entry-is-done-p))
20970 (todo (org-entry-is-todo-p))
20971 ;; Indentation of the first heading. It should be
20972 ;; relative to the indentation of its parent, if any.
20973 (start-ind (save-excursion
20975 ((not org-adapt-indentation) 0)
20976 ((not (outline-previous-heading)) 0)
20977 (t (length (match-string 0))))))
20978 ;; Level of first heading. Further headings will be
20979 ;; compared to it to determine hierarchy in the list.
20980 (ref-level (org-reduced-level (org-outline-level))))
20981 (when (or done todo) (org-todo ""))
20982 (while (< (point) end)
20983 (let* ((level (org-reduced-level (org-outline-level)))
20984 (delta (max 0 (- level ref-level))))
20985 ;; If current headline is less indented than the first
20986 ;; one, set it as reference, in order to preserve
20988 (when (< level ref-level) (setq ref-level level))
20989 (replace-match bul t t)
20990 (org-indent-line-to (+ start-ind (* delta bul-len)))
20991 (when (or done todo)
20992 (let* ((struct (org-list-struct))
20993 (old (copy-tree struct)))
20994 (org-list-set-checkbox (line-beginning-position)
20996 (if done "[X]" "[ ]"))
20997 (org-list-write-struct struct
20998 (org-list-parents-alist struct)
21000 ;; Ensure all text down to END (or SECTION-END) belongs
21001 ;; to the newly created item.
21002 (let ((section-end (save-excursion
21003 (or (outline-next-heading) (point)))))
21005 (funcall shift-text
21006 (+ start-ind (* (1+ delta) bul-len))
21007 (min end section-end)))))))
21008 ;; Case 3. Normal line with ARG: make the first line of region
21009 ;; an item, and shift indentation of others lines to
21010 ;; set them as item's body.
21011 (arg (let* ((bul (org-list-bullet-string "-"))
21012 (bul-len (length bul))
21013 (ref-ind (org-get-indentation)))
21014 (skip-chars-forward " \t")
21017 (while (< (point) end)
21018 ;; Ensure that lines less indented than first one
21019 ;; still get included in item body.
21020 (funcall shift-text
21021 (+ ref-ind bul-len)
21022 (min end (save-excursion (or (outline-next-heading)
21025 ;; Case 4. Normal line without ARG: turn each non-item line
21028 (while (< (point) end)
21029 (unless (or (org-at-heading-p) (org-at-item-p))
21030 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21032 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21033 (forward-line))))))))
21035 (defun org-toggle-heading (&optional nstars)
21036 "Convert headings to normal text, or items or text to headings.
21037 If there is no active region, only convert the current line.
21039 With a \\[universal-argument] prefix, convert the whole list at
21040 point into heading.
21044 - If the first non blank line is a headline, remove the stars
21045 from all headlines in the region.
21047 - If it is a normal line, turn each and every normal line (i.e.,
21048 not an heading or an item) in the region into headings. If you
21049 want to convert only the first line of this region, use one
21050 universal prefix argument.
21052 - If it is a plain list item, turn all plain list items into headings.
21054 When converting a line into a heading, the number of stars is chosen
21055 such that the lines become children of the current entry. However,
21056 when a numeric prefix argument is given, its value determines the
21057 number of stars to add."
21061 ;; Return beginning of first non-blank line, starting from
21066 (while (org-at-comment-p) (forward-line))
21067 (skip-chars-forward " \r\t\n")
21070 ;; Determine boundaries of changes. If a universal prefix has
21071 ;; been given, put the list in a region. If region ends at a bol,
21072 ;; do not consider the last line to be in the region.
21074 (when (and current-prefix-arg (org-at-item-p))
21075 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21076 (org-mark-element))
21078 (if (org-region-active-p)
21079 (setq beg (funcall skip-blanks (region-beginning))
21080 end (copy-marker (save-excursion
21081 (goto-char (region-end))
21082 (if (bolp) (point) (point-at-eol)))))
21083 (setq beg (funcall skip-blanks (point-at-bol))
21084 end (copy-marker (point-at-eol))))
21085 ;; Ensure inline tasks don't count as headings.
21086 (org-with-limited-levels
21090 ;; Case 1. Started at an heading: de-star headings.
21091 ((org-at-heading-p)
21092 (while (< (point) end)
21093 (when (org-at-heading-p t)
21094 (looking-at org-outline-regexp) (replace-match "")
21097 ;; Case 2. Started at an item: change items into headlines.
21098 ;; One star will be added by `org-list-to-subtree'.
21100 (let* ((stars (make-string
21101 ;; subtract the star that will be added again by
21102 ;; `org-list-to-subtree'
21103 (if (numberp nstars) (1- nstars)
21104 (or (org-current-level) 0))
21107 (cond (nstars "") ; stars from prefix only
21108 ((equal stars "") "") ; before first heading
21109 (org-odd-levels-only "*") ; inside heading, odd
21110 (t "")))) ; inside heading, oddeven
21111 (while (< (point) end)
21112 (when (org-at-item-p)
21113 ;; Pay attention to cases when region ends before list.
21114 (let* ((struct (org-list-struct))
21115 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21117 (narrow-to-region (point) list-end)
21119 (org-list-to-subtree
21120 (org-list-parse-list t)
21121 '(:istart (concat stars add-stars (funcall get-stars depth))
21122 :icount (concat stars add-stars (funcall get-stars depth)))))))
21125 ;; Case 3. Started at normal text: make every line an heading,
21126 ;; skipping headlines and items.
21129 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21131 (cond (nstars "") ; stars from prefix only
21132 ((equal stars "") "*") ; before first heading
21133 (org-odd-levels-only "**") ; inside heading, odd
21134 (t "*"))) ; inside heading, oddeven
21135 (rpl (concat stars add-stars " "))
21136 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21137 (while (< (point) (if (equal nstars '(4)) lend end))
21138 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21139 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21140 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21141 (forward-line)))))))
21142 (unless toggled (message "Cannot toggle heading from here"))))
21144 (defun org-meta-return (&optional arg)
21145 "Insert a new heading or wrap a region in a table.
21146 Calls `org-insert-heading' or `org-table-wrap-region', depending
21147 on context. See the individual commands for more information."
21149 (org-check-before-invisible-edit 'insert)
21150 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21151 (let* ((element (org-element-at-point))
21152 (type (org-element-type element)))
21153 (when (eq type 'table-row)
21154 (setq element (org-element-property :parent element))
21155 (setq type 'table))
21156 (if (and (eq type 'table)
21157 (eq (org-element-property :type element) 'org)
21158 (>= (point) (org-element-property :contents-begin element))
21159 (< (point) (org-element-property :contents-end element)))
21160 (call-interactively 'org-table-wrap-region)
21161 (call-interactively 'org-insert-heading)))))
21165 (defsubst org-in-subtree-not-table-p ()
21166 "Are we in a subtree and not in a table?"
21167 (and (not (org-before-first-heading-p))
21168 (not (org-at-table-p))))
21170 ;; Define the Org-mode menus
21171 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21173 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21174 ["Next Field" org-cycle (org-at-table-p)]
21175 ["Previous Field" org-shifttab (org-at-table-p)]
21176 ["Next Row" org-return (org-at-table-p)]
21178 ["Blank Field" org-table-blank-field (org-at-table-p)]
21179 ["Edit Field" org-table-edit-field (org-at-table-p)]
21180 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21183 ["Move Column Left" org-metaleft (org-at-table-p)]
21184 ["Move Column Right" org-metaright (org-at-table-p)]
21185 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21186 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21188 ["Move Row Up" org-metaup (org-at-table-p)]
21189 ["Move Row Down" org-metadown (org-at-table-p)]
21190 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21191 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21192 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21194 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21196 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21197 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21198 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21199 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21202 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21203 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21204 ["Edit Formulas" org-edit-special (org-at-table-p)]
21206 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21207 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21208 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21210 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21212 ["Sum Column/Rectangle" org-table-sum
21213 (or (org-at-table-p) (org-region-active-p))]
21214 ["Which Column?" org-table-current-column (org-at-table-p)])
21216 org-table-toggle-formula-debugger
21217 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21218 ["Show Col/Row Numbers"
21219 org-table-toggle-coordinate-overlays
21221 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21223 ["Create" org-table-create (and (not (org-at-table-p))
21224 org-enable-table-editor)]
21225 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21226 ["Import from File" org-table-import (not (org-at-table-p))]
21227 ["Export to File" org-table-export (org-at-table-p)]
21229 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21232 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21233 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21235 (easy-menu-define org-org-menu org-mode-map "Org menu"
21238 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21239 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21240 ["Sparse Tree..." org-sparse-tree t]
21241 ["Reveal Context" org-reveal t]
21242 ["Show All" show-all t]
21244 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21246 ["New Heading" org-insert-heading t]
21247 ("Navigate Headings"
21248 ["Up" outline-up-heading t]
21249 ["Next" outline-next-visible-heading t]
21250 ["Previous" outline-previous-visible-heading t]
21251 ["Next Same Level" outline-forward-same-level t]
21252 ["Previous Same Level" outline-backward-same-level t]
21254 ["Jump" org-goto t])
21256 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21258 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21259 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21261 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21262 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21263 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21265 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21267 ["Copy visible text" org-copy-visible t]
21269 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21270 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21271 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21272 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21274 ["Sort Region/Children" org-sort t]
21276 ["Convert to odd levels" org-convert-to-odd-levels t]
21277 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21279 ["Emphasis..." org-emphasize t]
21280 ["Edit Source Example" org-edit-special t]
21282 ["Footnote new/jump" org-footnote-action t]
21283 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21285 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21287 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21288 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21289 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21293 ["Store Link (Global)" org-store-link t]
21294 ["Find existing link to here" org-occur-link-in-agenda-files t]
21295 ["Insert Link" org-insert-link t]
21296 ["Follow Link" org-open-at-point t]
21298 ["Next link" org-next-link t]
21299 ["Previous link" org-previous-link t]
21301 ["Descriptive Links"
21302 org-toggle-link-display
21304 :selected org-descriptive-links
21307 org-toggle-link-display
21309 :selected (not org-descriptive-links)])
21312 ["TODO/DONE/-" org-todo t]
21314 ["Next keyword" org-shiftright (org-at-heading-p)]
21315 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21316 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21317 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21318 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21319 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21320 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21322 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21323 :selected org-enforce-todo-dependencies :style toggle :active t]
21324 "Settings for tree at point"
21325 ["Do Children sequentially" org-toggle-ordered-property :style radio
21326 :selected (org-entry-get nil "ORDERED")
21327 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21328 ["Do Children parallel" org-toggle-ordered-property :style radio
21329 :selected (not (org-entry-get nil "ORDERED"))
21330 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21332 ["Set Priority" org-priority t]
21333 ["Priority Up" org-shiftup t]
21334 ["Priority Down" org-shiftdown t]
21336 ["Get news from all feeds" org-feed-update-all t]
21337 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21338 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21339 ("TAGS and Properties"
21340 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21341 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21343 ["Set property" org-set-property (not (org-before-first-heading-p))]
21344 ["Column view of properties" org-columns t]
21345 ["Insert Column View DBlock" org-insert-columns-dblock t])
21346 ("Dates and Scheduling"
21347 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21348 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21350 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21351 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21352 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21353 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21354 ["Compute Time Range" org-evaluate-time-range t]
21355 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21356 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21358 ["Custom time format" org-toggle-time-stamp-overlays
21359 :style radio :selected org-display-custom-times]
21361 ["Goto Calendar" org-goto-calendar t]
21362 ["Date from Calendar" org-date-from-calendar t]
21364 ["Start/Restart Timer" org-timer-start t]
21365 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21366 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21367 ["Insert Timer String" org-timer t]
21368 ["Insert Timer Item" org-timer-item t])
21370 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21371 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21372 ["Clock out" org-clock-out t]
21373 ["Clock cancel" org-clock-cancel t]
21375 ["Mark as default task" org-clock-mark-default-task t]
21376 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21377 ["Goto running clock" org-clock-goto t]
21379 ["Display times" org-clock-display t]
21380 ["Create clock table" org-clock-report t]
21382 ["Record DONE time"
21383 (progn (setq org-log-done (not org-log-done))
21384 (message "Switching to %s will %s record a timestamp"
21385 (car org-done-keywords)
21386 (if org-log-done "automatically" "not")))
21387 :style toggle :selected org-log-done])
21389 ["Agenda Command..." org-agenda t]
21390 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21391 ("File List for Agenda")
21392 ("Special views current file"
21393 ["TODO Tree" org-show-todo-tree t]
21394 ["Check Deadlines" org-check-deadlines t]
21395 ["Timeline" org-timeline t]
21396 ["Tags/Property tree" org-match-sparse-tree t])
21398 ["Export/Publish..." org-export-dispatch t]
21400 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21401 :selected org-cdlatex-mode]
21402 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21403 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21404 ["Modify math symbol" org-cdlatex-math-modify
21405 (org-inside-LaTeX-fragment-p)]
21406 ["Insert citation" org-reftex-citation t]
21408 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21411 ["Push Files and Views" org-mobile-push t]
21412 ["Get Captured and Flagged" org-mobile-pull t]
21413 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21415 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21418 ["Show Version" org-version t]
21419 ["Info Documentation" org-info t])
21421 ["Browse Org Group" org-customize t]
21423 ["Expand This Menu" org-create-customize-menu
21424 (fboundp 'customize-menu-create)])
21425 ["Send bug report" org-submit-bug-report t]
21428 ["Refresh setup current buffer" org-mode-restart t]
21429 ["Reload Org (after update)" org-reload t]
21430 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21433 (defun org-info (&optional node)
21434 "Read documentation for Org-mode in the info system.
21435 With optional NODE, go directly to that node."
21437 (info (format "(org)%s" (or node ""))))
21440 (defun org-submit-bug-report ()
21441 "Submit a bug report on Org-mode via mail.
21443 Don't hesitate to report any problems or inaccurate documentation.
21445 If you don't have setup sending mail from (X)Emacs, please copy the
21446 output buffer into your mail program, as it gives us important
21447 information about your Org-mode version and configuration."
21449 (require 'reporter)
21450 (org-load-modules-maybe)
21451 (org-require-autoloaded-modules)
21452 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21453 (reporter-submit-bug-report
21454 "emacs-orgmode@gnu.org"
21455 (org-version nil 'full)
21457 (save-window-excursion
21458 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21459 (delete-other-windows)
21461 (insert "You are about to submit a bug report to the Org-mode mailing list.
21463 We would like to add your full Org-mode and Outline configuration to the
21464 bug report. This greatly simplifies the work of the maintainer and
21465 other experts on the mailing list.
21467 HOWEVER, some variables you have customized may contain private
21468 information. The names of customers, colleagues, or friends, might
21469 appear in the form of file names, tags, todo states, or search strings.
21470 If you answer yes to the prompt, you might want to check and remove
21471 such private information before sending the email.")
21472 (add-text-properties (point-min) (point-max) '(face org-warning))
21473 (when (yes-or-no-p "Include your Org-mode configuration ")
21477 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21478 (or (and (symbol-value v)
21479 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21481 (get v 'custom-type) (get v 'standard-value)
21482 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21484 (kill-buffer (get-buffer "*Warn about privacy*"))
21487 "Remember to cover the basics, that is, what you expected to happen and
21488 what in fact did happen. You don't know how to make a good report? See
21490 http://orgmode.org/manual/Feedback.html#Feedback
21492 Your bug report will be posted to the Org-mode mailing list.
21493 ------------------------------------------------------------------------")
21495 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21496 (replace-match "\\1Bug: \\3 [\\2]")))))
21499 (defun org-install-agenda-files-menu ()
21500 (let ((bl (buffer-list)))
21503 (set-buffer (pop bl))
21504 (if (derived-mode-p 'org-mode) (setq bl nil)))
21505 (when (derived-mode-p 'org-mode)
21507 '("Org") "File List for Agenda"
21510 ["Edit File List" (org-edit-agenda-file-list) t]
21511 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21512 ["Remove Current File from List" org-remove-file t]
21513 ["Cycle through agenda files" org-cycle-agenda-files t]
21514 ["Occur in all agenda files" org-occur-in-agenda-files t]
21516 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21520 (defun org-require-autoloaded-modules ()
21523 '(org-agenda org-archive org-attach org-clock org-colview org-id
21524 org-table org-timer)))
21527 (defun org-reload (&optional uncompiled)
21528 "Reload all org lisp files.
21529 With prefix arg UNCOMPILED, load the uncompiled versions."
21531 (require 'loadhist)
21532 (let* ((org-dir (org-find-library-dir "org"))
21533 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21534 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21535 (remove-re (mapconcat 'identity
21536 (mapcar (lambda (f) (concat "^" f "$"))
21537 (list (if (featurep 'xemacs)
21539 "org-colview-xemacs")
21540 "org" "org-loaddefs" "org-version"))
21542 (feats (delete-dups
21543 (mapcar 'file-name-sans-extension
21544 (mapcar 'file-name-nondirectory
21546 (mapcar 'feature-file
21553 (if (and (string-match feature-re f)
21554 (not (string-match remove-re f)))
21558 (list "org-version" "org")))
21559 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21560 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21561 load-uncore load-misses)
21564 (mapcar (lambda (f)
21565 (or (org-load-noerror-mustsuffix (concat org-dir f))
21566 (and (string= org-dir contrib-dir)
21567 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21568 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21569 (add-to-list 'load-uncore f 'append)
21574 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21575 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21577 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21578 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21579 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21582 (defun org-customize ()
21583 "Call the customize function with org as argument."
21585 (org-load-modules-maybe)
21586 (org-require-autoloaded-modules)
21587 (customize-browse 'org))
21589 (defun org-create-customize-menu ()
21590 "Create a full customization menu for Org-mode, insert it into the menu."
21592 (org-load-modules-maybe)
21593 (org-require-autoloaded-modules)
21594 (if (fboundp 'customize-menu-create)
21597 '("Org") "Customize"
21598 `(["Browse Org group" org-customize t]
21600 ,(customize-menu-create 'org)
21601 ["Set" Custom-set t]
21602 ["Save" Custom-save t]
21603 ["Reset to Current" Custom-reset-current t]
21604 ["Reset to Saved" Custom-reset-saved t]
21605 ["Reset to Standard Settings" Custom-reset-standard t]))
21606 (message "\"Org\"-menu now contains full customization menu"))
21607 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21609 ;;;; Miscellaneous stuff
21611 ;;; Generally useful functions
21613 (defsubst org-get-at-eol (property n)
21614 "Get text property PROPERTY at the end of line less N characters."
21615 (get-text-property (- (point-at-eol) n) property))
21617 (defun org-find-text-property-in-string (prop s)
21618 "Return the first non-nil value of property PROP in string S."
21619 (or (get-text-property 0 prop s)
21620 (get-text-property (or (next-single-property-change 0 prop s) 0)
21623 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21624 "Display the given MESSAGE as a warning."
21625 (if (fboundp 'display-warning)
21626 (display-warning 'org message
21627 (if (featurep 'xemacs) 'warning :warning))
21628 (let ((buf (get-buffer-create "*Org warnings*")))
21629 (with-current-buffer buf
21630 (goto-char (point-max))
21631 (insert "Warning (Org): " message)
21634 (display-buffer buf)
21637 (defun org-eval (form)
21638 "Eval FORM and return result."
21639 (condition-case error
21641 (error (format "%%![Error: %s]" error))))
21643 (defun org-in-clocktable-p ()
21644 "Check if the cursor is in a clocktable."
21645 (let ((pos (point)) start)
21648 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21649 (setq start (match-beginning 0))
21650 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21651 (>= (match-end 0) pos)
21654 (defun org-in-verbatim-emphasis ()
21656 (and (org-in-regexp org-emph-re 2)
21657 (>= (point) (match-beginning 3))
21658 (<= (point) (match-end 4))
21659 (member (match-string 3) '("=" "~")))))
21661 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21662 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21663 (if (and marker (marker-buffer marker)
21664 (buffer-live-p (marker-buffer marker)))
21666 (org-pop-to-buffer-same-window (marker-buffer marker))
21667 (if (or (> marker (point-max)) (< marker (point-min)))
21670 (org-show-context 'org-goto))
21672 (bookmark-jump bookmark)
21673 (error "Cannot find location"))))
21675 (defun org-quote-csv-field (s)
21676 "Quote field for inclusion in CSV material."
21677 (if (string-match "[\",]" s)
21678 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21681 (defun org-force-self-insert (N)
21682 "Needed to enforce self-insert under remapping."
21684 (self-insert-command N))
21686 (defun org-string-width (s)
21687 "Compute width of string, ignoring invisible characters.
21688 This ignores character with invisibility property `org-link', and also
21689 characters with property `org-cwidth', because these will become invisible
21690 upon the next fontification round."
21692 (when (or (eq t buffer-invisibility-spec)
21693 (assq 'org-link buffer-invisibility-spec))
21694 (while (setq b (text-property-any 0 (length s)
21695 'invisible 'org-link s))
21696 (setq s (concat (substring s 0 b)
21697 (substring s (or (next-single-property-change
21698 b 'invisible s) (length s)))))))
21699 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21700 (setq s (concat (substring s 0 b)
21701 (substring s (or (next-single-property-change
21702 b 'org-cwidth s) (length s))))))
21703 (setq l (string-width s) b -1)
21704 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21705 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21708 (defun org-shorten-string (s maxlength)
21709 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21710 If the string is shorter or has length MAXLENGTH, just return the
21711 original string. If it is longer, the functions finds a space in the
21712 string, breaks this string off at that locations and adds three dots
21713 as ellipsis. Including the ellipsis, the string will not be longer
21714 than MAXLENGTH. If finding a good breaking point in the string does
21715 not work, the string is just chopped off in the middle of a word
21717 (if (<= (length s) maxlength)
21719 (let* ((n (max (- maxlength 4) 1))
21720 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21721 (if (string-match re s)
21722 (concat (match-string 1 s) "...")
21723 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21725 (defun org-get-indentation (&optional line)
21726 "Get the indentation of the current line, interpreting tabs.
21727 When LINE is given, assume it represents a line and compute its indentation."
21729 (if (string-match "^ *" (org-remove-tabs line))
21732 (beginning-of-line 1)
21733 (skip-chars-forward " \t")
21734 (current-column))))
21736 (defun org-get-string-indentation (s)
21737 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21738 (let ((n -1) (i 0) (w tab-width) c)
21740 (while (< (setq n (1+ n)) (length s))
21741 (setq c (aref s n))
21742 (cond ((= c ?\ ) (setq i (1+ i)))
21743 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21744 (t (throw 'exit t)))))
21747 (defun org-remove-tabs (s &optional width)
21748 "Replace tabulators in S with spaces.
21749 Assumes that s is a single line, starting in column 0."
21750 (setq width (or width tab-width))
21751 (while (string-match "\t" s)
21752 (setq s (replace-match
21754 (- (* width (/ (+ (match-beginning 0) width) width))
21755 (match-beginning 0)) ?\ )
21759 (defun org-fix-indentation (line ind)
21760 "Fix indentation in LINE.
21761 IND is a cons cell with target and minimum indentation.
21762 If the current indentation in LINE is smaller than the minimum,
21763 leave it alone. If it is larger than ind, set it to the target."
21764 (let* ((l (org-remove-tabs line))
21765 (i (org-get-indentation l))
21766 (i1 (car ind)) (i2 (cdr ind)))
21767 (if (>= i i2) (setq l (substring line i2)))
21769 (concat (make-string i1 ?\ ) l)
21772 (defun org-remove-indentation (code &optional n)
21773 "Remove the maximum common indentation from the lines in CODE.
21774 N may optionally be the number of spaces to remove."
21777 (org-do-remove-indentation n)
21780 (defun org-do-remove-indentation (&optional n)
21781 "Remove the maximum common indentation from the buffer."
21782 (untabify (point-min) (point-max))
21783 (let ((min 10000) re)
21786 (goto-char (point-min))
21787 (while (re-search-forward "^ *[^ \n]" nil t)
21788 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21789 (unless (or (= min 0) (= min 10000))
21790 (setq re (format "^ \\{%d\\}" min))
21791 (goto-char (point-min))
21792 (while (re-search-forward re nil t)
21797 (defun org-fill-template (template alist)
21798 "Find each %key of ALIST in TEMPLATE and replace it."
21799 (let ((case-fold-search nil)
21801 (setq alist (sort (copy-sequence alist)
21802 (lambda (a b) (< (length (car a)) (length (car b))))))
21803 (while (setq entry (pop alist))
21805 (replace-regexp-in-string
21806 (concat "%" (regexp-quote (car entry)))
21807 (or (cdr entry) "") template t t)))
21810 (defun org-base-buffer (buffer)
21811 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21814 (or (buffer-base-buffer buffer)
21817 (defun org-wrap (string &optional width lines)
21818 "Wrap string to either a number of lines, or a width in characters.
21819 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21820 that costs. If there is a word longer than WIDTH, the text is actually
21821 wrapped to the length of that word.
21822 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21823 many lines, whatever width that takes.
21824 The return value is a list of lines, without newlines at the end."
21825 (let* ((words (org-split-string string "[ \t\n]+"))
21826 (maxword (apply 'max (mapcar 'org-string-width words)))
21829 (org-do-wrap words (max maxword width)))
21832 (setq ll (org-do-wrap words maxword))
21833 (if (<= (length ll) lines)
21836 (while (> (length ll) lines)
21838 (setq ll (org-do-wrap words w)))
21840 (t (error "Cannot wrap this")))))
21842 (defun org-do-wrap (words width)
21843 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21846 (setq line (pop words))
21847 (while (and words (< (+ (length line) (length (car words))) width))
21848 (setq line (concat line " " (pop words))))
21849 (setq lines (push line lines)))
21852 (defun org-split-string (string &optional separators)
21853 "Splits STRING into substrings at SEPARATORS.
21854 No empty strings are returned if there are matches at the beginning
21855 and end of string."
21856 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21860 (while (and (string-match rexp string
21862 (= start (match-beginning 0))
21863 (< start (length string)))
21865 (< (match-beginning 0) (length string)))
21867 (or (eq (match-beginning 0) 0)
21868 (and (eq (match-beginning 0) (match-end 0))
21869 (eq (match-beginning 0) start))
21871 (cons (substring string start (match-beginning 0))
21873 (setq start (match-end 0)))
21874 (or (eq start (length string))
21876 (cons (substring string start)
21880 (defun org-quote-vert (s)
21881 "Replace \"|\" with \"\\vert\"."
21882 (while (string-match "|" s)
21883 (setq s (replace-match "\\vert" t t s)))
21886 (defun org-uuidgen-p (s)
21887 "Is S an ID created by UUIDGEN?"
21888 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21890 (defun org-in-src-block-p (&optional inside)
21891 "Whether point is in a code source block.
21892 When INSIDE is non-nil, don't consider we are within a src block
21893 when point is at #+BEGIN_SRC or #+END_SRC."
21894 (let ((case-fold-search t) ov)
21895 (or (and (eq (get-char-property (point) 'src-block) t))
21899 (beginning-of-line)
21900 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21902 (defun org-context ()
21903 "Return a list of contexts of the current cursor position.
21904 If several contexts apply, all are returned.
21905 Each context entry is a list with a symbol naming the context, and
21906 two positions indicating start and end of the context. Possible
21909 :headline anywhere in a headline
21910 :headline-stars on the leading stars in a headline
21911 :todo-keyword on a TODO keyword (including DONE) in a headline
21912 :tags on the TAGS in a headline
21913 :priority on the priority cookie in a headline
21914 :item on the first line of a plain list item
21915 :item-bullet on the bullet/number of a plain list item
21916 :checkbox on the checkbox in a plain list item
21917 :table in an org-mode table
21918 :table-special on a special filed in a table
21919 :table-table in a table.el table
21920 :clocktable in a clocktable
21921 :src-block in a source block
21922 :link on a hyperlink
21923 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21924 :target on a <<target>>
21925 :radio-target on a <<<radio-target>>>
21926 :latex-fragment on a LaTeX fragment
21927 :latex-preview on a LaTeX fragment with overlaid preview image
21929 This function expects the position to be visible because it uses font-lock
21930 faces as a help to recognize the following contexts: :table-special, :link,
21932 (let* ((f (get-text-property (point) 'face))
21933 (faces (if (listp f) f (list f)))
21934 (case-fold-search t)
21935 (p (point)) clist o)
21936 ;; First the large context
21938 ((org-at-heading-p t)
21939 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21941 (beginning-of-line 1)
21942 (looking-at org-todo-line-tags-regexp))
21943 (push (org-point-in-group p 1 :headline-stars) clist)
21944 (push (org-point-in-group p 2 :todo-keyword) clist)
21945 (push (org-point-in-group p 4 :tags) clist))
21947 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21948 (if (looking-at "\\[#[A-Z0-9]\\]")
21949 (push (org-point-in-group p 0 :priority) clist)))
21952 (push (org-point-in-group p 2 :item-bullet) clist)
21953 (push (list :item (point-at-bol)
21954 (save-excursion (org-end-of-item) (point)))
21956 (and (org-at-item-checkbox-p)
21957 (push (org-point-in-group p 0 :checkbox) clist)))
21960 (push (list :table (org-table-begin) (org-table-end)) clist)
21961 (if (memq 'org-formula faces)
21962 (push (list :table-special
21963 (previous-single-property-change p 'face)
21964 (next-single-property-change p 'face)) clist)))
21965 ((org-at-table-p 'any)
21966 (push (list :table-table) clist)))
21969 (let ((case-fold-search t))
21970 ;; New the "medium" contexts: clocktables, source blocks
21971 (cond ((org-in-clocktable-p)
21972 (push (list :clocktable
21973 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21974 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21975 (match-beginning 1))
21976 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21977 (match-end 0))) clist))
21978 ((org-in-src-block-p)
21979 (push (list :src-block
21980 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21981 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21982 (match-beginning 1))
21983 (and (search-forward "#+END_SRC" nil t)
21984 (match-beginning 0))) clist))))
21987 ;; Now the small context
21989 ((org-at-timestamp-p)
21990 (push (org-point-in-group p 0 :timestamp) clist))
21991 ((memq 'org-link faces)
21993 (previous-single-property-change p 'face)
21994 (next-single-property-change p 'face)) clist))
21995 ((memq 'org-special-keyword faces)
21996 (push (list :keyword
21997 (previous-single-property-change p 'face)
21998 (next-single-property-change p 'face)) clist))
22000 (push (org-point-in-group p 0 :target) clist)
22001 (goto-char (1- (match-beginning 0)))
22002 (if (looking-at org-radio-target-regexp)
22003 (push (org-point-in-group p 0 :radio-target) clist))
22005 ((setq o (car (delq nil
22008 (if (memq x org-latex-fragment-image-overlays) x))
22009 (overlays-at (point))))))
22010 (push (list :latex-fragment
22011 (overlay-start o) (overlay-end o)) clist)
22012 (push (list :latex-preview
22013 (overlay-start o) (overlay-end o)) clist))
22014 ((org-inside-LaTeX-fragment-p)
22015 ;; FIXME: positions wrong.
22016 (push (list :latex-fragment (point) (point)) clist)))
22018 (setq clist (nreverse (delq nil clist)))
22021 ;; FIXME: Compare with at-regexp-p Do we need both?
22022 (defun org-in-regexp (re &optional nlines visually)
22023 "Check if point is inside a match of regexp.
22024 Normally only the current line is checked, but you can include NLINES extra
22025 lines both before and after point into the search.
22026 If VISUALLY is set, require that the cursor is not after the match but
22027 really on, so that the block visually is on the match."
22029 (let ((pos (point))
22030 (eol (point-at-eol (+ 1 (or nlines 0))))
22031 (inc (if visually 1 0)))
22033 (beginning-of-line (- 1 (or nlines 0)))
22034 (while (re-search-forward re eol t)
22035 (if (and (<= (match-beginning 0) pos)
22036 (>= (+ inc (match-end 0)) pos))
22037 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22039 (defun org-at-regexp-p (regexp)
22040 "Is point inside a match of REGEXP in the current line?"
22043 (let ((pos (point)) (end (point-at-eol)))
22044 (beginning-of-line 1)
22045 (while (re-search-forward regexp end t)
22046 (if (and (<= (match-beginning 0) pos)
22047 (>= (match-end 0) pos))
22051 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22052 "Non-nil when point is between matches of START-RE and END-RE.
22054 Also return a non-nil value when point is on one of the matches.
22056 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22057 buffer positions. Default values are the positions of headlines
22058 surrounding the point.
22060 The functions returns a cons cell whose car (resp. cdr) is the
22061 position before START-RE (resp. after END-RE)."
22063 (let ((pos (point))
22064 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22065 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22068 ;; Point is on a block when on START-RE or if START-RE can be
22069 ;; found before it...
22070 (and (or (org-at-regexp-p start-re)
22071 (re-search-backward start-re limit-up t))
22072 (setq beg (match-beginning 0))
22073 ;; ... and END-RE after it...
22074 (goto-char (match-end 0))
22075 (re-search-forward end-re limit-down t)
22076 (> (setq end (match-end 0)) pos)
22077 ;; ... without another START-RE in-between.
22078 (goto-char (match-beginning 0))
22079 (not (re-search-backward start-re (1+ beg) t))
22081 (cons beg end))))))
22083 (defun org-in-block-p (names)
22084 "Non-nil when point belongs to a block whose name belongs to NAMES.
22086 NAMES is a list of strings containing names of blocks.
22088 Return first block name matched, or nil. Beware that in case of
22089 nested blocks, the returned name may not belong to the closest
22093 (let ((case-fold-search t)
22094 (lim-up (save-excursion (outline-previous-heading)))
22095 (lim-down (save-excursion (outline-next-heading))))
22096 (mapc (lambda (name)
22097 (let ((n (regexp-quote name)))
22098 (when (org-between-regexps-p
22099 (concat "^[ \t]*#\\+begin_" n)
22100 (concat "^[ \t]*#\\+end_" n)
22106 (defun org-in-drawer-p ()
22107 "Non-nil if point is within a drawer.
22108 If point is within a drawer, return it, as parsed data."
22109 (let ((element (save-match-data (org-element-at-point))))
22110 (while (and element (not (memq (org-element-type element)
22111 '(drawer property-drawer))))
22112 (setq element (org-element-property :parent element)))
22115 (defun org-occur-in-agenda-files (regexp &optional nlines)
22116 "Call `multi-occur' with buffers for all agenda files."
22117 (interactive "sOrg-files matching: \np")
22118 (let* ((files (org-agenda-files))
22119 (tnames (mapcar 'file-truename files))
22120 (extra org-agenda-text-search-extra-files)
22122 (when (eq (car extra) 'agenda-archives)
22123 (setq extra (cdr extra))
22124 (setq files (org-add-archive-files files)))
22125 (while (setq f (pop extra))
22126 (unless (member (file-truename f) tnames)
22127 (add-to-list 'files f 'append)
22128 (add-to-list 'tnames (file-truename f) 'append)))
22130 (mapcar (lambda (x)
22131 (with-current-buffer
22132 (or (get-file-buffer x) (find-file-noselect x))
22138 (if (boundp 'occur-mode-find-occurrence-hook)
22140 (add-hook 'occur-mode-find-occurrence-hook
22142 (when (derived-mode-p 'org-mode)
22145 (defadvice occur-mode-goto-occurrence
22146 (after org-occur-reveal activate)
22147 (and (derived-mode-p 'org-mode) (org-reveal)))
22148 (defadvice occur-mode-goto-occurrence-other-window
22149 (after org-occur-reveal activate)
22150 (and (derived-mode-p 'org-mode) (org-reveal)))
22151 (defadvice occur-mode-display-occurrence
22152 (after org-occur-reveal activate)
22153 (when (derived-mode-p 'org-mode)
22154 (let ((pos (occur-mode-find-occurrence)))
22155 (with-current-buffer (marker-buffer pos)
22160 (defun org-occur-link-in-agenda-files ()
22161 "Create a link and search for it in the agendas.
22162 The link is not stored in `org-stored-links', it is just created
22163 for the search purpose."
22165 (let ((link (condition-case nil
22166 (org-store-link nil)
22167 (error "Unable to create a link to here"))))
22168 (org-occur-in-agenda-files (regexp-quote link))))
22170 (defun org-reverse-string (string)
22171 "Return the reverse of STRING."
22172 (apply 'string (reverse (string-to-list string))))
22174 ;; defsubst org-uniquify must be defined before first use
22176 (defun org-uniquify-alist (alist)
22177 "Merge elements of ALIST with the same key.
22179 For example, in this alist:
22181 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22182 => '((a 1 3) (b 2))
22184 merge (a 1) and (a 3) into (a 1 3).
22186 The function returns the new ALIST."
22191 (if (not (assoc (car e) rtn))
22193 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22194 (setq rtn (assq-delete-all (car e) rtn))
22199 (defun org-delete-all (elts list)
22200 "Remove all elements in ELTS from LIST."
22202 (setq list (delete (pop elts) list)))
22205 (defun org-count (cl-item cl-seq)
22206 "Count the number of occurrences of ITEM in SEQ.
22207 Taken from `count' in cl-seq.el with all keyword arguments removed."
22208 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22209 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22210 (while (< cl-start cl-end)
22211 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22212 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22213 (setq cl-start (1+ cl-start)))
22216 (defun org-remove-if (predicate seq)
22217 "Remove everything from SEQ that fulfills PREDICATE."
22221 (if (not (funcall predicate e)) (push e res)))
22224 (defun org-remove-if-not (predicate seq)
22225 "Remove everything from SEQ that does not fulfill PREDICATE."
22229 (if (funcall predicate e) (push e res)))
22232 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22233 "Reduce two-argument FUNCTION across SEQ.
22234 Taken from `reduce' in cl-seq.el with all keyword arguments but
22235 \":initial-value\" removed."
22236 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22237 (cadr (memq :initial-value cl-keys)))
22238 (cl-seq (pop cl-seq))
22239 (t (funcall cl-func)))))
22241 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22244 (defun org-every (pred seq)
22245 "Return true if PREDICATE is true of every element of SEQ.
22246 Adapted from `every' in cl.el."
22248 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22251 (defun org-some (pred seq)
22252 "Return true if PREDICATE is true of any element of SEQ.
22253 Adapted from `some' in cl.el."
22255 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22258 (defun org-back-over-empty-lines ()
22259 "Move backwards over whitespace, to the beginning of the first empty line.
22260 Returns the number of empty lines passed."
22261 (let ((pos (point)))
22262 (if (cdr (assoc 'heading org-blank-before-new-entry))
22263 (skip-chars-backward " \t\n\r")
22265 (forward-line -1)))
22266 (beginning-of-line 2)
22267 (goto-char (min (point) pos))
22268 (count-lines (point) pos)))
22270 (defun org-skip-whitespace ()
22271 (skip-chars-forward " \t\n\r"))
22273 (defun org-point-in-group (point group &optional context)
22274 "Check if POINT is in match-group GROUP.
22275 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22276 match. If the match group does not exist or point is not inside it,
22278 (and (match-beginning group)
22279 (>= point (match-beginning group))
22280 (<= point (match-end group))
22282 (list context (match-beginning group) (match-end group))
22285 (defun org-switch-to-buffer-other-window (&rest args)
22286 "Switch to buffer in a second window on the current frame.
22287 In particular, do not allow pop-up frames.
22288 Returns the newly created buffer."
22290 (apply 'switch-to-buffer-other-window args)))
22292 (defun org-combine-plists (&rest plists)
22293 "Create a single property list from all plists in PLISTS.
22294 The process starts by copying the first list, and then setting properties
22295 from the other lists. Settings in the last list are the most significant
22296 ones and overrule settings in the other lists."
22297 (let ((rtn (copy-sequence (pop plists)))
22300 (setq ls (pop plists))
22302 (setq p (pop ls) v (pop ls))
22303 (setq rtn (plist-put rtn p v))))
22306 (defun org-replace-escapes (string table)
22307 "Replace %-escapes in STRING with values in TABLE.
22308 TABLE is an association list with keys like \"%a\" and string values.
22309 The sequences in STRING may contain normal field width and padding information,
22310 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22311 so values can contain further %-escapes if they are define later in TABLE."
22312 (let ((tbl (copy-alist table))
22313 (case-fold-search nil)
22316 (while (setq e (pop tbl))
22317 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22318 (when (and (cdr e) (string-match re (cdr e)))
22319 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22321 (add-text-properties 0 3 (list 'sref sref) safe)
22322 (setcdr e (replace-match safe t t (cdr e)))))
22323 (while (string-match re string)
22324 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22326 (setq string (replace-match rpl t t string))))
22327 (while (setq pchg (next-property-change pchg string))
22328 (let ((sref (get-text-property pchg 'sref string)))
22329 (when (and sref (string-match "SREF" string pchg))
22330 (setq string (replace-match sref t t string)))))
22333 (defun org-sublist (list start end)
22334 "Return a section of LIST, from START to END.
22335 Counting starts at 1."
22336 (let (rtn (c start))
22337 (setq list (nthcdr (1- start) list))
22338 (while (and list (<= c end))
22339 (push (pop list) rtn)
22343 (defun org-find-base-buffer-visiting (file)
22344 "Like `find-buffer-visiting' but always return the base buffer and
22345 not an indirect buffer."
22346 (let ((buf (or (get-file-buffer file)
22347 (find-buffer-visiting file))))
22349 (or (buffer-base-buffer buf) buf)
22352 (defun org-image-file-name-regexp (&optional extensions)
22353 "Return regexp matching the file names of images.
22354 If EXTENSIONS is given, only match these."
22355 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22356 (image-file-name-regexp)
22357 (let ((image-file-name-extensions
22359 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22360 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22362 (regexp-opt (nconc (mapcar 'upcase
22363 image-file-name-extensions)
22364 image-file-name-extensions)
22368 (defun org-file-image-p (file &optional extensions)
22369 "Return non-nil if FILE is an image."
22371 (string-match (org-image-file-name-regexp extensions) file)))
22373 (defun org-get-cursor-date (&optional with-time)
22374 "Return the date at cursor in as a time.
22375 This works in the calendar and in the agenda, anywhere else it just
22376 returns the current time.
22377 If WITH-TIME is non-nil, returns the time of the event at point (in
22378 the agenda) or the current time of the day."
22379 (let (date day defd tp tm hod mod)
22381 (setq tp (get-text-property (point) 'time))
22382 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22383 (setq hod (string-to-number (match-string 1 tp))
22384 mod (string-to-number (match-string 2 tp))))
22385 (or tp (setq hod (nth 2 (decode-time (current-time)))
22386 mod (nth 1 (decode-time (current-time))))))
22388 ((eq major-mode 'calendar-mode)
22389 (setq date (calendar-cursor-to-date)
22390 defd (encode-time 0 (or mod 0) (or hod 0)
22391 (nth 1 date) (nth 0 date) (nth 2 date))))
22392 ((eq major-mode 'org-agenda-mode)
22393 (setq day (get-text-property (point) 'day))
22395 (setq date (calendar-gregorian-from-absolute day)
22396 defd (encode-time 0 (or mod 0) (or hod 0)
22397 (nth 1 date) (nth 0 date) (nth 2 date))))))
22398 (or defd (current-time))))
22400 (defun org-mark-subtree (&optional up)
22401 "Mark the current subtree.
22402 This puts point at the start of the current subtree, and mark at
22403 the end. If a numeric prefix UP is given, move up into the
22404 hierarchy of headlines by UP levels before marking the subtree."
22406 (org-with-limited-levels
22407 (cond ((org-at-heading-p) (beginning-of-line))
22408 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22409 (t (outline-previous-visible-heading 1))))
22410 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22411 (if (org-called-interactively-p 'any)
22412 (call-interactively 'org-mark-element)
22413 (org-mark-element)))
22418 (defun org--get-expected-indentation (element contentsp)
22419 "Expected indentation column for current line, according to ELEMENT.
22420 ELEMENT is an element containing point. CONTENTSP is non-nil
22421 when indentation is to be computed according to contents of
22423 (let ((type (org-element-type element))
22424 (start (org-element-property :begin element)))
22425 (org-with-wide-buffer
22429 (footnote-definition 0)
22430 ((headline inlinetask nil)
22431 (if (not org-adapt-indentation) 0
22432 (let ((level (org-current-level)))
22433 (if level (1+ level) 0))))
22435 (org-list-item-body-column
22436 (org-element-property :post-affiliated element)))
22439 (goto-char (org-element-property :post-affiliated element))
22440 (org-get-indentation)))
22443 (org-get-indentation))))
22444 ((memq type '(headline inlinetask nil))
22445 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22446 (org--get-expected-indentation element t)
22448 ((eq type 'footnote-definition) 0)
22449 ;; First paragraph of a footnote definition or an item.
22450 ;; Indent like parent.
22451 ((< (line-beginning-position) start)
22452 (org--get-expected-indentation
22453 (org-element-property :parent element) t))
22454 ;; At first line: indent according to previous sibling, if any,
22455 ;; ignoring footnote definitions and inline tasks, or parent's
22457 ((= (line-beginning-position) start)
22460 (if (= (point-min) start) (throw 'exit 0)
22461 (goto-char (1- start))
22462 (let* ((previous (org-element-at-point))
22464 (while (and parent (<= (org-element-property :end parent) start))
22465 (setq previous parent
22466 parent (org-element-property :parent parent)))
22468 ((not previous) (throw 'exit 0))
22469 ((> (org-element-property :end previous) start)
22470 (throw 'exit (org--get-expected-indentation previous t)))
22471 ((memq (org-element-type previous)
22472 '(footnote-definition inlinetask))
22473 (setq start (org-element-property :begin previous)))
22474 (t (goto-char (org-element-property :begin previous))
22476 (if (bolp) (org-get-indentation)
22477 ;; At first paragraph in an item or
22478 ;; a footnote definition.
22479 (org--get-expected-indentation
22480 (org-element-property :parent previous) t))))))))))
22481 ;; Otherwise, move to the first non-blank line above.
22483 (beginning-of-line)
22484 (let ((pos (point)))
22485 (skip-chars-backward " \r\t\n")
22487 ;; Two blank lines end a footnote definition or a plain
22488 ;; list. When we indent an empty line after them, the
22489 ;; containing list or footnote definition is over, so it
22490 ;; qualifies as a previous sibling. Therefore, we indent
22491 ;; like its first line.
22492 ((and (memq type '(footnote-definition plain-list))
22493 (> (count-lines (point) pos) 2))
22495 (org-get-indentation))
22496 ;; Line above is the first one of a paragraph at the
22497 ;; beginning of an item or a footnote definition. Indent
22499 ((< (line-beginning-position) start)
22500 (org--get-expected-indentation
22501 (org-element-property :parent element) t))
22502 ;; POS is after contents in a greater element. Indent like
22503 ;; the beginning of the element.
22505 ;; As a special case, if point is at the end of a footnote
22506 ;; definition or an item, indent like the very last element
22508 ((let ((cend (org-element-property :contents-end element)))
22509 (and cend (<= cend pos)))
22510 (if (memq type '(footnote-definition item plain-list))
22511 (org--get-expected-indentation (org-element-at-point) nil)
22513 (org-get-indentation)))
22514 ;; In any other case, indent like the current line.
22515 (t (org-get-indentation)))))))))
22517 (defun org--align-node-property ()
22518 "Align node property at point.
22519 Alignment is done according to `org-property-format', which see."
22520 (when (save-excursion
22521 (beginning-of-line)
22522 (looking-at org-property-re))
22524 (concat (match-string 4)
22526 (format org-property-format (match-string 1) (match-string 3))))
22529 (defun org-indent-line ()
22530 "Indent line depending on context.
22532 Indentation is done according to the following rules:
22534 - Footnote definitions, headlines and inline tasks have to
22537 - On the very first line of an element, consider, in order, the
22538 next rules until one matches:
22540 1. If there's a sibling element before, ignoring footnote
22541 definitions and inline tasks, indent like its first line.
22543 2. If element has a parent, indent like its contents. More
22544 precisely, if parent is an item, indent after the
22545 description part, if any, or the bullet (see
22546 ``org-list-description-max-indent'). Else, indent like
22547 parent's first line.
22549 3. Otherwise, indent relatively to current level, if
22550 `org-adapt-indentation' is non-nil, or to left margin.
22552 - On a blank line at the end of a plain list, an item, or
22553 a footnote definition, indent like the very last element
22556 - In the code part of a source block, use language major mode
22557 to indent current line if `org-src-tab-acts-natively' is
22558 non-nil. If it is nil, do nothing.
22560 - Otherwise, indent like the first non-blank line above.
22562 The function doesn't indent an item as it could break the whole
22563 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22564 \\[org-shiftmetaright].
22566 Also align node properties according to `org-property-format'."
22570 (let ((indent-line-function
22571 (cadadr (assq 'indent-line-function org-fb-vars))))
22572 (indent-according-to-mode)))
22573 ((org-at-heading-p) 'noindent)
22575 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22576 (type (org-element-type element)))
22577 (cond ((and (memq type '(plain-list item))
22578 (= (line-beginning-position)
22579 (org-element-property :post-affiliated element)))
22581 ((and (eq type 'src-block)
22582 org-src-tab-acts-natively
22583 (> (line-beginning-position)
22584 (org-element-property :post-affiliated element))
22585 (< (line-beginning-position)
22586 (org-with-wide-buffer
22587 (goto-char (org-element-property :end element))
22588 (skip-chars-backward " \r\t\n")
22589 (line-beginning-position))))
22590 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22591 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22593 (let ((column (org--get-expected-indentation element nil)))
22594 ;; Preserve current column.
22595 (if (<= (current-column) (current-indentation))
22596 (org-indent-line-to column)
22597 (save-excursion (org-indent-line-to column))))
22598 ;; Align node property. Also preserve current column.
22599 (when (eq type 'node-property)
22600 (let ((column (current-column)))
22601 (org--align-node-property)
22602 (org-move-to-column column)))))))))
22604 (defun org-indent-region (start end)
22605 "Indent each non-blank line in the region.
22606 Called from a program, START and END specify the region to
22607 indent. The function will not indent contents of example blocks,
22608 verse blocks and export blocks as leading white spaces are
22609 assumed to be significant there."
22613 (skip-chars-forward " \r\t\n")
22614 (unless (eobp) (beginning-of-line))
22617 ;; Set IND as indentation for all lines between point and
22618 ;; POS or END, whichever comes first. Blank lines are
22619 ;; ignored. Leave point after POS once done.
22620 (let ((limit (copy-marker (min end pos))))
22621 (while (< (point) limit)
22622 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22624 (set-marker limit nil))))
22625 (end (copy-marker end)))
22626 (while (< (point) end)
22627 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22628 (let* ((element (org-element-at-point))
22629 (type (org-element-type element))
22630 (element-end (copy-marker (org-element-property :end element)))
22631 (ind (org--get-expected-indentation element nil)))
22633 ((or (memq type '(paragraph table table-row))
22634 (not (or (org-element-property :contents-begin element)
22636 '(example-block export-block src-block)))))
22637 ;; Elements here are indented as a single block. Also
22638 ;; align node properties.
22639 (when (eq type 'node-property)
22640 (org--align-node-property)
22641 (beginning-of-line))
22642 (funcall indent-to ind element-end))
22644 ;; Elements in this category consist of three parts:
22645 ;; before the contents, the contents, and after the
22646 ;; contents. The contents are treated specially,
22647 ;; according to the element type, or not indented at
22648 ;; all. Other parts are indented as a single block.
22649 (let* ((post (copy-marker
22650 (org-element-property :post-affiliated element)))
22654 ((not (org-element-property :contents-begin element))
22655 ;; Fake contents for source blocks.
22656 (org-with-wide-buffer
22660 ((memq type '(footnote-definition item plain-list))
22661 ;; Contents in these elements could start on
22662 ;; the same line as the beginning of the
22663 ;; element. Make sure we start indenting
22664 ;; from the second line.
22665 (org-with-wide-buffer
22668 (skip-chars-forward " \r\t\n")
22669 (if (eobp) (point) (line-beginning-position))))
22670 (t (org-element-property :contents-begin element)))))
22672 (or (org-element-property :contents-end element)
22673 ;; Fake contents for source blocks.
22674 (org-with-wide-buffer
22675 (goto-char element-end)
22676 (skip-chars-backward " \r\t\n")
22677 (line-beginning-position))))))
22678 ;; Do not change items indentation individually as it
22679 ;; might break the list as a whole. On the other
22680 ;; hand, when at a plain list, indent it as a whole.
22681 (cond ((eq type 'plain-list)
22682 (let ((offset (- ind (org-get-indentation))))
22683 (unless (zerop offset)
22684 (indent-rigidly (org-element-property :begin element)
22685 (org-element-property :end element)
22688 ((eq type 'item) (goto-char cbeg))
22689 (t (funcall indent-to ind cbeg)))
22690 (when (< (point) end)
22692 ((example-block export-block verse-block))
22694 ;; In a source block, indent source code
22695 ;; according to language major mode, but only if
22696 ;; `org-src-tab-acts-natively' is non-nil.
22697 (when (and (< (point) end) org-src-tab-acts-natively)
22699 (let (org-src-strip-leading-and-trailing-blank-lines
22700 ;; Region boundaries in edit buffer.
22701 (start (1+ (- (point) cbeg)))
22702 (end (- (min cend end) cbeg)))
22703 (org-babel-do-in-edit-buffer
22704 (indent-region start end))))))
22705 (t (org-indent-region (point) (min cend end))))
22706 (goto-char (min cend end))
22707 (when (< (point) end) (funcall indent-to ind element-end)))
22708 (set-marker post nil)
22709 (set-marker cbeg nil)
22710 (set-marker cend nil))))
22711 (set-marker element-end nil))))
22712 (set-marker end nil))))
22714 (defun org-indent-drawer ()
22715 "Indent the drawer at point."
22717 (unless (save-excursion
22718 (beginning-of-line)
22719 (org-looking-at-p org-drawer-regexp))
22720 (user-error "Not at a drawer"))
22721 (let ((element (org-element-at-point)))
22722 (unless (memq (org-element-type element) '(drawer property-drawer))
22723 (user-error "Not at a drawer"))
22724 (org-with-wide-buffer
22725 (org-indent-region (org-element-property :begin element)
22726 (org-element-property :end element))))
22727 (message "Drawer at point indented"))
22729 (defun org-indent-block ()
22730 "Indent the block at point."
22732 (unless (save-excursion
22733 (beginning-of-line)
22734 (let ((case-fold-search t))
22735 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22736 (user-error "Not at a block"))
22737 (let ((element (org-element-at-point)))
22738 (unless (memq (org-element-type element)
22739 '(comment-block center-block dynamic-block example-block
22740 export-block quote-block special-block
22741 src-block verse-block))
22742 (user-error "Not at a block"))
22743 (org-with-wide-buffer
22744 (org-indent-region (org-element-property :begin element)
22745 (org-element-property :end element))))
22746 (message "Block at point indented"))
22751 ;; We use our own fill-paragraph and auto-fill functions.
22753 ;; `org-fill-paragraph' relies on adaptive filling and context
22754 ;; checking. Appropriate `fill-prefix' is computed with
22755 ;; `org-adaptive-fill-function'.
22757 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22758 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22759 ;; `org-adaptive-fill-function' value. Internally,
22760 ;; `org-comment-line-break-function' breaks the line.
22762 ;; `org-setup-filling' installs filling and auto-filling related
22763 ;; variables during `org-mode' initialization.
22765 (defvar org-element-paragraph-separate) ; org-element.el
22766 (defun org-setup-filling ()
22767 (require 'org-element)
22768 ;; Prevent auto-fill from inserting unwanted new items.
22769 (when (boundp 'fill-nobreak-predicate)
22771 'fill-nobreak-predicate
22773 (append fill-nobreak-predicate
22774 '(org-fill-line-break-nobreak-p
22775 org-fill-paragraph-with-timestamp-nobreak-p)))))
22776 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22777 (org-set-local 'paragraph-start paragraph-ending)
22778 (org-set-local 'paragraph-separate paragraph-ending))
22779 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22780 (org-set-local 'auto-fill-inhibit-regexp nil)
22781 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22782 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22783 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22785 (defun org-fill-line-break-nobreak-p ()
22786 "Non-nil when a new line at point would create an Org line break."
22788 (skip-chars-backward "[ \t]")
22789 (skip-chars-backward "\\\\")
22790 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22792 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22793 "Non-nil when a new line at point would split a timestamp."
22794 (and (org-at-timestamp-p t)
22795 (not (looking-at org-ts-regexp-both))))
22797 (declare-function message-in-body-p "message" ())
22798 (defvar orgtbl-line-start-regexp) ; From org-table.el
22799 (defun org-adaptive-fill-function ()
22800 "Compute a fill prefix for the current line.
22801 Return fill prefix, as a string, or nil if current line isn't
22802 meant to be filled. For convenience, if `adaptive-fill-regexp'
22803 matches in paragraphs or comments, use it."
22805 (when (derived-mode-p 'message-mode)
22807 (beginning-of-line)
22808 (cond ((or (not (message-in-body-p))
22809 (looking-at orgtbl-line-start-regexp))
22811 ((looking-at message-cite-prefix-regexp)
22812 (throw 'exit (match-string-no-properties 0)))
22813 ((looking-at org-outline-regexp)
22814 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22815 (org-with-wide-buffer
22816 (unless (org-at-heading-p)
22817 (let* ((p (line-beginning-position))
22818 (element (save-excursion
22819 (beginning-of-line)
22820 (org-element-at-point)))
22821 (type (org-element-type element))
22822 (post-affiliated (org-element-property :post-affiliated element)))
22823 (unless (< p post-affiliated)
22827 (beginning-of-line)
22828 (looking-at "[ \t]*")
22829 (concat (match-string 0) "# ")))
22830 (footnote-definition "")
22832 (make-string (org-list-item-body-column post-affiliated) ?\s))
22834 ;; Fill prefix is usually the same as the current line,
22835 ;; unless the paragraph is at the beginning of an item.
22836 (let ((parent (org-element-property :parent element)))
22838 (beginning-of-line)
22839 (cond ((eq (org-element-type parent) 'item)
22840 (make-string (org-list-item-body-column
22841 (org-element-property :begin parent))
22843 ((and adaptive-fill-regexp
22845 ;; `adaptive-fill-function' to let
22846 ;; `fill-context-prefix' handle
22847 ;; `adaptive-fill-regexp' variable.
22848 (let (adaptive-fill-function)
22849 (fill-context-prefix
22851 (org-element-property :end element)))))
22852 ((looking-at "[ \t]+") (match-string 0))
22855 ;; Only fill contents if P is within block boundaries.
22856 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22859 (cend (save-excursion
22860 (goto-char (org-element-property :end element))
22861 (skip-chars-backward " \r\t\n")
22862 (line-beginning-position))))
22863 (when (and (>= p cbeg) (< p cend))
22864 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22868 (declare-function message-goto-body "message" ())
22869 (defvar message-cite-prefix-regexp) ; From message.el
22870 (defun org-fill-paragraph (&optional justify)
22871 "Fill element at point, when applicable.
22873 This function only applies to comment blocks, comments, example
22874 blocks and paragraphs. Also, as a special case, re-align table
22875 when point is at one.
22877 If JUSTIFY is non-nil (interactively, with prefix argument),
22878 justify as well. If `sentence-end-double-space' is non-nil, then
22879 period followed by one space does not end a sentence, so don't
22880 break a line there. The variable `fill-column' controls the
22883 For convenience, when point is at a plain list, an item or
22884 a footnote definition, try to fill the first paragraph within."
22886 (if (and (derived-mode-p 'message-mode)
22887 (or (not (message-in-body-p))
22888 (save-excursion (move-beginning-of-line 1)
22889 (looking-at message-cite-prefix-regexp))))
22890 ;; First ensure filling is correct in message-mode.
22891 (let ((fill-paragraph-function
22892 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22893 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22894 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22895 (paragraph-separate
22896 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22897 (fill-paragraph nil))
22898 (with-syntax-table org-mode-transpose-word-syntax-table
22899 ;; Move to end of line in order to get the first paragraph
22900 ;; within a plain list or a footnote definition.
22901 (let ((element (save-excursion
22903 (or (ignore-errors (org-element-at-point))
22904 (user-error "An element cannot be parsed line %d"
22905 (line-number-at-pos (point)))))))
22906 ;; First check if point is in a blank line at the beginning of
22907 ;; the buffer. In that case, ignore filling.
22908 (case (org-element-type element)
22909 ;; Use major mode filling function is src blocks.
22910 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22911 ;; Align Org tables, leave table.el tables as-is.
22912 (table-row (org-table-align) t)
22914 (when (eq (org-element-property :type element) 'org)
22916 (goto-char (org-element-property :post-affiliated element))
22917 (org-table-align)))
22920 ;; Paragraphs may contain `line-break' type objects.
22921 (let ((beg (max (point-min)
22922 (org-element-property :contents-begin element)))
22923 (end (min (point-max)
22924 (org-element-property :contents-end element))))
22925 ;; Do nothing if point is at an affiliated keyword.
22926 (if (< (line-end-position) beg) t
22927 (when (derived-mode-p 'message-mode)
22928 ;; In `message-mode', do not fill following citation
22929 ;; in current paragraph nor text before message body.
22930 (let ((body-start (save-excursion (message-goto-body))))
22931 (when body-start (setq beg (max body-start beg))))
22932 (when (save-excursion
22934 (concat "^" message-cite-prefix-regexp) end t))
22935 (setq end (match-beginning 0))))
22936 ;; Fill paragraph, taking line breaks into account.
22939 (let ((cuts (list beg)))
22940 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22941 (when (eq 'line-break
22943 (save-excursion (backward-char)
22944 (org-element-context))))
22945 (push (point) cuts)))
22946 (dolist (c (delq end cuts))
22947 (fill-region-as-paragraph c end justify)
22950 ;; Contents of `comment-block' type elements should be
22951 ;; filled as plain text, but only if point is within block
22954 (let* ((case-fold-search t)
22955 (beg (save-excursion
22956 (goto-char (org-element-property :begin element))
22957 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22960 (end (save-excursion
22961 (goto-char (org-element-property :end element))
22962 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22963 (line-beginning-position))))
22964 (if (or (< (point) beg) (> (point) end)) t
22965 (fill-region-as-paragraph
22966 (save-excursion (end-of-line)
22967 (re-search-backward "^[ \t]*$" beg 'move)
22968 (line-beginning-position))
22969 (save-excursion (beginning-of-line)
22970 (re-search-forward "^[ \t]*$" end 'move)
22971 (line-beginning-position))
22975 (let ((begin (org-element-property :post-affiliated element))
22976 (end (org-element-property :end element)))
22977 (when (and (>= (point) begin) (<= (point) end))
22978 (let ((begin (save-excursion
22980 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22981 (progn (forward-line) (point))
22983 (end (save-excursion
22985 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22986 (1- (line-beginning-position))
22987 (skip-chars-backward " \r\t\n")
22988 (line-end-position)))))
22989 ;; Do not fill comments when at a blank line.
22990 (when (> end begin)
22993 (beginning-of-line)
22994 (looking-at "[ \t]*#")
22995 (let ((comment-prefix (match-string 0)))
22996 (goto-char (match-end 0))
22997 (if (looking-at adaptive-fill-regexp)
22998 (concat comment-prefix (match-string 0))
22999 (concat comment-prefix " "))))))
23001 (fill-region-as-paragraph begin end justify))))))
23003 ;; Ignore every other element.
23006 (defun org-auto-fill-function ()
23007 "Auto-fill function."
23008 ;; Check if auto-filling is meaningful.
23009 (let ((fc (current-fill-column)))
23010 (when (and fc (> (current-column) fc))
23011 (let* ((fill-prefix (org-adaptive-fill-function))
23012 ;; Enforce empty fill prefix, if required. Otherwise, it
23013 ;; will be computed again.
23014 (adaptive-fill-mode (not (equal fill-prefix ""))))
23015 (when fill-prefix (do-auto-fill))))))
23017 (defun org-comment-line-break-function (&optional soft)
23018 "Break line at point and indent, continuing comment if within one.
23019 The inserted newline is marked hard if variable
23020 `use-hard-newlines' is true, unless optional argument SOFT is
23022 (if soft (insert-and-inherit ?\n) (newline 1))
23023 (save-excursion (forward-char -1) (delete-horizontal-space))
23024 (delete-horizontal-space)
23025 (indent-to-left-margin)
23026 (insert-before-markers-and-inherit fill-prefix))
23029 ;;; Fixed Width Areas
23031 (defun org-toggle-fixed-width ()
23032 "Toggle fixed-width markup.
23034 Add or remove fixed-width markup on current line, whenever it
23035 makes sense. Return an error otherwise.
23037 If a region is active and if it contains only fixed-width areas
23038 or blank lines, remove all fixed-width markup in it. If the
23039 region contains anything else, convert all non-fixed-width lines
23040 to fixed-width ones.
23042 Blank lines at the end of the region are ignored unless the
23043 region only contains such lines."
23045 (if (not (org-region-active-p))
23048 ;; Remove fixed width marker only in a fixed-with element.
23050 ;; Add fixed width maker in paragraphs, in blank lines after
23051 ;; elements or at the beginning of a headline or an inlinetask,
23052 ;; and before any one-line elements (e.g., a clock).
23054 (beginning-of-line)
23055 (let* ((element (org-element-at-point))
23056 (type (org-element-type element)))
23058 ((and (eq type 'fixed-width)
23059 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23061 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23062 ((and (memq type '(babel-call clock comment diary-sexp headline
23063 horizontal-rule keyword paragraph
23065 (<= (org-element-property :post-affiliated element) (point)))
23066 (skip-chars-forward " \t")
23068 ((and (org-looking-at-p "[ \t]*$")
23069 (or (eq type 'inlinetask)
23071 (skip-chars-forward " \r\t\n")
23072 (<= (org-element-property :end element) (point)))))
23073 (delete-region (point) (line-end-position))
23076 (t (user-error "Cannot insert a fixed-width line here")))))
23078 (let* ((begin (save-excursion
23079 (goto-char (region-beginning))
23080 (line-beginning-position)))
23083 (goto-char (region-end))
23084 (unless (eolp) (beginning-of-line))
23085 (if (save-excursion (re-search-backward "\\S-" begin t))
23086 (progn (skip-chars-backward " \r\t\n") (point))
23092 (skip-chars-forward " \r\t\n")
23093 (when (eobp) (throw 'not-all-p nil))
23094 (while (< (point) end)
23095 (let ((element (org-element-at-point)))
23096 (if (eq (org-element-type element) 'fixed-width)
23097 (goto-char (org-element-property :end element))
23098 (throw 'not-all-p nil))))
23100 (if all-fixed-width-p
23103 (while (< (point) end)
23104 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23107 (if (= (line-end-position) (match-end 0)) 0 1)))
23109 (let ((min-ind (point-max)))
23110 ;; Find minimum indentation across all lines.
23113 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23116 (while (< (point) end)
23117 (unless (org-looking-at-p "[ \t]*$")
23118 (let ((ind (org-get-indentation)))
23119 (setq min-ind (min min-ind ind))
23120 (when (zerop ind) (throw 'zerop t))))
23122 ;; Loop over all lines and add fixed-width markup everywhere
23123 ;; but in fixed-width lines.
23126 (while (< (point) end)
23128 ((org-at-heading-p)
23131 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23134 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23135 (let* ((element (org-element-at-point))
23136 (element-end (org-element-property :end element)))
23137 (if (eq (org-element-type element) 'fixed-width)
23138 (progn (goto-char element-end)
23139 (skip-chars-backward " \r\t\n")
23141 (let ((limit (min end element-end)))
23142 (while (< (point) limit)
23143 (org-move-to-column min-ind t)
23145 (forward-line))))))
23147 (org-move-to-column min-ind t)
23149 (forward-line)))))))
23150 (set-marker end nil))))
23155 ;; Org comments syntax is quite complex. It requires the entire line
23156 ;; to be just a comment. Also, even with the right syntax at the
23157 ;; beginning of line, some some elements (i.e. verse-block or
23158 ;; example-block) don't accept comments. Usual Emacs comment commands
23159 ;; cannot cope with those requirements. Therefore, Org replaces them.
23161 ;; Org still relies on `comment-dwim', but cannot trust
23162 ;; `comment-only-p'. So, `comment-region-function' and
23163 ;; `uncomment-region-function' both point
23164 ;; to`org-comment-or-uncomment-region'. Eventually,
23165 ;; `org-insert-comment' takes care of insertion of comments at the
23166 ;; beginning of line.
23168 ;; `org-setup-comments-handling' install comments related variables
23169 ;; during `org-mode' initialization.
23171 (defun org-setup-comments-handling ()
23173 (org-set-local 'comment-use-syntax nil)
23174 (org-set-local 'comment-start "# ")
23175 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23176 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23177 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23178 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23180 (defun org-insert-comment ()
23181 "Insert an empty comment above current line.
23182 If the line is empty, insert comment at its beginning. When
23183 point is within a source block, comment according to the related
23185 (if (let ((element (org-element-at-point)))
23186 (and (eq (org-element-type element) 'src-block)
23188 (goto-char (org-element-property :post-affiliated element))
23189 (line-end-position))
23192 (goto-char (org-element-property :end element))
23193 (skip-chars-backward " \r\t\n")
23194 (line-beginning-position))
23196 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23197 (beginning-of-line)
23198 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23203 (defvar comment-empty-lines) ; From newcomment.el.
23204 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23205 "Comment or uncomment each non-blank line in the region.
23206 Uncomment each non-blank line between BEG and END if it only
23207 contains commented lines. Otherwise, comment them. If region is
23208 strictly within a source block, use appropriate comment syntax."
23209 (if (let ((element (org-element-at-point)))
23210 (and (eq (org-element-type element) 'src-block)
23212 (goto-char (org-element-property :post-affiliated element))
23213 (line-end-position))
23215 (>= (save-excursion
23216 (goto-char (org-element-property :end element))
23217 (skip-chars-backward " \r\t\n")
23218 (line-beginning-position))
23220 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23223 (narrow-to-region (save-excursion (goto-char beg)
23224 (skip-chars-forward " \r\t\n" end)
23225 (line-beginning-position))
23226 (save-excursion (goto-char end)
23227 (skip-chars-backward " \r\t\n" beg)
23228 (line-end-position)))
23230 ;; UNCOMMENTP is non-nil when every non blank line between
23231 ;; BEG and END is a comment.
23233 (goto-char (point-min))
23234 (while (and (not (eobp))
23235 (let ((element (org-element-at-point)))
23236 (and (eq (org-element-type element) 'comment)
23237 (goto-char (min (point-max)
23238 (org-element-property
23239 :end element)))))))
23242 ;; Only blank lines and comments in region: uncomment it.
23244 (goto-char (point-min))
23245 (while (not (eobp))
23246 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23247 (replace-match "" nil nil nil 1))
23249 ;; Comment each line in region.
23250 (let ((min-indent (point-max)))
23251 ;; First find the minimum indentation across all lines.
23253 (goto-char (point-min))
23254 (while (and (not (eobp)) (not (zerop min-indent)))
23255 (unless (looking-at "[ \t]*$")
23256 (setq min-indent (min min-indent (current-indentation))))
23258 ;; Then loop over all lines.
23260 (goto-char (point-min))
23261 (while (not (eobp))
23262 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23263 ;; Don't get fooled by invisible text (e.g. link path)
23264 ;; when moving to column MIN-INDENT.
23265 (let ((buffer-invisibility-spec nil))
23266 (org-move-to-column min-indent t))
23267 (insert comment-start))
23268 (forward-line)))))))))
23270 (defun org-comment-dwim (arg)
23271 "Call `comment-dwim' within a source edit buffer if needed."
23273 (if (org-in-src-block-p)
23274 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23275 (call-interactively 'comment-dwim)))
23280 ;; This section contains tools to operate on timestamp objects, as
23281 ;; returned by, e.g. `org-element-context'.
23283 (defun org-timestamp-has-time-p (timestamp)
23284 "Non-nil when TIMESTAMP has a time specified."
23285 (org-element-property :hour-start timestamp))
23287 (defun org-timestamp-format (timestamp format &optional end utc)
23288 "Format a TIMESTAMP element into a string.
23290 FORMAT is a format specifier to be passed to
23291 `format-time-string'.
23293 When optional argument END is non-nil, use end of date-range or
23294 time-range, if possible.
23296 When optional argument UTC is non-nil, time will be expressed as
23298 (format-time-string
23300 (apply 'encode-time
23303 (lambda (prop) (or (org-element-property prop timestamp) 0))
23304 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23305 '(:minute-start :hour-start :day-start :month-start
23309 (defun org-timestamp-split-range (timestamp &optional end)
23310 "Extract a timestamp object from a date or time range.
23312 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23313 the end of the range. Otherwise, extract its start.
23315 Return a new timestamp object sharing the same parent as
23317 (let ((type (org-element-property :type timestamp)))
23318 (if (memq type '(active inactive diary)) timestamp
23319 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23321 (org-element-put-property
23322 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23323 ;; Copy start properties over end properties if END is
23324 ;; non-nil. Otherwise, copy end properties over `start' ones.
23325 (let ((p-alist '((:minute-start . :minute-end)
23326 (:hour-start . :hour-end)
23327 (:day-start . :day-end)
23328 (:month-start . :month-end)
23329 (:year-start . :year-end))))
23330 (dolist (p-cell p-alist)
23331 (org-element-put-property
23333 (funcall (if end 'car 'cdr) p-cell)
23334 (org-element-property
23335 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23336 ;; Eventually refresh `:raw-value'.
23337 (org-element-put-property split-ts :raw-value nil)
23338 (org-element-put-property
23339 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23341 (defun org-timestamp-translate (timestamp &optional boundary)
23342 "Apply `org-translate-time' on a TIMESTAMP object.
23343 When optional argument BOUNDARY is non-nil, it is either the
23344 symbol `start' or `end'. In this case, only translate the
23345 starting or ending part of TIMESTAMP if it is a date or time
23346 range. Otherwise, translate both parts."
23347 (if (and (not boundary)
23348 (memq (org-element-property :type timestamp)
23349 '(active-range inactive-range)))
23351 (org-translate-time
23352 (org-element-property :raw-value
23353 (org-timestamp-split-range timestamp)))
23355 (org-translate-time
23356 (org-element-property :raw-value
23357 (org-timestamp-split-range timestamp t))))
23358 (org-translate-time
23359 (org-element-property
23361 (if (not boundary) timestamp
23362 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23368 (defun org-reftex-citation ()
23369 "Use reftex-citation to insert a citation into the buffer.
23370 This looks for a line like
23372 #+BIBLIOGRAPHY: foo plain option:-d
23374 and derives from it that foo.bib is the bibliography file relevant
23375 for this document. It then installs the necessary environment for RefTeX
23376 to work in this buffer and calls `reftex-citation' to insert a citation
23379 Export of such citations to both LaTeX and HTML is handled by the contributed
23380 package ox-bibtex by Taru Karttunen."
23382 (let ((reftex-docstruct-symbol 'rds)
23383 (reftex-cite-format "\\cite{%l}")
23388 (let ((case-fold-search t)
23389 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23390 (if (not (save-excursion
23391 (or (re-search-forward re nil t)
23392 (re-search-backward re nil t))))
23393 (user-error "No bibliography defined in file")
23394 (setq bib (concat (match-string 1) ".bib")
23395 rds (list (list 'bib bib)))))))
23396 (call-interactively 'reftex-citation)))
23398 ;;;; Functions extending outline functionality
23400 (defun org-beginning-of-line (&optional arg)
23401 "Go to the beginning of the current line. If that is invisible, continue
23402 to a visible line beginning. This makes the function of C-a more intuitive.
23403 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23404 first attempt, and only move to after the tags when the cursor is already
23405 beyond the end of the headline."
23407 (let ((pos (point))
23408 (special (if (consp org-special-ctrl-a/e)
23409 (car org-special-ctrl-a/e)
23410 org-special-ctrl-a/e))
23411 deactivate-mark refpos)
23412 (if (org-bound-and-true-p visual-line-mode)
23413 (beginning-of-visual-line 1)
23414 (beginning-of-line 1))
23415 (if (and arg (fboundp 'move-beginning-of-line))
23416 (call-interactively 'move-beginning-of-line)
23420 (if (org-truely-invisible-p)
23421 (while (and (not (bobp)) (org-truely-invisible-p))
23423 (beginning-of-line 1))
23424 (forward-char 1))))
23427 ((and (looking-at org-complex-heading-regexp)
23428 (= (char-after (match-end 1)) ?\ ))
23429 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23433 (cond ((> pos refpos) refpos)
23434 ((= pos (point)) refpos)
23436 (cond ((> pos (point)) (point))
23437 ((not (eq last-command this-command)) (point))
23440 ;; Being at an item and not looking at an the item means point
23441 ;; was previously moved to beginning of a visual line, which
23442 ;; doesn't contain the item. Therefore, do nothing special,
23444 (when (looking-at org-list-full-item-re)
23445 ;; Set special position at first white space character after
23446 ;; bullet, and check-box, if any.
23447 (let ((after-bullet
23448 (let ((box (match-end 3)))
23449 (if (not box) (match-end 1)
23450 (let ((after (char-after box)))
23451 (if (and after (= after ? )) (1+ box) box))))))
23452 ;; Special case: Move point to special position when
23453 ;; currently after it or at beginning of line.
23455 (when (or (> pos after-bullet) (= (point) pos))
23456 (goto-char after-bullet))
23457 ;; Reversed case: Move point to special position when
23458 ;; point was already at beginning of line and command is
23460 (when (and (= (point) pos) (eq last-command this-command))
23461 (goto-char after-bullet))))))))
23463 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23464 (setq disable-point-adjustment
23465 (or (not (invisible-p (point)))
23466 (not (invisible-p (max (point-min) (1- (point))))))))
23468 (defun org-end-of-line (&optional arg)
23469 "Go to the end of the line.
23470 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23471 tags on the first attempt, and only move to after the tags when
23472 the cursor is already beyond the end of the headline."
23474 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23475 org-special-ctrl-a/e))
23476 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23477 'end-of-visual-line)
23478 ((fboundp 'move-end-of-line) 'move-end-of-line)
23481 (if (or (not special) arg) (call-interactively move-fun)
23482 (let* ((element (save-excursion (beginning-of-line)
23483 (org-element-at-point)))
23484 (type (org-element-type element)))
23486 ((memq type '(headline inlinetask))
23487 (let ((pos (point)))
23488 (beginning-of-line 1)
23489 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23491 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23492 (goto-char (match-beginning 1))
23493 (goto-char (match-end 0)))
23494 (if (or (< pos (match-end 0))
23495 (not (eq this-command last-command)))
23496 (goto-char (match-end 0))
23497 (goto-char (match-beginning 1))))
23498 (call-interactively move-fun))))
23499 ((outline-invisible-p (line-end-position))
23500 ;; If element is hidden, `move-end-of-line' would put point
23501 ;; after it. Use `end-of-line' to stay on current line.
23502 (call-interactively 'end-of-line))
23503 (t (call-interactively move-fun)))))
23504 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23505 (setq disable-point-adjustment
23506 (or (not (invisible-p (point)))
23507 (not (invisible-p (max (point-min) (1- (point))))))))
23509 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23510 (define-key org-mode-map "\C-e" 'org-end-of-line)
23512 (defun org-backward-sentence (&optional arg)
23513 "Go to beginning of sentence, or beginning of table field.
23514 This will call `backward-sentence' or `org-table-beginning-of-field',
23515 depending on context."
23518 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23519 (t (call-interactively 'backward-sentence))))
23521 (defun org-forward-sentence (&optional arg)
23522 "Go to end of sentence, or end of table field.
23523 This will call `forward-sentence' or `org-table-end-of-field',
23524 depending on context."
23527 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23528 (t (call-interactively 'forward-sentence))))
23530 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23531 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23533 (defun org-kill-line (&optional arg)
23534 "Kill line, to tags or end of line."
23537 ((or (not org-special-ctrl-k)
23539 (not (org-at-heading-p)))
23540 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23541 org-ctrl-k-protect-subtree)
23542 (if (or (eq org-ctrl-k-protect-subtree 'error)
23543 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23544 (user-error "C-k aborted as it would kill a hidden subtree")))
23545 (call-interactively
23546 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23547 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23548 (kill-region (point) (match-beginning 1))
23549 (org-set-tags nil t))
23550 (t (kill-region (point) (point-at-eol)))))
23552 (define-key org-mode-map "\C-k" 'org-kill-line)
23554 (defun org-yank (&optional arg)
23555 "Yank. If the kill is a subtree, treat it specially.
23556 This command will look at the current kill and check if is a single
23557 subtree, or a series of subtrees[1]. If it passes the test, and if the
23558 cursor is at the beginning of a line or after the stars of a currently
23559 empty headline, then the yank is handled specially. How exactly depends
23560 on the value of the following variables, both set by default.
23562 `org-yank-folded-subtrees'
23563 When set, the subtree(s) will be folded after insertion, but only
23564 if doing so would now swallow text after the yanked text.
23566 `org-yank-adjusted-subtrees'
23567 When set, the subtree will be promoted or demoted in order to
23568 fit into the local outline tree structure, which means that the
23569 level will be adjusted so that it becomes the smaller one of the
23570 two *visible* surrounding headings.
23572 Any prefix to this command will cause `yank' to be called directly with
23573 no special treatment. In particular, a simple \\[universal-argument] prefix \
23575 plainly yank the text as it is.
23577 \[1] The test checks if the first non-white line is a heading
23578 and if there are no other headings with fewer stars."
23580 (org-yank-generic 'yank arg))
23582 (defun org-yank-generic (command arg)
23583 "Perform some yank-like command.
23585 This function implements the behavior described in the `org-yank'
23586 documentation. However, it has been generalized to work for any
23587 interactive command with similar behavior."
23589 ;; pretend to be command COMMAND
23590 (setq this-command command)
23593 (call-interactively command)
23595 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23596 (and (org-kill-is-subtree-p)
23598 (and (looking-at "[ \t]*$")
23601 (buffer-substring (point-at-bol) (point)))))))
23604 ((and subtreep org-yank-folded-subtrees)
23605 (let ((beg (point))
23607 (if (and subtreep org-yank-adjusted-subtrees)
23608 (org-paste-subtree nil nil 'for-yank)
23609 (call-interactively command))
23613 (when (and (bolp) subtreep
23614 (not (setq swallowp
23615 (org-yank-folding-would-swallow-text beg end))))
23616 (org-with-limited-levels
23617 (or (looking-at org-outline-regexp)
23618 (re-search-forward org-outline-regexp-bol end t))
23619 (while (and (< (point) end) (looking-at org-outline-regexp))
23621 (org-cycle-show-empty-lines 'folded)
23622 (condition-case nil
23623 (outline-forward-same-level 1)
23624 (error (goto-char end))))))
23627 "Inserted text not folded because that would swallow text"))
23630 (skip-chars-forward " \t\n\r")
23631 (beginning-of-line 1)
23632 (push-mark beg 'nomsg)))
23633 ((and subtreep org-yank-adjusted-subtrees)
23634 (let ((beg (point-at-bol)))
23635 (org-paste-subtree nil nil 'for-yank)
23636 (push-mark beg 'nomsg)))
23638 (call-interactively command))))))
23640 (defun org-yank-folding-would-swallow-text (beg end)
23641 "Would hide-subtree at BEG swallow any text after END?"
23643 (org-with-limited-levels
23646 (when (or (looking-at org-outline-regexp)
23647 (re-search-forward org-outline-regexp-bol end t))
23648 (setq level (org-outline-level)))
23650 (skip-chars-forward " \t\r\n\v\f")
23652 (and (bolp) (looking-at org-outline-regexp)
23653 (<= (org-outline-level) level)))
23654 nil ; Nothing would be swallowed
23655 t))))) ; something would swallow
23657 (define-key org-mode-map "\C-y" 'org-yank)
23659 (defun org-truely-invisible-p ()
23660 "Check if point is at a character currently not visible.
23661 This version does not only check the character property, but also
23663 ;; Early versions of noutline don't have `outline-invisible-p'.
23664 (if (org-bound-and-true-p visible-mode)
23666 (outline-invisible-p)))
23668 (defun org-invisible-p2 ()
23669 "Check if point is at a character currently not visible."
23671 (if (and (eolp) (not (bobp))) (backward-char 1))
23672 ;; Early versions of noutline don't have `outline-invisible-p'.
23673 (outline-invisible-p)))
23675 (defun org-back-to-heading (&optional invisible-ok)
23676 "Call `outline-back-to-heading', but provide a better error message."
23677 (condition-case nil
23678 (outline-back-to-heading invisible-ok)
23679 (error (error "Before first headline at position %d in buffer %s"
23680 (point) (current-buffer)))))
23682 (defun org-before-first-heading-p ()
23683 "Before first heading?"
23686 (null (re-search-backward org-outline-regexp-bol nil t))))
23688 (defun org-at-heading-p (&optional ignored)
23689 (outline-on-heading-p t))
23690 ;; Compatibility alias with Org versions < 7.8.03
23691 (defalias 'org-on-heading-p 'org-at-heading-p)
23693 (defun org-in-commented-heading-p (&optional no-inheritance)
23694 "Non-nil if point is under a commented heading.
23695 This function also checks ancestors of the current headline,
23696 unless optional argument NO-INHERITANCE is non-nil."
23698 ((org-before-first-heading-p) nil)
23699 ((let ((headline (nth 4 (org-heading-components))))
23701 (let ((case-fold-search nil))
23702 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23704 (no-inheritance nil)
23706 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23708 (defun org-at-comment-p nil
23709 "Is cursor in a commented line?"
23712 (beginning-of-line)
23713 (looking-at "^[ \t]*# "))))
23715 (defun org-at-drawer-p nil
23716 "Is cursor at a drawer keyword?"
23718 (move-beginning-of-line 1)
23719 (looking-at org-drawer-regexp)))
23721 (defun org-at-block-p nil
23722 "Is cursor at a block keyword?"
23724 (move-beginning-of-line 1)
23725 (looking-at org-block-regexp)))
23727 (defun org-point-at-end-of-empty-headline ()
23728 "If point is at the end of an empty headline, return t, else nil.
23729 If the heading only contains a TODO keyword, it is still still considered
23731 (and (looking-at "[ \t]*$")
23732 (when org-todo-line-regexp
23734 (beginning-of-line 1)
23735 (let ((case-fold-search nil))
23736 (looking-at org-todo-line-regexp)
23737 (string= (match-string 3) ""))))))
23739 (defun org-at-heading-or-item-p ()
23740 (or (org-at-heading-p) (org-at-item-p)))
23742 (defun org-at-target-p ()
23743 (or (org-in-regexp org-radio-target-regexp)
23744 (org-in-regexp org-target-regexp)))
23745 ;; Compatibility alias with Org versions < 7.8.03
23746 (defalias 'org-on-target-p 'org-at-target-p)
23748 (defun org-up-heading-all (arg)
23749 "Move to the heading line of which the present line is a subheading.
23750 This function considers both visible and invisible heading lines.
23751 With argument, move up ARG levels."
23752 (if (fboundp 'outline-up-heading-all)
23753 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23754 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23756 (defun org-up-heading-safe ()
23757 "Move to the heading line of which the present line is a subheading.
23758 This version will not throw an error. It will return the level of the
23759 headline found, or nil if no higher level is found.
23761 Also, this function will be a lot faster than `outline-up-heading',
23762 because it relies on stars being the outline starters. This can really
23763 make a significant difference in outlines with very many siblings."
23764 (when (ignore-errors (org-back-to-heading t))
23765 (let ((level-up (1- (funcall outline-level))))
23766 (and (> level-up 0)
23767 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23768 (funcall outline-level)))))
23770 (defun org-first-sibling-p ()
23771 "Is this heading the first child of its parents?"
23773 (let ((re org-outline-regexp-bol)
23775 (unless (org-at-heading-p t)
23776 (user-error "Not at a heading"))
23777 (setq level (funcall outline-level))
23779 (if (not (re-search-backward re nil t))
23781 (setq l (funcall outline-level))
23784 (defun org-goto-sibling (&optional previous)
23785 "Goto the next sibling, even if it is invisible.
23786 When PREVIOUS is set, go to the previous sibling instead. Returns t
23787 when a sibling was found. When none is found, return nil and don't
23789 (let ((fun (if previous 're-search-backward 're-search-forward))
23791 (re org-outline-regexp-bol)
23793 (when (ignore-errors (org-back-to-heading t))
23794 (setq level (funcall outline-level))
23796 (or previous (forward-char 1))
23797 (while (funcall fun re nil t)
23798 (setq l (funcall outline-level))
23799 (when (< l level) (goto-char pos) (throw 'exit nil))
23800 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23804 (defun org-show-siblings ()
23805 "Show all siblings of the current headline."
23807 (while (org-goto-sibling) (org-flag-heading nil)))
23809 (while (org-goto-sibling 'previous)
23810 (org-flag-heading nil))))
23812 (defun org-goto-first-child ()
23813 "Goto the first child, even if it is invisible.
23814 Return t when a child was found. Otherwise don't move point and
23816 (let (level (pos (point)) (re org-outline-regexp-bol))
23817 (when (ignore-errors (org-back-to-heading t))
23818 (setq level (outline-level))
23820 (if (and (re-search-forward re nil t) (> (outline-level) level))
23821 (progn (goto-char (match-beginning 0)) t)
23822 (goto-char pos) nil))))
23824 (defun org-show-hidden-entry ()
23825 "Show an entry where even the heading is hidden."
23829 (defun org-flag-heading (flag &optional entry)
23830 "Flag the current heading. FLAG non-nil means make invisible.
23831 When ENTRY is non-nil, show the entire entry."
23833 (org-back-to-heading t)
23834 ;; Check if we should show the entire entry
23839 (and (outline-next-heading)
23840 (org-flag-heading nil))))
23841 (outline-flag-region (max (point-min) (1- (point)))
23842 (save-excursion (outline-end-of-heading) (point))
23845 (defun org-get-next-sibling ()
23846 "Move to next heading of the same level, and return point.
23847 If there is no such heading, return nil.
23848 This is like outline-next-sibling, but invisible headings are ok."
23849 (let ((level (funcall outline-level)))
23850 (outline-next-heading)
23851 (while (and (not (eobp)) (> (funcall outline-level) level))
23852 (outline-next-heading))
23853 (if (or (eobp) (< (funcall outline-level) level))
23857 (defun org-get-last-sibling ()
23858 "Move to previous heading of the same level, and return point.
23859 If there is no such heading, return nil."
23860 (let ((opoint (point))
23861 (level (funcall outline-level)))
23862 (outline-previous-heading)
23863 (when (and (/= (point) opoint) (outline-on-heading-p t))
23864 (while (and (> (funcall outline-level) level)
23866 (outline-previous-heading))
23867 (if (< (funcall outline-level) level)
23871 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23872 "Goto to the end of a subtree."
23873 ;; This contains an exact copy of the original function, but it uses
23874 ;; `org-back-to-heading', to make it work also in invisible
23875 ;; trees. And is uses an invisible-ok argument.
23876 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23877 ;; Furthermore, when used inside Org, finding the end of a large subtree
23878 ;; with many children and grandchildren etc, this can be much faster
23879 ;; than the outline version.
23880 (org-back-to-heading invisible-ok)
23882 (level (funcall outline-level)))
23883 (if (and (derived-mode-p 'org-mode) (< level 1000))
23884 ;; A true heading (not a plain list item), in Org-mode
23885 ;; This means we can easily find the end by looking
23886 ;; only for the right number of stars. Using a regexp to do
23887 ;; this is so much faster than using a Lisp loop.
23888 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23890 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23891 ;; something else, do it the slow way
23892 (while (and (not (eobp))
23893 (or first (> (funcall outline-level) level)))
23895 (outline-next-heading)))
23897 (if (memq (preceding-char) '(?\n ?\^M))
23899 ;; Go to end of line before heading
23901 (if (memq (preceding-char) '(?\n ?\^M))
23902 ;; leave blank line before heading
23903 (forward-char -1))))))
23906 (defun org-end-of-meta-data-and-drawers ()
23907 "Jump to the first text after meta data and drawers in the current entry.
23908 This will move over empty lines, lines with planning time stamps,
23909 clocking lines, and drawers."
23910 (org-back-to-heading t)
23911 (let ((end (save-excursion (outline-next-heading) (point)))
23912 (re (concat "\\(" org-drawer-regexp "\\)"
23913 "\\|" "[ \t]*" org-keyword-time-regexp)))
23915 (while (re-search-forward re end t)
23916 (if (not (match-end 1))
23917 ;; empty or planning line
23919 ;; a drawer, find the end
23920 (re-search-forward "^[ \t]*:END:" end 'move)
23922 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23925 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23926 "Move forward to the ARG'th subheading at same level as this one.
23927 Stop at the first and last subheadings of a superior heading.
23928 Normally this only looks at visible headings, but when INVISIBLE-OK is
23929 non-nil it will also look at invisible ones."
23931 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23932 (if (and arg (< arg 0))
23933 (goto-char (point-min))
23934 (outline-next-heading))
23936 (let ((level (- (match-end 0) (match-beginning 0) 1))
23937 (f (if (and arg (< arg 0))
23938 're-search-backward
23939 're-search-forward))
23940 (count (if arg (abs arg) 1))
23942 (while (and (prog1 (> count 0)
23943 (forward-char (if (and arg (< arg 0)) -1 1)))
23944 (funcall f org-outline-regexp-bol nil 'move))
23945 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23946 (cond ((< l level) (setq count 0))
23950 (goto-char (line-beginning-position))
23951 (not (outline-invisible-p)))))
23952 (setq count (1- count))
23954 (setq result (point)))))))
23955 (goto-char result))
23956 (beginning-of-line 1)))
23958 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23959 "Move backward to the ARG'th subheading at same level as this one.
23960 Stop at the first and last subheadings of a superior heading."
23962 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23964 (defun org-next-block (arg &optional backward block-regexp)
23965 "Jump to the next block.
23966 With a prefix argument ARG, jump forward ARG many source blocks.
23967 When BACKWARD is non-nil, jump to the previous block.
23968 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23970 (let ((re (or block-regexp org-block-regexp))
23971 (re-search-fn (or (and backward 're-search-backward)
23972 're-search-forward)))
23973 (if (looking-at re) (forward-char 1))
23974 (condition-case nil
23975 (funcall re-search-fn re nil nil arg)
23976 (error (user-error "No %s code blocks"
23977 (if backward "previous" "further" ))))
23978 (goto-char (match-beginning 0)) (org-show-context)))
23980 (defun org-previous-block (arg &optional block-regexp)
23981 "Jump to the previous block.
23982 With a prefix argument ARG, jump backward ARG many source blocks.
23983 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23985 (org-next-block arg t block-regexp))
23987 (defun org-forward-paragraph ()
23988 "Move forward to beginning of next paragraph or equivalent.
23990 The function moves point to the beginning of the next visible
23991 structural element, which can be a paragraph, a table, a list
23992 item, etc. It also provides some special moves for convenience:
23994 - On an affiliated keyword, jump to the beginning of the
23996 - On an item or a footnote definition, move to the second
23997 element inside, if any.
23998 - On a table or a property drawer, jump after it.
23999 - On a verse or source block, stop after blank lines."
24001 (when (eobp) (user-error "Cannot move further down"))
24002 (let* ((deactivate-mark nil)
24003 (element (org-element-at-point))
24004 (type (org-element-type element))
24005 (post-affiliated (org-element-property :post-affiliated element))
24006 (contents-begin (org-element-property :contents-begin element))
24007 (contents-end (org-element-property :contents-end element))
24008 (end (let ((end (org-element-property :end element)) (parent element))
24009 (while (and (setq parent (org-element-property :parent parent))
24010 (= (org-element-property :contents-end parent) end))
24011 (setq end (org-element-property :end parent)))
24013 (cond ((not element)
24014 (skip-chars-forward " \r\t\n")
24015 (or (eobp) (beginning-of-line)))
24016 ;; On affiliated keywords, move to element's beginning.
24017 ((< (point) post-affiliated)
24018 (goto-char post-affiliated))
24019 ;; At a table row, move to the end of the table. Similarly,
24020 ;; at a node property, move to the end of the property
24022 ((memq type '(node-property table-row))
24023 (goto-char (org-element-property
24024 :end (org-element-property :parent element))))
24025 ((memq type '(property-drawer table)) (goto-char end))
24026 ;; Consider blank lines as separators in verse and source
24027 ;; blocks to ease editing.
24028 ((memq type '(src-block verse-block))
24029 (when (eq type 'src-block)
24031 (save-excursion (goto-char end)
24032 (skip-chars-backward " \r\t\n")
24033 (line-beginning-position))))
24034 (beginning-of-line)
24035 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24036 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24038 (skip-chars-forward " \r\t\n")
24039 (if (= (point) contents-end) (goto-char end)
24040 (beginning-of-line))))
24041 ;; With no contents, just skip element.
24042 ((not contents-begin) (goto-char end))
24043 ;; If contents are invisible, skip the element altogether.
24044 ((outline-invisible-p (line-end-position))
24047 (org-with-limited-levels (outline-next-visible-heading 1)))
24048 ;; At a plain list, make sure we move to the next item
24049 ;; instead of skipping the whole list.
24050 (plain-list (forward-char)
24051 (org-forward-paragraph))
24052 (otherwise (goto-char end))))
24053 ((>= (point) contents-end) (goto-char end))
24054 ((>= (point) contents-begin)
24055 ;; This can only happen on paragraphs and plain lists.
24057 (paragraph (goto-char end))
24058 ;; At a plain list, try to move to second element in
24059 ;; first item, if possible.
24060 (plain-list (end-of-line)
24061 (org-forward-paragraph))))
24062 ;; When contents start on the middle of a line (e.g. in
24063 ;; items and footnote definitions), try to reach first
24064 ;; element starting after current line.
24065 ((> (line-end-position) contents-begin)
24067 (org-forward-paragraph))
24068 (t (goto-char contents-begin)))))
24070 (defun org-backward-paragraph ()
24071 "Move backward to start of previous paragraph or equivalent.
24073 The function moves point to the beginning of the current
24074 structural element, which can be a paragraph, a table, a list
24075 item, etc., or to the beginning of the previous visible one if
24076 point is already there. It also provides some special moves for
24079 - On an affiliated keyword, jump to the first one.
24080 - On a table or a property drawer, move to its beginning.
24081 - On a verse or source block, stop before blank lines."
24083 (when (bobp) (user-error "Cannot move further up"))
24084 (let* ((deactivate-mark nil)
24085 (element (org-element-at-point))
24086 (type (org-element-type element))
24087 (contents-begin (org-element-property :contents-begin element))
24088 (contents-end (org-element-property :contents-end element))
24089 (post-affiliated (org-element-property :post-affiliated element))
24090 (begin (org-element-property :begin element)))
24092 ((not element) (goto-char (point-min)))
24095 (org-backward-paragraph))
24096 ((<= (point) post-affiliated) (goto-char begin))
24097 ((memq type '(node-property table-row))
24098 (goto-char (org-element-property
24099 :post-affiliated (org-element-property :parent element))))
24100 ((memq type '(property-drawer table)) (goto-char begin))
24101 ((memq type '(src-block verse-block))
24102 (when (eq type 'src-block)
24103 (setq contents-begin
24104 (save-excursion (goto-char begin) (forward-line) (point))))
24105 (if (= (point) contents-begin) (goto-char post-affiliated)
24106 ;; Inside a verse block, see blank lines as paragraph
24108 (let ((origin (point)))
24109 (skip-chars-backward " \r\t\n" contents-begin)
24110 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24111 (skip-chars-forward " \r\t\n" origin)
24112 (if (= (point) origin) (goto-char contents-begin)
24113 (beginning-of-line))))))
24114 ((not contents-begin) (goto-char (or post-affiliated begin)))
24115 ((eq type 'paragraph)
24116 (goto-char contents-begin)
24117 ;; When at first paragraph in an item or a footnote definition,
24118 ;; move directly to beginning of line.
24119 (let ((parent-contents
24120 (org-element-property
24121 :contents-begin (org-element-property :parent element))))
24122 (when (and parent-contents (= parent-contents contents-begin))
24123 (beginning-of-line))))
24124 ;; At the end of a greater element, move to the beginning of the
24125 ;; last element within.
24126 ((>= (point) contents-end)
24127 (goto-char (1- contents-end))
24128 (org-backward-paragraph))
24129 (t (goto-char (or post-affiliated begin))))
24130 ;; Ensure we never leave point invisible.
24131 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24133 (defun org-forward-element ()
24134 "Move forward by one element.
24135 Move to the next element at the same level, when possible."
24137 (cond ((eobp) (user-error "Cannot move further down"))
24138 ((org-with-limited-levels (org-at-heading-p))
24139 (let ((origin (point)))
24140 (goto-char (org-end-of-subtree nil t))
24141 (unless (org-with-limited-levels (org-at-heading-p))
24143 (user-error "Cannot move further down"))))
24145 (let* ((elem (org-element-at-point))
24146 (end (org-element-property :end elem))
24147 (parent (org-element-property :parent elem)))
24148 (cond ((and parent (= (org-element-property :contents-end parent) end))
24149 (goto-char (org-element-property :end parent)))
24150 ((integer-or-marker-p end) (goto-char end))
24151 (t (message "No element at point")))))))
24153 (defun org-backward-element ()
24154 "Move backward by one element.
24155 Move to the previous element at the same level, when possible."
24157 (cond ((bobp) (user-error "Cannot move further up"))
24158 ((org-with-limited-levels (org-at-heading-p))
24159 ;; At a headline, move to the previous one, if any, or stay
24161 (let ((origin (point)))
24162 (org-with-limited-levels (org-backward-heading-same-level 1))
24163 ;; When current headline has no sibling above, move to its
24165 (when (= (point) origin)
24166 (or (org-with-limited-levels (org-up-heading-safe))
24167 (progn (goto-char origin)
24168 (user-error "Cannot move further up"))))))
24170 (let* ((elem (org-element-at-point))
24171 (beg (org-element-property :begin elem)))
24173 ;; Move to beginning of current element if point isn't
24175 ((null beg) (message "No element at point"))
24176 ((/= (point) beg) (goto-char beg))
24178 (skip-chars-backward " \r\t\n")
24180 (let ((prev (org-element-at-point)))
24181 (goto-char (org-element-property :begin prev))
24182 (while (and (setq prev (org-element-property :parent prev))
24183 (<= (org-element-property :end prev) beg))
24184 (goto-char (org-element-property :begin prev)))))))))))
24186 (defun org-up-element ()
24187 "Move to upper element."
24189 (if (org-with-limited-levels (org-at-heading-p))
24190 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24191 (let* ((elem (org-element-at-point))
24192 (parent (org-element-property :parent elem)))
24193 (if parent (goto-char (org-element-property :begin parent))
24194 (if (org-with-limited-levels (org-before-first-heading-p))
24195 (user-error "No surrounding element")
24196 (org-with-limited-levels (org-back-to-heading)))))))
24198 (defvar org-element-greater-elements)
24199 (defun org-down-element ()
24200 "Move to inner element."
24202 (let ((element (org-element-at-point)))
24204 ((memq (org-element-type element) '(plain-list table))
24205 (goto-char (org-element-property :contents-begin element))
24207 ((memq (org-element-type element) org-element-greater-elements)
24208 ;; If contents are hidden, first disclose them.
24209 (when (outline-invisible-p (line-end-position)) (org-cycle))
24210 (goto-char (or (org-element-property :contents-begin element)
24211 (user-error "No content for this element"))))
24212 (t (user-error "No inner element")))))
24214 (defun org-drag-element-backward ()
24215 "Move backward element at point."
24217 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24218 (let* ((elem (org-element-at-point))
24221 (goto-char (org-element-property :begin elem))
24222 (skip-chars-backward " \r\t\n")
24224 (let* ((beg (org-element-property :begin elem))
24225 (prev (org-element-at-point))
24227 (while (and (setq up (org-element-property :parent up))
24228 (<= (org-element-property :end up) beg))
24231 ;; Error out if no previous element or previous element is
24232 ;; a parent of the current one.
24233 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24234 (user-error "Cannot drag element backward")
24235 (let ((pos (point)))
24236 (org-element-swap-A-B prev-elem elem)
24237 (goto-char (+ (org-element-property :begin prev-elem)
24238 (- pos (org-element-property :begin elem)))))))))
24240 (defun org-drag-element-forward ()
24241 "Move forward element at point."
24243 (let* ((pos (point))
24244 (elem (org-element-at-point)))
24245 (when (= (point-max) (org-element-property :end elem))
24246 (user-error "Cannot drag element forward"))
24247 (goto-char (org-element-property :end elem))
24248 (let ((next-elem (org-element-at-point)))
24249 (when (or (org-element-nested-p elem next-elem)
24250 (and (eq (org-element-type next-elem) 'headline)
24251 (not (eq (org-element-type elem) 'headline))))
24253 (user-error "Cannot drag element forward"))
24254 ;; Compute new position of point: it's shifted by NEXT-ELEM
24255 ;; body's length (without final blanks) and by the length of
24256 ;; blanks between ELEM and NEXT-ELEM.
24257 (let ((size-next (- (save-excursion
24258 (goto-char (org-element-property :end next-elem))
24259 (skip-chars-backward " \r\t\n")
24261 ;; Small correction if buffer doesn't end
24262 ;; with a newline character.
24263 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24264 (org-element-property :begin next-elem)))
24265 (size-blank (- (org-element-property :end elem)
24267 (goto-char (org-element-property :end elem))
24268 (skip-chars-backward " \r\t\n")
24271 (org-element-swap-A-B elem next-elem)
24272 (goto-char (+ pos size-next size-blank))))))
24274 (defun org-drag-line-forward (arg)
24275 "Drag the line at point ARG lines forward."
24277 (dotimes (n (abs arg))
24278 (let ((c (current-column)))
24281 (beginning-of-line 2)
24282 (transpose-lines 1)
24283 (beginning-of-line 0))
24284 (transpose-lines 1)
24285 (beginning-of-line -1))
24286 (org-move-to-column c))))
24288 (defun org-drag-line-backward (arg)
24289 "Drag the line at point ARG lines backward."
24291 (org-drag-line-forward (- arg)))
24293 (defun org-mark-element ()
24294 "Put point at beginning of this element, mark at end.
24296 Interactively, if this command is repeated or (in Transient Mark
24297 mode) if the mark is active, it marks the next element after the
24298 ones already marked."
24300 (let (deactivate-mark)
24301 (if (and (org-called-interactively-p 'any)
24302 (or (and (eq last-command this-command) (mark t))
24303 (and transient-mark-mode mark-active)))
24307 (goto-char (org-element-property :end (org-element-at-point)))))
24308 (let ((element (org-element-at-point)))
24310 (push-mark (org-element-property :end element) t t)
24311 (goto-char (org-element-property :begin element))))))
24313 (defun org-narrow-to-element ()
24314 "Narrow buffer to current element."
24316 (let ((elem (org-element-at-point)))
24318 ((eq (car elem) 'headline)
24320 (org-element-property :begin elem)
24321 (org-element-property :end elem)))
24322 ((memq (car elem) org-element-greater-elements)
24324 (org-element-property :contents-begin elem)
24325 (org-element-property :contents-end elem)))
24328 (org-element-property :begin elem)
24329 (org-element-property :end elem))))))
24331 (defun org-transpose-element ()
24332 "Transpose current and previous elements, keeping blank lines between.
24333 Point is moved after both elements."
24335 (org-skip-whitespace)
24336 (let ((end (org-element-property :end (org-element-at-point))))
24337 (org-drag-element-backward)
24340 (defun org-unindent-buffer ()
24341 "Un-indent the visible part of the buffer.
24342 Relative indentation (between items, inside blocks, etc.) isn't
24345 (unless (eq major-mode 'org-mode)
24346 (user-error "Cannot un-indent a buffer not in Org mode"))
24347 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24348 unindent-tree ; For byte-compiler.
24354 (if (memq (org-element-type element) '(headline section))
24355 (funcall unindent-tree (org-element-contents element))
24359 (org-element-property :begin element)
24360 (org-element-property :end element))
24361 (org-do-remove-indentation)))))
24362 (reverse contents))))))
24363 (funcall unindent-tree (org-element-contents parse-tree))))
24365 (defun org-show-subtree ()
24366 "Show everything after this heading at deeper levels."
24368 (outline-flag-region
24371 (org-end-of-subtree t t))
24374 (defun org-show-entry ()
24375 "Show the body directly following this heading.
24376 Show the heading too, if it is currently invisible."
24380 (org-back-to-heading t)
24381 (outline-flag-region
24382 (max (point-min) (1- (point)))
24384 (if (re-search-forward
24385 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24386 (match-beginning 1)
24389 (org-cycle-hide-drawers 'children))))
24391 (defun org-make-options-regexp (kwds &optional extra)
24392 "Make a regular expression for keyword lines.
24393 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24394 when non-nil, is a regexp matching keywords names."
24395 (concat "^[ \t]*#\\+\\("
24397 (and extra (concat (and kwds "\\|") extra))
24398 "\\):[ \t]*\\(.*\\)"))
24400 ;; Make isearch reveal the necessary context
24401 (defun org-isearch-end ()
24402 "Reveal context after isearch exits."
24403 (when isearch-success ; only if search was successful
24404 (if (featurep 'xemacs)
24405 ;; Under XEmacs, the hook is run in the correct place,
24406 ;; we directly show the context.
24407 (org-show-context 'isearch)
24408 ;; In Emacs the hook runs *before* restoring the overlays.
24409 ;; So we have to use a one-time post-command-hook to do this.
24410 ;; (Emacs 22 has a special variable, see function `org-mode')
24411 (unless (and (boundp 'isearch-mode-end-hook-quit)
24412 isearch-mode-end-hook-quit)
24413 ;; Only when the isearch was not quitted.
24414 (org-add-hook 'post-command-hook 'org-isearch-post-command
24415 'append 'local)))))
24417 (defun org-isearch-post-command ()
24418 "Remove self from hook, and show context."
24419 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24420 (org-show-context 'isearch))
24423 ;;;; Integration with and fixes for other packages
24427 (defvar org-imenu-markers nil
24428 "All markers currently used by Imenu.")
24429 (make-variable-buffer-local 'org-imenu-markers)
24431 (defun org-imenu-new-marker (&optional pos)
24432 "Return a new marker for use by Imenu, and remember the marker."
24433 (let ((m (make-marker)))
24434 (move-marker m (or pos (point)))
24435 (push m org-imenu-markers)
24438 (defun org-imenu-get-tree ()
24439 "Produce the index for Imenu."
24440 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24441 (setq org-imenu-markers nil)
24442 (let* ((n org-imenu-depth)
24443 (re (concat "^" (org-get-limited-outline-regexp)))
24444 (subs (make-vector (1+ n) nil))
24446 m level head0 head)
24450 (goto-char (point-max))
24451 (while (re-search-backward re nil t)
24452 (setq level (org-reduced-level (funcall outline-level)))
24453 (when (and (<= level n)
24454 (looking-at org-complex-heading-regexp)
24455 (setq head0 (org-match-string-no-properties 4)))
24456 (setq head (org-link-display-format head0)
24457 m (org-imenu-new-marker))
24458 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24459 (if (>= level last-level)
24460 (push (cons head m) (aref subs level))
24461 (push (cons head (aref subs (1+ level))) (aref subs level))
24462 (loop for i from (1+ level) to n do (aset subs i nil)))
24463 (setq last-level level)))))
24466 (eval-after-load "imenu"
24468 (add-hook 'imenu-after-jump-hook
24470 (if (derived-mode-p 'org-mode)
24471 (org-show-context 'org-goto))))))
24473 (defun org-link-display-format (link)
24474 "Replace a link with its the description.
24475 If there is no description, use the link target."
24477 (if (string-match org-bracket-link-analytic-regexp link)
24478 (replace-match (if (match-end 5)
24479 (match-string 5 link)
24480 (concat (match-string 1 link)
24481 (match-string 3 link)))
24485 (defun org-toggle-link-display ()
24486 "Toggle the literal or descriptive display of links."
24488 (if org-descriptive-links
24489 (progn (org-remove-from-invisibility-spec '(org-link))
24490 (org-restart-font-lock)
24491 (setq org-descriptive-links nil))
24492 (progn (add-to-invisibility-spec '(org-link))
24493 (org-restart-font-lock)
24494 (setq org-descriptive-links t))))
24496 ;; Speedbar support
24498 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24499 "Overlay marking the agenda restriction line in speedbar.")
24500 (overlay-put org-speedbar-restriction-lock-overlay
24501 'face 'org-agenda-restriction-lock)
24502 (overlay-put org-speedbar-restriction-lock-overlay
24503 'help-echo "Agendas are currently limited to this item.")
24504 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24506 (defun org-speedbar-set-agenda-restriction ()
24507 "Restrict future agenda commands to the location at point in speedbar.
24508 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24510 (require 'org-agenda)
24511 (let (p m tp np dir txt)
24513 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24515 (setq m (get-text-property p 'org-imenu-marker))
24516 (with-current-buffer (marker-buffer m)
24518 (org-agenda-set-restriction-lock 'subtree)))
24519 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24520 'speedbar-function 'speedbar-find-file))
24521 (setq tp (previous-single-property-change
24522 (1+ p) 'speedbar-function)
24523 np (next-single-property-change
24524 tp 'speedbar-function)
24525 dir (speedbar-line-directory)
24526 txt (buffer-substring-no-properties (or tp (point-min))
24527 (or np (point-max))))
24528 (with-current-buffer (find-file-noselect
24529 (let ((default-directory dir))
24530 (expand-file-name txt)))
24531 (unless (derived-mode-p 'org-mode)
24532 (user-error "Cannot restrict to non-Org-mode file"))
24533 (org-agenda-set-restriction-lock 'file)))
24534 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24535 (move-overlay org-speedbar-restriction-lock-overlay
24536 (point-at-bol) (point-at-eol))
24537 (setq current-prefix-arg nil)
24538 (org-agenda-maybe-redo)))
24540 (defvar speedbar-file-key-map)
24541 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24542 (eval-after-load "speedbar"
24544 (speedbar-add-supported-extension ".org")
24545 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24546 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24547 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24548 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24549 (add-hook 'speedbar-visiting-tag-hook
24550 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24552 ;;; Fixes and Hacks for problems with other packages
24554 (defun org--flyspell-object-check-p (element)
24555 "Non-nil when Flyspell can check object at point.
24556 ELEMENT is the element at point."
24557 (let ((object (save-excursion
24558 (when (org-looking-at-p "\\>") (backward-char))
24559 (org-element-context element))))
24560 (case (org-element-type object)
24561 ;; Prevent checks in links due to keybinding conflict with
24563 ((code entity export-snippet inline-babel-call
24564 inline-src-block line-break latex-fragment link macro
24565 statistics-cookie target timestamp verbatim)
24567 (footnote-reference
24568 ;; Only in inline footnotes, within the definition.
24569 (and (eq (org-element-property :type object) 'inline)
24571 (goto-char (org-element-property :begin object))
24572 (search-forward ":" nil t 2))
24576 (defun org-mode-flyspell-verify ()
24577 "Function used for `flyspell-generic-check-word-predicate'."
24578 (if (org-at-heading-p)
24579 ;; At a headline or an inlinetask, check title only. This is
24580 ;; faster than relying on `org-element-at-point'.
24581 (and (save-excursion (beginning-of-line)
24582 (and (let ((case-fold-search t))
24583 (not (looking-at "\\*+ END[ \t]*$")))
24584 (looking-at org-complex-heading-regexp)))
24585 (match-beginning 4)
24586 (>= (point) (match-beginning 4))
24587 (or (not (match-beginning 5))
24588 (< (point) (match-beginning 5))))
24589 (let* ((element (org-element-at-point))
24590 (post-affiliated (org-element-property :post-affiliated element)))
24592 ;; Ignore checks in all affiliated keywords but captions.
24593 ((< (point) post-affiliated)
24594 (and (save-excursion
24595 (beginning-of-line)
24596 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24597 (> (point) (match-end 0))
24598 (org--flyspell-object-check-p element)))
24599 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24600 ((and org-log-into-drawer
24601 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24603 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24604 (setq parent (org-element-property :parent parent)))
24606 (eq (compare-strings
24608 (org-element-property :drawer-name parent) nil nil t)
24612 (case (org-element-type element)
24613 ((comment quote-section) t)
24615 ;; Allow checks between block markers, not on them.
24616 (and (> (line-beginning-position) post-affiliated)
24619 (skip-chars-forward " \r\t\n")
24620 (< (point) (org-element-property :end element)))))
24621 ;; Arbitrary list of keywords where checks are meaningful.
24622 ;; Make sure point is on the value part of the element.
24624 (and (member (org-element-property :key element)
24625 '("DESCRIPTION" "TITLE"))
24627 (beginning-of-line) (search-forward ":") (point))
24629 ;; Check is globally allowed in paragraphs verse blocks and
24630 ;; table rows (after affiliated keywords) but some objects
24631 ;; must not be affected.
24632 ((paragraph table-row verse-block)
24633 (let ((cbeg (org-element-property :contents-begin element))
24634 (cend (org-element-property :contents-end element)))
24635 (and cbeg (>= (point) cbeg) (< (point) cend)
24636 (org--flyspell-object-check-p element))))))))))
24637 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24639 (defun org-remove-flyspell-overlays-in (beg end)
24640 "Remove flyspell overlays in region."
24641 (and (org-bound-and-true-p flyspell-mode)
24642 (fboundp 'flyspell-delete-region-overlays)
24643 (flyspell-delete-region-overlays beg end)))
24645 (defvar flyspell-delayed-commands)
24646 (eval-after-load "flyspell"
24647 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24649 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24650 (eval-after-load "bookmark"
24651 '(if (boundp 'bookmark-after-jump-hook)
24652 ;; We can use the hook
24653 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24654 ;; Hook not available, use advice
24655 (defadvice bookmark-jump (after org-make-visible activate)
24656 "Make the position visible."
24657 (org-bookmark-jump-unhide))))
24659 ;; Make sure saveplace shows the location if it was hidden
24660 (eval-after-load "saveplace"
24661 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24662 "Make the position visible."
24663 (org-bookmark-jump-unhide)))
24665 ;; Make sure ecb shows the location if it was hidden
24666 (eval-after-load "ecb"
24667 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24668 "Make hierarchy visible when jumping into location from ECB tree buffer."
24669 (if (derived-mode-p 'org-mode)
24670 (org-show-context))))
24672 (defun org-bookmark-jump-unhide ()
24673 "Unhide the current position, to show the bookmark location."
24674 (and (derived-mode-p 'org-mode)
24675 (or (outline-invisible-p)
24676 (save-excursion (goto-char (max (point-min) (1- (point))))
24677 (outline-invisible-p)))
24678 (org-show-context 'bookmark-jump)))
24680 (defun org-mark-jump-unhide ()
24681 "Make the point visible with `org-show-context' after jumping to the mark."
24682 (when (and (derived-mode-p 'org-mode)
24683 (outline-invisible-p))
24684 (org-show-context 'mark-goto)))
24686 (eval-after-load "simple"
24687 '(defadvice pop-to-mark-command (after org-make-visible activate)
24688 "Make the point visible with `org-show-context'."
24689 (org-mark-jump-unhide)))
24691 (eval-after-load "simple"
24692 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24693 "Make the point visible with `org-show-context'."
24694 (org-mark-jump-unhide)))
24696 (eval-after-load "simple"
24697 '(defadvice pop-global-mark (after org-make-visible activate)
24698 "Make the point visible with `org-show-context'."
24699 (org-mark-jump-unhide)))
24701 ;; Make session.el ignore our circular variable
24702 (defvar session-globals-exclude)
24703 (eval-after-load "session"
24704 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24710 (run-hooks 'org-load-hook)
24712 ;;; org.el ends here