Rewrite `org-entry-properties'
[org-mode/org-tableheadings.git] / lisp / org.el
blob72b281aed9cc829c28241e331bd45e40984136f5
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (equal this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
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
198 "\\`[ \t\n\r]+" ""
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)
204 ;;;###autoload
205 (defun org-babel-do-load-languages (sym value)
206 "Load the languages defined in `org-babel-load-languages'."
207 (set-default sym value)
208 (mapc (lambda (pair)
209 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
210 (if active
211 (progn
212 (require (intern (concat "ob-" lang))))
213 (progn
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))
221 ;;;###autoload
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)
230 (float-time
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)))
239 (setq exported-file
240 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
241 (message "%s %s"
242 (if compile
243 (progn (byte-compile-file exported-file 'load)
244 "Compiled and loaded")
245 (progn (load-file exported-file) "Loaded"))
246 exported-file)))
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."
259 :group 'org-babel
260 :set 'org-babel-do-load-languages
261 :version "24.1"
262 :type '(alist :tag "Babel Languages"
263 :key-type
264 (choice
265 (const :tag "Awk" awk)
266 (const :tag "C" C)
267 (const :tag "R" R)
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)
279 (const :tag "IO" io)
280 (const :tag "J" J)
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
315 identifier."
316 :type 'boolean
317 :version "24.1"
318 :group 'org-id)
320 ;;; Version
321 (org-check-version)
323 ;;;###autoload
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
329 FULL is given."
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")))
335 (org-trash (or
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)"
342 org-version
343 git-version
344 (if org-install-dir
345 (if (string= org-dir org-install-dir)
346 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))
352 version1))
354 (defconst org-version (org-version))
357 ;;; Syntax Constants
359 ;;;; Block
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-planning-line-re
393 (concat "^[ \t]*"
394 (regexp-opt
395 (list org-closed-string org-deadline-string org-scheduled-string)
397 "Matches a line with planning info.
398 Matched keyword is in group 1.")
400 (defconst org-clock-line-re
401 (concat "^[ \t]*" org-clock-string)
402 "Matches a line with clock info.")
404 ;;;; Drawer
406 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
407 "Matches first or last line of a hidden block.
408 Group 1 contains drawer's name or \"END\".")
410 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
411 "Regular expression matching the first line of a property drawer.")
413 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
414 "Regular expression matching the last line of a property drawer.")
416 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
417 "Regular expression matching the first line of a clock drawer.")
419 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
420 "Regular expression matching the last line of a clock drawer.")
422 (defconst org-property-drawer-re
423 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
424 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*"
425 "[ \t]*:END:[ \t]*$")
426 "Matches an entire property drawer.")
428 (defconst org-clock-drawer-re
429 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
430 org-clock-drawer-end-re "\\)\n?")
431 "Matches an entire clock drawer.")
433 ;;;; Headline
435 (defconst org-heading-keyword-regexp-format
436 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
437 "Printf format for a regexp matching a headline with some keyword.
438 This regexp will match the headline of any node which has the
439 exact keyword that is put into the format. The keyword isn't in
440 any group by default, but the stars and the body are.")
442 (defconst org-heading-keyword-maybe-regexp-format
443 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
444 "Printf format for a regexp matching a headline, possibly with some keyword.
445 This regexp can match any headline with the specified keyword, or
446 without a keyword. The keyword isn't in any group by default,
447 but the stars and the body are.")
449 (defconst org-archive-tag "ARCHIVE"
450 "The tag that marks a subtree as archived.
451 An archived subtree does not open during visibility cycling, and does
452 not contribute to the agenda listings.")
454 (defconst org-comment-string "COMMENT"
455 "Entries starting with this keyword will never be exported.
456 An entry can be toggled between COMMENT and normal with
457 \\[org-toggle-comment].")
460 ;;;; LaTeX Environments and Fragments
462 (defconst org-latex-regexps
463 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
464 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
465 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
466 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
467 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
468 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
469 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
470 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
471 "Regular expressions for matching embedded LaTeX.")
473 ;;;; Node Property
475 (defconst org-effort-property "Effort"
476 "The property that is being used to keep track of effort estimates.
477 Effort estimates given in this property need to have the format H:MM.")
479 ;;;; Table
481 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
482 "Detect an org-type or table-type table.")
484 (defconst org-table-line-regexp "^[ \t]*|"
485 "Detect an org-type table line.")
487 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
488 "Detect an org-type table line.")
490 (defconst org-table-hline-regexp "^[ \t]*|-"
491 "Detect an org-type table hline.")
493 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
494 "Detect a table-type table hline.")
496 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
497 "Detect the first line outside a table when searching from within it.
498 This works for both table types.")
500 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
501 "Detect a #+TBLFM line.")
503 ;;;; Timestamp
505 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
506 "Regular expression for fast time stamp matching.")
508 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
509 "Regular expression for fast time stamp matching.")
511 (defconst org-ts-regexp0
512 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
513 "Regular expression matching time strings for analysis.
514 This one does not require the space after the date, so it can be used
515 on a string that terminates immediately after the date.")
517 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
518 "Regular expression matching time strings for analysis.")
520 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
521 "Regular expression matching time stamps, with groups.")
523 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
524 "Regular expression matching time stamps (also [..]), with groups.")
526 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
527 "Regular expression matching a time stamp range.")
529 (defconst org-tr-regexp-both
530 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
531 "Regular expression matching a time stamp range.")
533 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
534 org-ts-regexp "\\)?")
535 "Regular expression matching a time stamp or time stamp range.")
537 (defconst org-tsr-regexp-both
538 (concat org-ts-regexp-both "\\(--?-?"
539 org-ts-regexp-both "\\)?")
540 "Regular expression matching a time stamp or time stamp range.
541 The time stamps may be either active or inactive.")
543 (defconst org-repeat-re
544 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
545 "Regular expression for specifying repeated events.
546 After a match, group 1 contains the repeat expression.")
548 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
549 "Formats for `format-time-string' which are used for time stamps.")
552 ;;; The custom variables
554 (defgroup org nil
555 "Outline-based notes management and organizer."
556 :tag "Org"
557 :group 'outlines
558 :group 'calendar)
560 (defcustom org-mode-hook nil
561 "Mode hook for Org-mode, run after the mode was turned on."
562 :group 'org
563 :type 'hook)
565 (defcustom org-load-hook nil
566 "Hook that is run after org.el has been loaded."
567 :group 'org
568 :type 'hook)
570 (defcustom org-log-buffer-setup-hook nil
571 "Hook that is run after an Org log buffer is created."
572 :group 'org
573 :version "24.1"
574 :type 'hook)
576 (defvar org-modules) ; defined below
577 (defvar org-modules-loaded nil
578 "Have the modules been loaded already?")
580 (defun org-load-modules-maybe (&optional force)
581 "Load all extensions listed in `org-modules'."
582 (when (or force (not org-modules-loaded))
583 (mapc (lambda (ext)
584 (condition-case nil (require ext)
585 (error (message "Problems while trying to load feature `%s'" ext))))
586 org-modules)
587 (setq org-modules-loaded t)))
589 (defun org-set-modules (var value)
590 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
591 (set var value)
592 (when (featurep 'org)
593 (org-load-modules-maybe 'force)
594 (org-element-cache-reset 'all)))
596 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
597 "Modules that should always be loaded together with org.el.
599 If a description starts with <C>, the file is not part of Emacs
600 and loading it will require that you have downloaded and properly
601 installed the Org mode distribution.
603 You can also use this system to load external packages (i.e. neither Org
604 core modules, nor modules from the CONTRIB directory). Just add symbols
605 to the end of the list. If the package is called org-xyz.el, then you need
606 to add the symbol `xyz', and the package must have a call to:
608 \(provide 'org-xyz)
610 For export specific modules, see also `org-export-backends'."
611 :group 'org
612 :set 'org-set-modules
613 :version "24.4"
614 :package-version '(Org . "8.0")
615 :type
616 '(set :greedy t
617 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
618 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
619 (const :tag " crypt: Encryption of subtrees" org-crypt)
620 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
621 (const :tag " docview: Links to doc-view buffers" org-docview)
622 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
623 (const :tag " habit: Track your consistency with habits" org-habit)
624 (const :tag " id: Global IDs for identifying entries" org-id)
625 (const :tag " info: Links to Info nodes" org-info)
626 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
627 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
628 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
629 (const :tag " mouse: Additional mouse support" org-mouse)
630 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
631 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
632 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
634 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
635 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
636 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
637 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
638 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
639 (const :tag "C collector: Collect properties into tables" org-collector)
640 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
641 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
642 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
643 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
644 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
645 (const :tag "C eval: Include command output as text" org-eval)
646 (const :tag "C eww: Store link to url of eww" org-eww)
647 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
648 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
649 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
650 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
651 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
652 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
653 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
654 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
655 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
656 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
657 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
658 (const :tag "C mew: Links to Mew folders/messages" org-mew)
659 (const :tag "C mtags: Support for muse-like tags" org-mtags)
660 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
661 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
662 (const :tag "C registry: A registry for Org-mode links" org-registry)
663 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
664 (const :tag "C secretary: Team management with org-mode" org-secretary)
665 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
666 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
667 (const :tag "C track: Keep up with Org-mode development" org-track)
668 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
669 (const :tag "C vm: Links to VM folders/messages" org-vm)
670 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
671 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
672 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
674 (defvar org-export--registered-backends) ; From ox.el.
675 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
676 (declare-function org-export-backend-name "ox" (backend))
677 (defcustom org-export-backends '(ascii html icalendar latex)
678 "List of export back-ends that should be always available.
680 If a description starts with <C>, the file is not part of Emacs
681 and loading it will require that you have downloaded and properly
682 installed the Org mode distribution.
684 Unlike to `org-modules', libraries in this list will not be
685 loaded along with Org, but only once the export framework is
686 needed.
688 This variable needs to be set before org.el is loaded. If you
689 need to make a change while Emacs is running, use the customize
690 interface or run the following code, where VAL stands for the new
691 value of the variable, after updating it:
693 \(progn
694 \(setq org-export--registered-backends
695 \(org-remove-if-not
696 \(lambda (backend)
697 \(let ((name (org-export-backend-name backend)))
698 \(or (memq name val)
699 \(catch 'parentp
700 \(dolist (b val)
701 \(and (org-export-derived-backend-p b name)
702 \(throw 'parentp t)))))))
703 org-export--registered-backends))
704 \(let ((new-list (mapcar 'org-export-backend-name
705 org-export--registered-backends)))
706 \(dolist (backend val)
707 \(cond
708 \((not (load (format \"ox-%s\" backend) t t))
709 \(message \"Problems while trying to load export back-end `%s'\"
710 backend))
711 \((not (memq backend new-list)) (push backend new-list))))
712 \(set-default 'org-export-backends new-list)))
714 Adding a back-end to this list will also pull the back-end it
715 depends on, if any."
716 :group 'org
717 :group 'org-export
718 :version "24.4"
719 :package-version '(Org . "8.0")
720 :initialize 'custom-initialize-set
721 :set (lambda (var val)
722 (if (not (featurep 'ox)) (set-default var val)
723 ;; Any back-end not required anymore (not present in VAL and not
724 ;; a parent of any back-end in the new value) is removed from the
725 ;; list of registered back-ends.
726 (setq org-export--registered-backends
727 (org-remove-if-not
728 (lambda (backend)
729 (let ((name (org-export-backend-name backend)))
730 (or (memq name val)
731 (catch 'parentp
732 (dolist (b val)
733 (and (org-export-derived-backend-p b name)
734 (throw 'parentp t)))))))
735 org-export--registered-backends))
736 ;; Now build NEW-LIST of both new back-ends and required
737 ;; parents.
738 (let ((new-list (mapcar 'org-export-backend-name
739 org-export--registered-backends)))
740 (dolist (backend val)
741 (cond
742 ((not (load (format "ox-%s" backend) t t))
743 (message "Problems while trying to load export back-end `%s'"
744 backend))
745 ((not (memq backend new-list)) (push backend new-list))))
746 ;; Set VAR to that list with fixed dependencies.
747 (set-default var new-list))))
748 :type '(set :greedy t
749 (const :tag " ascii Export buffer to ASCII format" ascii)
750 (const :tag " beamer Export buffer to Beamer presentation" beamer)
751 (const :tag " html Export buffer to HTML format" html)
752 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
753 (const :tag " latex Export buffer to LaTeX format" latex)
754 (const :tag " man Export buffer to MAN format" man)
755 (const :tag " md Export buffer to Markdown format" md)
756 (const :tag " odt Export buffer to ODT format" odt)
757 (const :tag " org Export buffer to Org format" org)
758 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
759 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
760 (const :tag "C deck Export buffer to deck.js presentations" deck)
761 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
762 (const :tag "C groff Export buffer to Groff format" groff)
763 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
764 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
765 (const :tag "C s5 Export buffer to s5 presentations" s5)
766 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
768 (eval-after-load 'ox
769 '(mapc
770 (lambda (backend)
771 (condition-case nil (require (intern (format "ox-%s" backend)))
772 (error (message "Problems while trying to load export back-end `%s'"
773 backend))))
774 org-export-backends))
776 (defcustom org-support-shift-select nil
777 "Non-nil means make shift-cursor commands select text when possible.
779 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
780 start selecting a region, or enlarge regions started in this way.
781 In Org-mode, in special contexts, these same keys are used for
782 other purposes, important enough to compete with shift selection.
783 Org tries to balance these needs by supporting `shift-select-mode'
784 outside these special contexts, under control of this variable.
786 The default of this variable is nil, to avoid confusing behavior. Shifted
787 cursor keys will then execute Org commands in the following contexts:
788 - on a headline, changing TODO state (left/right) and priority (up/down)
789 - on a time stamp, changing the time
790 - in a plain list item, changing the bullet type
791 - in a property definition line, switching between allowed values
792 - in the BEGIN line of a clock table (changing the time block).
793 Outside these contexts, the commands will throw an error.
795 When this variable is t and the cursor is not in a special
796 context, Org-mode will support shift-selection for making and
797 enlarging regions. To make this more effective, the bullet
798 cycling will no longer happen anywhere in an item line, but only
799 if the cursor is exactly on the bullet.
801 If you set this variable to the symbol `always', then the keys
802 will not be special in headlines, property lines, and item lines,
803 to make shift selection work there as well. If this is what you
804 want, you can use the following alternative commands: `C-c C-t'
805 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
806 can be used to switch TODO sets, `C-c -' to cycle item bullet
807 types, and properties can be edited by hand or in column view.
809 However, when the cursor is on a timestamp, shift-cursor commands
810 will still edit the time stamp - this is just too good to give up.
812 XEmacs user should have this variable set to nil, because
813 `shift-select-mode' is in Emacs 23 or later only."
814 :group 'org
815 :type '(choice
816 (const :tag "Never" nil)
817 (const :tag "When outside special context" t)
818 (const :tag "Everywhere except timestamps" always)))
820 (defcustom org-loop-over-headlines-in-active-region nil
821 "Shall some commands act upon headlines in the active region?
823 When set to `t', some commands will be performed in all headlines
824 within the active region.
826 When set to `start-level', some commands will be performed in all
827 headlines within the active region, provided that these headlines
828 are of the same level than the first one.
830 When set to a string, those commands will be performed on the
831 matching headlines within the active region. Such string must be
832 a tags/property/todo match as it is used in the agenda tags view.
834 The list of commands is: `org-schedule', `org-deadline',
835 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
836 `org-archive-to-archive-sibling'. The archiving commands skip
837 already archived entries."
838 :type '(choice (const :tag "Don't loop" nil)
839 (const :tag "All headlines in active region" t)
840 (const :tag "In active region, headlines at the same level than the first one" start-level)
841 (string :tag "Tags/Property/Todo matcher"))
842 :version "24.1"
843 :group 'org-todo
844 :group 'org-archive)
846 (defgroup org-startup nil
847 "Options concerning startup of Org-mode."
848 :tag "Org Startup"
849 :group 'org)
851 (defcustom org-startup-folded t
852 "Non-nil means entering Org-mode will switch to OVERVIEW.
853 This can also be configured on a per-file basis by adding one of
854 the following lines anywhere in the buffer:
856 #+STARTUP: fold (or `overview', this is equivalent)
857 #+STARTUP: nofold (or `showall', this is equivalent)
858 #+STARTUP: content
859 #+STARTUP: showeverything
861 By default, this option is ignored when Org opens agenda files
862 for the first time. If you want the agenda to honor the startup
863 option, set `org-agenda-inhibit-startup' to nil."
864 :group 'org-startup
865 :type '(choice
866 (const :tag "nofold: show all" nil)
867 (const :tag "fold: overview" t)
868 (const :tag "content: all headlines" content)
869 (const :tag "show everything, even drawers" showeverything)))
871 (defcustom org-startup-truncated t
872 "Non-nil means entering Org-mode will set `truncate-lines'.
873 This is useful since some lines containing links can be very long and
874 uninteresting. Also tables look terrible when wrapped."
875 :group 'org-startup
876 :type 'boolean)
878 (defcustom org-startup-indented nil
879 "Non-nil means turn on `org-indent-mode' on startup.
880 This can also be configured on a per-file basis by adding one of
881 the following lines anywhere in the buffer:
883 #+STARTUP: indent
884 #+STARTUP: noindent"
885 :group 'org-structure
886 :type '(choice
887 (const :tag "Not" nil)
888 (const :tag "Globally (slow on startup in large files)" t)))
890 (defcustom org-use-sub-superscripts t
891 "Non-nil means interpret \"_\" and \"^\" for display.
893 If you want to control how Org exports those characters, see
894 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
895 used to be an alias for `org-export-with-sub-superscripts' in
896 Org <8.0, it is not anymore.
898 When this option is turned on, you can use TeX-like syntax for
899 sub- and superscripts within the buffer. Several characters after
900 \"_\" or \"^\" will be considered as a single item - so grouping
901 with {} is normally not needed. For example, the following things
902 will be parsed as single sub- or superscripts:
904 10^24 or 10^tau several digits will be considered 1 item.
905 10^-12 or 10^-tau a leading sign with digits or a word
906 x^2-y^3 will be read as x^2 - y^3, because items are
907 terminated by almost any nonword/nondigit char.
908 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
910 Still, ambiguity is possible. So when in doubt, use {} to enclose
911 the sub/superscript. If you set this variable to the symbol `{}',
912 the braces are *required* in order to trigger interpretations as
913 sub/superscript. This can be helpful in documents that need \"_\"
914 frequently in plain text."
915 :group 'org-startup
916 :version "24.4"
917 :package-version '(Org . "8.0")
918 :type '(choice
919 (const :tag "Always interpret" t)
920 (const :tag "Only with braces" {})
921 (const :tag "Never interpret" nil)))
923 (defcustom org-startup-with-beamer-mode nil
924 "Non-nil means turn on `org-beamer-mode' on startup.
925 This can also be configured on a per-file basis by adding one of
926 the following lines anywhere in the buffer:
928 #+STARTUP: beamer"
929 :group 'org-startup
930 :version "24.1"
931 :type 'boolean)
933 (defcustom org-startup-align-all-tables nil
934 "Non-nil means align all tables when visiting a file.
935 This is useful when the column width in tables is forced with <N> cookies
936 in table fields. Such tables will look correct only after the first re-align.
937 This can also be configured on a per-file basis by adding one of
938 the following lines anywhere in the buffer:
939 #+STARTUP: align
940 #+STARTUP: noalign"
941 :group 'org-startup
942 :type 'boolean)
944 (defcustom org-startup-with-inline-images nil
945 "Non-nil means show inline images when loading a new Org file.
946 This can also be configured on a per-file basis by adding one of
947 the following lines anywhere in the buffer:
948 #+STARTUP: inlineimages
949 #+STARTUP: noinlineimages"
950 :group 'org-startup
951 :version "24.1"
952 :type 'boolean)
954 (defcustom org-startup-with-latex-preview nil
955 "Non-nil means preview LaTeX fragments when loading a new Org file.
957 This can also be configured on a per-file basis by adding one of
958 the following lines anywhere in the buffer:
959 #+STARTUP: latexpreview
960 #+STARTUP: nolatexpreview"
961 :group 'org-startup
962 :version "24.4"
963 :package-version '(Org . "8.0")
964 :type 'boolean)
966 (defcustom org-insert-mode-line-in-empty-file nil
967 "Non-nil means insert the first line setting Org-mode in empty files.
968 When the function `org-mode' is called interactively in an empty file, this
969 normally means that the file name does not automatically trigger Org-mode.
970 To ensure that the file will always be in Org-mode in the future, a
971 line enforcing Org-mode will be inserted into the buffer, if this option
972 has been set."
973 :group 'org-startup
974 :type 'boolean)
976 (defcustom org-replace-disputed-keys nil
977 "Non-nil means use alternative key bindings for some keys.
978 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
979 These keys are also used by other packages like shift-selection-mode'
980 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
981 If you want to use Org-mode together with one of these other modes,
982 or more generally if you would like to move some Org-mode commands to
983 other keys, set this variable and configure the keys with the variable
984 `org-disputed-keys'.
986 This option is only relevant at load-time of Org-mode, and must be set
987 *before* org.el is loaded. Changing it requires a restart of Emacs to
988 become effective."
989 :group 'org-startup
990 :type 'boolean)
992 (defcustom org-use-extra-keys nil
993 "Non-nil means use extra key sequence definitions for certain commands.
994 This happens automatically if you run XEmacs or if `window-system'
995 is nil. This variable lets you do the same manually. You must
996 set it before loading org.
998 Example: on Carbon Emacs 22 running graphically, with an external
999 keyboard on a Powerbook, the default way of setting M-left might
1000 not work for either Alt or ESC. Setting this variable will make
1001 it work for ESC."
1002 :group 'org-startup
1003 :type 'boolean)
1005 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1007 (defcustom org-disputed-keys
1008 '(([(shift up)] . [(meta p)])
1009 ([(shift down)] . [(meta n)])
1010 ([(shift left)] . [(meta -)])
1011 ([(shift right)] . [(meta +)])
1012 ([(control shift right)] . [(meta shift +)])
1013 ([(control shift left)] . [(meta shift -)]))
1014 "Keys for which Org-mode and other modes compete.
1015 This is an alist, cars are the default keys, second element specifies
1016 the alternative to use when `org-replace-disputed-keys' is t.
1018 Keys can be specified in any syntax supported by `define-key'.
1019 The value of this option takes effect only at Org-mode's startup,
1020 therefore you'll have to restart Emacs to apply it after changing."
1021 :group 'org-startup
1022 :type 'alist)
1024 (defun org-key (key)
1025 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1026 Or return the original if not disputed.
1027 Also apply the translations defined in `org-xemacs-key-equivalents'."
1028 (when org-replace-disputed-keys
1029 (let* ((nkey (key-description key))
1030 (x (org-find-if (lambda (x)
1031 (equal (key-description (car x)) nkey))
1032 org-disputed-keys)))
1033 (setq key (if x (cdr x) key))))
1034 (when (featurep 'xemacs)
1035 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1036 key)
1038 (defun org-find-if (predicate seq)
1039 (catch 'exit
1040 (while seq
1041 (if (funcall predicate (car seq))
1042 (throw 'exit (car seq))
1043 (pop seq)))))
1045 (defun org-defkey (keymap key def)
1046 "Define a key, possibly translated, as returned by `org-key'."
1047 (define-key keymap (org-key key) def))
1049 (defcustom org-ellipsis nil
1050 "The ellipsis to use in the Org-mode outline.
1051 When nil, just use the standard three dots.
1052 When a string, use that string instead.
1053 When a face, use the standard 3 dots, but with the specified face.
1054 The change affects only Org-mode (which will then use its own display table).
1055 Changing this requires executing \\[org-mode] in a buffer to become
1056 effective."
1057 :group 'org-startup
1058 :type '(choice (const :tag "Default" nil)
1059 (face :tag "Face" :value org-warning)
1060 (string :tag "String" :value "...#")))
1062 (defvar org-display-table nil
1063 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1065 (defgroup org-keywords nil
1066 "Keywords in Org-mode."
1067 :tag "Org Keywords"
1068 :group 'org)
1070 (defcustom org-closed-keep-when-no-todo nil
1071 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1072 :group 'org-todo
1073 :group 'org-keywords
1074 :version "24.4"
1075 :package-version '(Org . "8.0")
1076 :type 'boolean)
1078 (defgroup org-structure nil
1079 "Options concerning the general structure of Org-mode files."
1080 :tag "Org Structure"
1081 :group 'org)
1083 (defgroup org-reveal-location nil
1084 "Options about how to make context of a location visible."
1085 :tag "Org Reveal Location"
1086 :group 'org-structure)
1088 (defconst org-context-choice
1089 '(choice
1090 (const :tag "Always" t)
1091 (const :tag "Never" nil)
1092 (repeat :greedy t :tag "Individual contexts"
1093 (cons
1094 (choice :tag "Context"
1095 (const agenda)
1096 (const org-goto)
1097 (const occur-tree)
1098 (const tags-tree)
1099 (const link-search)
1100 (const mark-goto)
1101 (const bookmark-jump)
1102 (const isearch)
1103 (const default))
1104 (boolean))))
1105 "Contexts for the reveal options.")
1107 (defcustom org-show-hierarchy-above '((default . t))
1108 "Non-nil means show full hierarchy when revealing a location.
1109 Org-mode often shows locations in an org-mode file which might have
1110 been invisible before. When this is set, the hierarchy of headings
1111 above the exposed location is shown.
1112 Turning this off for example for sparse trees makes them very compact.
1113 Instead of t, this can also be an alist specifying this option for different
1114 contexts. Valid contexts are
1115 agenda when exposing an entry from the agenda
1116 org-goto when using the command `org-goto' on key C-c C-j
1117 occur-tree when using the command `org-occur' on key C-c /
1118 tags-tree when constructing a sparse tree based on tags matches
1119 link-search when exposing search matches associated with a link
1120 mark-goto when exposing the jump goal of a mark
1121 bookmark-jump when exposing a bookmark location
1122 isearch when exiting from an incremental search
1123 default default for all contexts not set explicitly"
1124 :group 'org-reveal-location
1125 :type org-context-choice)
1127 (defcustom org-show-following-heading '((default . nil))
1128 "Non-nil means show following heading when revealing a location.
1129 Org-mode often shows locations in an org-mode file which might have
1130 been invisible before. When this is set, the heading following the
1131 match is shown.
1132 Turning this off for example for sparse trees makes them very compact,
1133 but makes it harder to edit the location of the match. In such a case,
1134 use the command \\[org-reveal] to show more context.
1135 Instead of t, this can also be an alist specifying this option for different
1136 contexts. See `org-show-hierarchy-above' for valid contexts."
1137 :group 'org-reveal-location
1138 :type org-context-choice)
1140 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1141 "Non-nil means show all sibling heading when revealing a location.
1142 Org-mode often shows locations in an org-mode file which might have
1143 been invisible before. When this is set, the sibling of the current entry
1144 heading are all made visible. If `org-show-hierarchy-above' is t,
1145 the same happens on each level of the hierarchy above the current entry.
1147 By default this is on for the isearch context, off for all other contexts.
1148 Turning this off for example for sparse trees makes them very compact,
1149 but makes it harder to edit the location of the match. In such a case,
1150 use the command \\[org-reveal] to show more context.
1151 Instead of t, this can also be an alist specifying this option for different
1152 contexts. See `org-show-hierarchy-above' for valid contexts."
1153 :group 'org-reveal-location
1154 :type org-context-choice
1155 :version "24.4"
1156 :package-version '(Org . "8.0"))
1158 (defcustom org-show-entry-below '((default . nil))
1159 "Non-nil means show the entry below a headline when revealing a location.
1160 Org-mode often shows locations in an org-mode file which might have
1161 been invisible before. When this is set, the text below the headline that is
1162 exposed is also shown.
1164 By default this is off for all contexts.
1165 Instead of t, this can also be an alist specifying this option for different
1166 contexts. See `org-show-hierarchy-above' for valid contexts."
1167 :group 'org-reveal-location
1168 :type org-context-choice)
1170 (defcustom org-indirect-buffer-display 'other-window
1171 "How should indirect tree buffers be displayed?
1172 This applies to indirect buffers created with the commands
1173 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1174 Valid values are:
1175 current-window Display in the current window
1176 other-window Just display in another window.
1177 dedicated-frame Create one new frame, and re-use it each time.
1178 new-frame Make a new frame each time. Note that in this case
1179 previously-made indirect buffers are kept, and you need to
1180 kill these buffers yourself."
1181 :group 'org-structure
1182 :group 'org-agenda-windows
1183 :type '(choice
1184 (const :tag "In current window" current-window)
1185 (const :tag "In current frame, other window" other-window)
1186 (const :tag "Each time a new frame" new-frame)
1187 (const :tag "One dedicated frame" dedicated-frame)))
1189 (defcustom org-use-speed-commands nil
1190 "Non-nil means activate single letter commands at beginning of a headline.
1191 This may also be a function to test for appropriate locations where speed
1192 commands should be active.
1194 For example, to activate speed commands when the point is on any
1195 star at the beginning of the headline, you can do this:
1197 (setq org-use-speed-commands
1198 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1199 :group 'org-structure
1200 :type '(choice
1201 (const :tag "Never" nil)
1202 (const :tag "At beginning of headline stars" t)
1203 (function)))
1205 (defcustom org-speed-commands-user nil
1206 "Alist of additional speed commands.
1207 This list will be checked before `org-speed-commands-default'
1208 when the variable `org-use-speed-commands' is non-nil
1209 and when the cursor is at the beginning of a headline.
1210 The car if each entry is a string with a single letter, which must
1211 be assigned to `self-insert-command' in the global map.
1212 The cdr is either a command to be called interactively, a function
1213 to be called, or a form to be evaluated.
1214 An entry that is just a list with a single string will be interpreted
1215 as a descriptive headline that will be added when listing the speed
1216 commands in the Help buffer using the `?' speed command."
1217 :group 'org-structure
1218 :type '(repeat :value ("k" . ignore)
1219 (choice :value ("k" . ignore)
1220 (list :tag "Descriptive Headline" (string :tag "Headline"))
1221 (cons :tag "Letter and Command"
1222 (string :tag "Command letter")
1223 (choice
1224 (function)
1225 (sexp))))))
1227 (defcustom org-bookmark-names-plist
1228 '(:last-capture "org-capture-last-stored"
1229 :last-refile "org-refile-last-stored"
1230 :last-capture-marker "org-capture-last-stored-marker")
1231 "Names for bookmarks automatically set by some Org commands.
1232 This can provide strings as names for a number of bookmarks Org sets
1233 automatically. The following keys are currently implemented:
1234 :last-capture
1235 :last-capture-marker
1236 :last-refile
1237 When a key does not show up in the property list, the corresponding bookmark
1238 is not set."
1239 :group 'org-structure
1240 :type 'plist)
1242 (defgroup org-cycle nil
1243 "Options concerning visibility cycling in Org-mode."
1244 :tag "Org Cycle"
1245 :group 'org-structure)
1247 (defcustom org-cycle-skip-children-state-if-no-children t
1248 "Non-nil means skip CHILDREN state in entries that don't have any."
1249 :group 'org-cycle
1250 :type 'boolean)
1252 (defcustom org-cycle-max-level nil
1253 "Maximum level which should still be subject to visibility cycling.
1254 Levels higher than this will, for cycling, be treated as text, not a headline.
1255 When `org-odd-levels-only' is set, a value of N in this variable actually
1256 means 2N-1 stars as the limiting headline.
1257 When nil, cycle all levels.
1258 Note that the limiting level of cycling is also influenced by
1259 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1260 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1261 than its value."
1262 :group 'org-cycle
1263 :type '(choice
1264 (const :tag "No limit" nil)
1265 (integer :tag "Maximum level")))
1267 (defcustom org-hide-block-startup nil
1268 "Non-nil means entering Org-mode will fold all blocks.
1269 This can also be set in on a per-file basis with
1271 #+STARTUP: hideblocks
1272 #+STARTUP: showblocks"
1273 :group 'org-startup
1274 :group 'org-cycle
1275 :type 'boolean)
1277 (defcustom org-cycle-global-at-bob nil
1278 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1279 This makes it possible to do global cycling without having to use S-TAB or
1280 \\[universal-argument] TAB. For this special case to work, the first line
1281 of the buffer must not be a headline -- it may be empty or some other text.
1282 When used in this way, `org-cycle-hook' is disabled temporarily to make
1283 sure the cursor stays at the beginning of the buffer. When this option is
1284 nil, don't do anything special at the beginning of the buffer."
1285 :group 'org-cycle
1286 :type 'boolean)
1288 (defcustom org-cycle-level-after-item/entry-creation t
1289 "Non-nil means cycle entry level or item indentation in new empty entries.
1291 When the cursor is at the end of an empty headline, i.e., with only stars
1292 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1293 and then all possible ancestor states, before returning to the original state.
1294 This makes data entry extremely fast: M-RET to create a new headline,
1295 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1297 When the cursor is at the end of an empty plain list item, one TAB will
1298 make it a subitem, two or more tabs will back up to make this an item
1299 higher up in the item hierarchy."
1300 :group 'org-cycle
1301 :type 'boolean)
1303 (defcustom org-cycle-emulate-tab t
1304 "Where should `org-cycle' emulate TAB.
1305 nil Never
1306 white Only in completely white lines
1307 whitestart Only at the beginning of lines, before the first non-white char
1308 t Everywhere except in headlines
1309 exc-hl-bol Everywhere except at the start of a headline
1310 If TAB is used in a place where it does not emulate TAB, the current subtree
1311 visibility is cycled."
1312 :group 'org-cycle
1313 :type '(choice (const :tag "Never" nil)
1314 (const :tag "Only in completely white lines" white)
1315 (const :tag "Before first char in a line" whitestart)
1316 (const :tag "Everywhere except in headlines" t)
1317 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1319 (defcustom org-cycle-separator-lines 2
1320 "Number of empty lines needed to keep an empty line between collapsed trees.
1321 If you leave an empty line between the end of a subtree and the following
1322 headline, this empty line is hidden when the subtree is folded.
1323 Org-mode will leave (exactly) one empty line visible if the number of
1324 empty lines is equal or larger to the number given in this variable.
1325 So the default 2 means at least 2 empty lines after the end of a subtree
1326 are needed to produce free space between a collapsed subtree and the
1327 following headline.
1329 If the number is negative, and the number of empty lines is at least -N,
1330 all empty lines are shown.
1332 Special case: when 0, never leave empty lines in collapsed view."
1333 :group 'org-cycle
1334 :type 'integer)
1335 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1337 (defcustom org-pre-cycle-hook nil
1338 "Hook that is run before visibility cycling is happening.
1339 The function(s) in this hook must accept a single argument which indicates
1340 the new state that will be set right after running this hook. The
1341 argument is a symbol. Before a global state change, it can have the values
1342 `overview', `content', or `all'. Before a local state change, it can have
1343 the values `folded', `children', or `subtree'."
1344 :group 'org-cycle
1345 :type 'hook)
1347 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1348 org-cycle-hide-drawers
1349 org-cycle-hide-inline-tasks
1350 org-cycle-show-empty-lines
1351 org-optimize-window-after-visibility-change)
1352 "Hook that is run after `org-cycle' has changed the buffer visibility.
1353 The function(s) in this hook must accept a single argument which indicates
1354 the new state that was set by the most recent `org-cycle' command. The
1355 argument is a symbol. After a global state change, it can have the values
1356 `overview', `contents', or `all'. After a local state change, it can have
1357 the values `folded', `children', or `subtree'."
1358 :group 'org-cycle
1359 :type 'hook)
1361 (defgroup org-edit-structure nil
1362 "Options concerning structure editing in Org-mode."
1363 :tag "Org Edit Structure"
1364 :group 'org-structure)
1366 (defcustom org-odd-levels-only nil
1367 "Non-nil means skip even levels and only use odd levels for the outline.
1368 This has the effect that two stars are being added/taken away in
1369 promotion/demotion commands. It also influences how levels are
1370 handled by the exporters.
1371 Changing it requires restart of `font-lock-mode' to become effective
1372 for fontification also in regions already fontified.
1373 You may also set this on a per-file basis by adding one of the following
1374 lines to the buffer:
1376 #+STARTUP: odd
1377 #+STARTUP: oddeven"
1378 :group 'org-edit-structure
1379 :group 'org-appearance
1380 :type 'boolean)
1382 (defcustom org-adapt-indentation t
1383 "Non-nil means adapt indentation to outline node level.
1385 When this variable is set, Org assumes that you write outlines by
1386 indenting text in each node to align with the headline (after the stars).
1387 The following issues are influenced by this variable:
1389 - When this is set and the *entire* text in an entry is indented, the
1390 indentation is increased by one space in a demotion command, and
1391 decreased by one in a promotion command. If any line in the entry
1392 body starts with text at column 0, indentation is not changed at all.
1394 - Property drawers and planning information is inserted indented when
1395 this variable s set. When nil, they will not be indented.
1397 - TAB indents a line relative to context. The lines below a headline
1398 will be indented when this variable is set.
1400 Note that this is all about true indentation, by adding and removing
1401 space characters. See also `org-indent.el' which does level-dependent
1402 indentation in a virtual way, i.e. at display time in Emacs."
1403 :group 'org-edit-structure
1404 :type 'boolean)
1406 (defcustom org-special-ctrl-a/e nil
1407 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1409 When t, `C-a' will bring back the cursor to the beginning of the
1410 headline text, i.e. after the stars and after a possible TODO
1411 keyword. In an item, this will be the position after bullet and
1412 check-box, if any. When the cursor is already at that position,
1413 another `C-a' will bring it to the beginning of the line.
1415 `C-e' will jump to the end of the headline, ignoring the presence
1416 of tags in the headline. A second `C-e' will then jump to the
1417 true end of the line, after any tags. This also means that, when
1418 this variable is non-nil, `C-e' also will never jump beyond the
1419 end of the heading of a folded section, i.e. not after the
1420 ellipses.
1422 When set to the symbol `reversed', the first `C-a' or `C-e' works
1423 normally, going to the true line boundary first. Only a directly
1424 following, identical keypress will bring the cursor to the
1425 special positions.
1427 This may also be a cons cell where the behavior for `C-a' and
1428 `C-e' is set separately."
1429 :group 'org-edit-structure
1430 :type '(choice
1431 (const :tag "off" nil)
1432 (const :tag "on: after stars/bullet and before tags first" t)
1433 (const :tag "reversed: true line boundary first" reversed)
1434 (cons :tag "Set C-a and C-e separately"
1435 (choice :tag "Special C-a"
1436 (const :tag "off" nil)
1437 (const :tag "on: after stars/bullet first" t)
1438 (const :tag "reversed: before stars/bullet first" reversed))
1439 (choice :tag "Special C-e"
1440 (const :tag "off" nil)
1441 (const :tag "on: before tags first" t)
1442 (const :tag "reversed: after tags first" reversed)))))
1443 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1445 (defcustom org-special-ctrl-k nil
1446 "Non-nil means `C-k' will behave specially in headlines.
1447 When nil, `C-k' will call the default `kill-line' command.
1448 When t, the following will happen while the cursor is in the headline:
1450 - When the cursor is at the beginning of a headline, kill the entire
1451 line and possible the folded subtree below the line.
1452 - When in the middle of the headline text, kill the headline up to the tags.
1453 - When after the headline text, kill the tags."
1454 :group 'org-edit-structure
1455 :type 'boolean)
1457 (defcustom org-ctrl-k-protect-subtree nil
1458 "Non-nil means, do not delete a hidden subtree with C-k.
1459 When set to the symbol `error', simply throw an error when C-k is
1460 used to kill (part-of) a headline that has hidden text behind it.
1461 Any other non-nil value will result in a query to the user, if it is
1462 OK to kill that hidden subtree. When nil, kill without remorse."
1463 :group 'org-edit-structure
1464 :version "24.1"
1465 :type '(choice
1466 (const :tag "Do not protect hidden subtrees" nil)
1467 (const :tag "Protect hidden subtrees with a security query" t)
1468 (const :tag "Never kill a hidden subtree with C-k" error)))
1470 (defcustom org-special-ctrl-o t
1471 "Non-nil means, make `C-o' insert a row in tables."
1472 :group 'org-edit-structure
1473 :type 'boolean)
1475 (defcustom org-catch-invisible-edits nil
1476 "Check if in invisible region before inserting or deleting a character.
1477 Valid values are:
1479 nil Do not check, so just do invisible edits.
1480 error Throw an error and do nothing.
1481 show Make point visible, and do the requested edit.
1482 show-and-error Make point visible, then throw an error and abort the edit.
1483 smart Make point visible, and do insertion/deletion if it is
1484 adjacent to visible text and the change feels predictable.
1485 Never delete a previously invisible character or add in the
1486 middle or right after an invisible region. Basically, this
1487 allows insertion and backward-delete right before ellipses.
1488 FIXME: maybe in this case we should not even show?"
1489 :group 'org-edit-structure
1490 :version "24.1"
1491 :type '(choice
1492 (const :tag "Do not check" nil)
1493 (const :tag "Throw error when trying to edit" error)
1494 (const :tag "Unhide, but do not do the edit" show-and-error)
1495 (const :tag "Show invisible part and do the edit" show)
1496 (const :tag "Be smart and do the right thing" smart)))
1498 (defcustom org-yank-folded-subtrees t
1499 "Non-nil means when yanking subtrees, fold them.
1500 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1501 it starts with a heading and all other headings in it are either children
1502 or siblings, then fold all the subtrees. However, do this only if no
1503 text after the yank would be swallowed into a folded tree by this action."
1504 :group 'org-edit-structure
1505 :type 'boolean)
1507 (defcustom org-yank-adjusted-subtrees nil
1508 "Non-nil means when yanking subtrees, adjust the level.
1509 With this setting, `org-paste-subtree' is used to insert the subtree, see
1510 this function for details."
1511 :group 'org-edit-structure
1512 :type 'boolean)
1514 (defcustom org-M-RET-may-split-line '((default . t))
1515 "Non-nil means M-RET will split the line at the cursor position.
1516 When nil, it will go to the end of the line before making a
1517 new line.
1518 You may also set this option in a different way for different
1519 contexts. Valid contexts are:
1521 headline when creating a new headline
1522 item when creating a new item
1523 table in a table field
1524 default the value to be used for all contexts not explicitly
1525 customized"
1526 :group 'org-structure
1527 :group 'org-table
1528 :type '(choice
1529 (const :tag "Always" t)
1530 (const :tag "Never" nil)
1531 (repeat :greedy t :tag "Individual contexts"
1532 (cons
1533 (choice :tag "Context"
1534 (const headline)
1535 (const item)
1536 (const table)
1537 (const default))
1538 (boolean)))))
1541 (defcustom org-insert-heading-respect-content nil
1542 "Non-nil means insert new headings after the current subtree.
1543 When nil, the new heading is created directly after the current line.
1544 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1545 this variable on for the duration of the command."
1546 :group 'org-structure
1547 :type 'boolean)
1549 (defcustom org-blank-before-new-entry '((heading . auto)
1550 (plain-list-item . auto))
1551 "Should `org-insert-heading' leave a blank line before new heading/item?
1552 The value is an alist, with `heading' and `plain-list-item' as CAR,
1553 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1554 which case Org will look at the surrounding headings/items and try to
1555 make an intelligent decision whether to insert a blank line or not.
1557 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1558 the setting here is ignored and no empty line is inserted to avoid breaking
1559 the list structure."
1560 :group 'org-edit-structure
1561 :type '(list
1562 (cons (const heading)
1563 (choice (const :tag "Never" nil)
1564 (const :tag "Always" t)
1565 (const :tag "Auto" auto)))
1566 (cons (const plain-list-item)
1567 (choice (const :tag "Never" nil)
1568 (const :tag "Always" t)
1569 (const :tag "Auto" auto)))))
1571 (defcustom org-insert-heading-hook nil
1572 "Hook being run after inserting a new heading."
1573 :group 'org-edit-structure
1574 :type 'hook)
1576 (defcustom org-enable-fixed-width-editor t
1577 "Non-nil means lines starting with \":\" are treated as fixed-width.
1578 This currently only means they are never auto-wrapped.
1579 When nil, such lines will be treated like ordinary lines."
1580 :group 'org-edit-structure
1581 :type 'boolean)
1583 (defcustom org-goto-auto-isearch t
1584 "Non-nil means typing characters in `org-goto' starts incremental search.
1585 When nil, you can use these keybindings to navigate the buffer:
1587 q Quit the org-goto interface
1588 n Go to the next visible heading
1589 p Go to the previous visible heading
1590 f Go one heading forward on same level
1591 b Go one heading backward on same level
1592 u Go one heading up"
1593 :group 'org-edit-structure
1594 :type 'boolean)
1596 (defgroup org-sparse-trees nil
1597 "Options concerning sparse trees in Org-mode."
1598 :tag "Org Sparse Trees"
1599 :group 'org-structure)
1601 (defcustom org-highlight-sparse-tree-matches t
1602 "Non-nil means highlight all matches that define a sparse tree.
1603 The highlights will automatically disappear the next time the buffer is
1604 changed by an edit command."
1605 :group 'org-sparse-trees
1606 :type 'boolean)
1608 (defcustom org-remove-highlights-with-change t
1609 "Non-nil means any change to the buffer will remove temporary highlights.
1610 Such highlights are created by `org-occur' and `org-clock-display'.
1611 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1612 The highlights created by `org-toggle-latex-fragment' always need
1613 `C-c C-x C-l' to be removed."
1614 :group 'org-sparse-trees
1615 :group 'org-time
1616 :type 'boolean)
1619 (defcustom org-occur-hook '(org-first-headline-recenter)
1620 "Hook that is run after `org-occur' has constructed a sparse tree.
1621 This can be used to recenter the window to show as much of the structure
1622 as possible."
1623 :group 'org-sparse-trees
1624 :type 'hook)
1626 (defgroup org-imenu-and-speedbar nil
1627 "Options concerning imenu and speedbar in Org-mode."
1628 :tag "Org Imenu and Speedbar"
1629 :group 'org-structure)
1631 (defcustom org-imenu-depth 2
1632 "The maximum level for Imenu access to Org-mode headlines.
1633 This also applied for speedbar access."
1634 :group 'org-imenu-and-speedbar
1635 :type 'integer)
1637 (defgroup org-table nil
1638 "Options concerning tables in Org-mode."
1639 :tag "Org Table"
1640 :group 'org)
1642 (defcustom org-enable-table-editor 'optimized
1643 "Non-nil means lines starting with \"|\" are handled by the table editor.
1644 When nil, such lines will be treated like ordinary lines.
1646 When equal to the symbol `optimized', the table editor will be optimized to
1647 do the following:
1648 - Automatic overwrite mode in front of whitespace in table fields.
1649 This makes the structure of the table stay in tact as long as the edited
1650 field does not exceed the column width.
1651 - Minimize the number of realigns. Normally, the table is aligned each time
1652 TAB or RET are pressed to move to another field. With optimization this
1653 happens only if changes to a field might have changed the column width.
1654 Optimization requires replacing the functions `self-insert-command',
1655 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1656 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1657 very good at guessing when a re-align will be necessary, but you can always
1658 force one with \\[org-ctrl-c-ctrl-c].
1660 If you would like to use the optimized version in Org-mode, but the
1661 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1663 This variable can be used to turn on and off the table editor during a session,
1664 but in order to toggle optimization, a restart is required.
1666 See also the variable `org-table-auto-blank-field'."
1667 :group 'org-table
1668 :type '(choice
1669 (const :tag "off" nil)
1670 (const :tag "on" t)
1671 (const :tag "on, optimized" optimized)))
1673 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1674 (version<= emacs-version "24.1"))
1675 "Non-nil means cluster self-insert commands for undo when possible.
1676 If this is set, then, like in the Emacs command loop, 20 consecutive
1677 characters will be undone together.
1678 This is configurable, because there is some impact on typing performance."
1679 :group 'org-table
1680 :type 'boolean)
1682 (defcustom org-table-tab-recognizes-table.el t
1683 "Non-nil means TAB will automatically notice a table.el table.
1684 When it sees such a table, it moves point into it and - if necessary -
1685 calls `table-recognize-table'."
1686 :group 'org-table-editing
1687 :type 'boolean)
1689 (defgroup org-link nil
1690 "Options concerning links in Org-mode."
1691 :tag "Org Link"
1692 :group 'org)
1694 (defvar org-link-abbrev-alist-local nil
1695 "Buffer-local version of `org-link-abbrev-alist', which see.
1696 The value of this is taken from the #+LINK lines.")
1697 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1699 (defcustom org-link-abbrev-alist nil
1700 "Alist of link abbreviations.
1701 The car of each element is a string, to be replaced at the start of a link.
1702 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1703 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1705 [[linkkey:tag][description]]
1707 The 'linkkey' must be a word word, starting with a letter, followed
1708 by letters, numbers, '-' or '_'.
1710 If REPLACE is a string, the tag will simply be appended to create the link.
1711 If the string contains \"%s\", the tag will be inserted there. If the string
1712 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1713 at that point (see the function `url-hexify-string'). If the string contains
1714 the specifier \"%(my-function)\", then the custom function `my-function' will
1715 be invoked: this function takes the tag as its only argument and must return
1716 a string.
1718 REPLACE may also be a function that will be called with the tag as the
1719 only argument to create the link, which should be returned as a string.
1721 See the manual for examples."
1722 :group 'org-link
1723 :type '(repeat
1724 (cons
1725 (string :tag "Protocol")
1726 (choice
1727 (string :tag "Format")
1728 (function)))))
1730 (defcustom org-descriptive-links t
1731 "Non-nil means Org will display descriptive links.
1732 E.g. [[http://orgmode.org][Org website]] will be displayed as
1733 \"Org Website\", hiding the link itself and just displaying its
1734 description. When set to `nil', Org will display the full links
1735 literally.
1737 You can interactively set the value of this variable by calling
1738 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1739 :group 'org-link
1740 :type 'boolean)
1742 (defcustom org-link-file-path-type 'adaptive
1743 "How the path name in file links should be stored.
1744 Valid values are:
1746 relative Relative to the current directory, i.e. the directory of the file
1747 into which the link is being inserted.
1748 absolute Absolute path, if possible with ~ for home directory.
1749 noabbrev Absolute path, no abbreviation of home directory.
1750 adaptive Use relative path for files in the current directory and sub-
1751 directories of it. For other files, use an absolute path."
1752 :group 'org-link
1753 :type '(choice
1754 (const relative)
1755 (const absolute)
1756 (const noabbrev)
1757 (const adaptive)))
1759 (defvaralias 'org-activate-links 'org-highlight-links)
1760 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1761 "Types of links that should be highlighted in Org-mode files.
1763 This is a list of symbols, each one of them leading to the
1764 highlighting of a certain link type.
1766 You can still open links that are not highlighted.
1768 In principle, it does not hurt to turn on highlighting for all
1769 link types. There may be a small gain when turning off unused
1770 link types. The types are:
1772 bracket The recommended [[link][description]] or [[link]] links with hiding.
1773 angle Links in angular brackets that may contain whitespace like
1774 <bbdb:Carsten Dominik>.
1775 plain Plain links in normal text, no whitespace, like http://google.com.
1776 radio Text that is matched by a radio target, see manual for details.
1777 tag Tag settings in a headline (link to tag search).
1778 date Time stamps (link to calendar).
1779 footnote Footnote labels.
1781 If you set this variable during an Emacs session, use `org-mode-restart'
1782 in the Org buffer so that the change takes effect."
1783 :group 'org-link
1784 :group 'org-appearance
1785 :type '(set :greedy t
1786 (const :tag "Double bracket links" bracket)
1787 (const :tag "Angular bracket links" angle)
1788 (const :tag "Plain text links" plain)
1789 (const :tag "Radio target matches" radio)
1790 (const :tag "Tags" tag)
1791 (const :tag "Timestamps" date)
1792 (const :tag "Footnotes" footnote)))
1794 (defcustom org-make-link-description-function nil
1795 "Function to use for generating link descriptions from links.
1796 When nil, the link location will be used. This function must take
1797 two parameters: the first one is the link, the second one is the
1798 description generated by `org-insert-link'. The function should
1799 return the description to use."
1800 :group 'org-link
1801 :type '(choice (const nil) (function)))
1803 (defgroup org-link-store nil
1804 "Options concerning storing links in Org-mode."
1805 :tag "Org Store Link"
1806 :group 'org-link)
1808 (defcustom org-url-hexify-p t
1809 "When non-nil, hexify URL when creating a link."
1810 :type 'boolean
1811 :version "24.3"
1812 :group 'org-link-store)
1814 (defcustom org-email-link-description-format "Email %c: %.30s"
1815 "Format of the description part of a link to an email or usenet message.
1816 The following %-escapes will be replaced by corresponding information:
1818 %F full \"From\" field
1819 %f name, taken from \"From\" field, address if no name
1820 %T full \"To\" field
1821 %t first name in \"To\" field, address if no name
1822 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1823 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1824 %s subject
1825 %d date
1826 %m message-id.
1828 You may use normal field width specification between the % and the letter.
1829 This is for example useful to limit the length of the subject.
1831 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1832 :group 'org-link-store
1833 :type 'string)
1835 (defcustom org-from-is-user-regexp
1836 (let (r1 r2)
1837 (when (and user-mail-address (not (string= user-mail-address "")))
1838 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1839 (when (and user-full-name (not (string= user-full-name "")))
1840 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1841 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1842 "Regexp matched against the \"From:\" header of an email or usenet message.
1843 It should match if the message is from the user him/herself."
1844 :group 'org-link-store
1845 :type 'regexp)
1847 (defcustom org-context-in-file-links t
1848 "Non-nil means file links from `org-store-link' contain context.
1849 A search string will be added to the file name with :: as separator and
1850 used to find the context when the link is activated by the command
1851 `org-open-at-point'. When this option is t, the entire active region
1852 will be placed in the search string of the file link. If set to a
1853 positive integer, only the first n lines of context will be stored.
1855 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1856 negates this setting for the duration of the command."
1857 :group 'org-link-store
1858 :type '(choice boolean integer))
1860 (defcustom org-keep-stored-link-after-insertion nil
1861 "Non-nil means keep link in list for entire session.
1863 The command `org-store-link' adds a link pointing to the current
1864 location to an internal list. These links accumulate during a session.
1865 The command `org-insert-link' can be used to insert links into any
1866 Org-mode file (offering completion for all stored links). When this
1867 option is nil, every link which has been inserted once using \\[org-insert-link]
1868 will be removed from the list, to make completing the unused links
1869 more efficient."
1870 :group 'org-link-store
1871 :type 'boolean)
1873 (defgroup org-link-follow nil
1874 "Options concerning following links in Org-mode."
1875 :tag "Org Follow Link"
1876 :group 'org-link)
1878 (defcustom org-link-translation-function nil
1879 "Function to translate links with different syntax to Org syntax.
1880 This can be used to translate links created for example by the Planner
1881 or emacs-wiki packages to Org syntax.
1882 The function must accept two parameters, a TYPE containing the link
1883 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1884 which is everything after the link protocol. It should return a cons
1885 with possibly modified values of type and path.
1886 Org contains a function for this, so if you set this variable to
1887 `org-translate-link-from-planner', you should be able follow many
1888 links created by planner."
1889 :group 'org-link-follow
1890 :type '(choice (const nil) (function)))
1892 (defcustom org-follow-link-hook nil
1893 "Hook that is run after a link has been followed."
1894 :group 'org-link-follow
1895 :type 'hook)
1897 (defcustom org-tab-follows-link nil
1898 "Non-nil means on links TAB will follow the link.
1899 Needs to be set before org.el is loaded.
1900 This really should not be used, it does not make sense, and the
1901 implementation is bad."
1902 :group 'org-link-follow
1903 :type 'boolean)
1905 (defcustom org-return-follows-link nil
1906 "Non-nil means on links RET will follow the link.
1907 In tables, the special behavior of RET has precedence."
1908 :group 'org-link-follow
1909 :type 'boolean)
1911 (defcustom org-mouse-1-follows-link
1912 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1913 "Non-nil means mouse-1 on a link will follow the link.
1914 A longer mouse click will still set point. Does not work on XEmacs.
1915 Needs to be set before org.el is loaded."
1916 :group 'org-link-follow
1917 :version "24.4"
1918 :package-version '(Org . "8.3")
1919 :type '(choice
1920 (const :tag "A double click follows the link" double)
1921 (const :tag "Unconditionally follow the link with mouse-1" t)
1922 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1924 (defcustom org-mark-ring-length 4
1925 "Number of different positions to be recorded in the ring.
1926 Changing this requires a restart of Emacs to work correctly."
1927 :group 'org-link-follow
1928 :type 'integer)
1930 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1931 "Non-nil means internal links in Org files must exactly match a headline.
1932 When nil, the link search tries to match a phrase with all words
1933 in the search text."
1934 :group 'org-link-follow
1935 :version "24.1"
1936 :type '(choice
1937 (const :tag "Use fuzzy text search" nil)
1938 (const :tag "Match only exact headline" t)
1939 (const :tag "Match exact headline or query to create it"
1940 query-to-create)))
1942 (defcustom org-link-frame-setup
1943 '((vm . vm-visit-folder-other-frame)
1944 (vm-imap . vm-visit-imap-folder-other-frame)
1945 (gnus . org-gnus-no-new-news)
1946 (file . find-file-other-window)
1947 (wl . wl-other-frame))
1948 "Setup the frame configuration for following links.
1949 When following a link with Emacs, it may often be useful to display
1950 this link in another window or frame. This variable can be used to
1951 set this up for the different types of links.
1952 For VM, use any of
1953 `vm-visit-folder'
1954 `vm-visit-folder-other-window'
1955 `vm-visit-folder-other-frame'
1956 For Gnus, use any of
1957 `gnus'
1958 `gnus-other-frame'
1959 `org-gnus-no-new-news'
1960 For FILE, use any of
1961 `find-file'
1962 `find-file-other-window'
1963 `find-file-other-frame'
1964 For Wanderlust use any of
1965 `wl'
1966 `wl-other-frame'
1967 For the calendar, use the variable `calendar-setup'.
1968 For BBDB, it is currently only possible to display the matches in
1969 another window."
1970 :group 'org-link-follow
1971 :type '(list
1972 (cons (const vm)
1973 (choice
1974 (const vm-visit-folder)
1975 (const vm-visit-folder-other-window)
1976 (const vm-visit-folder-other-frame)))
1977 (cons (const vm-imap)
1978 (choice
1979 (const vm-visit-imap-folder)
1980 (const vm-visit-imap-folder-other-window)
1981 (const vm-visit-imap-folder-other-frame)))
1982 (cons (const gnus)
1983 (choice
1984 (const gnus)
1985 (const gnus-other-frame)
1986 (const org-gnus-no-new-news)))
1987 (cons (const file)
1988 (choice
1989 (const find-file)
1990 (const find-file-other-window)
1991 (const find-file-other-frame)))
1992 (cons (const wl)
1993 (choice
1994 (const wl)
1995 (const wl-other-frame)))))
1997 (defcustom org-display-internal-link-with-indirect-buffer nil
1998 "Non-nil means use indirect buffer to display infile links.
1999 Activating internal links (from one location in a file to another location
2000 in the same file) normally just jumps to the location. When the link is
2001 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2002 is displayed in
2003 another window. When this option is set, the other window actually displays
2004 an indirect buffer clone of the current buffer, to avoid any visibility
2005 changes to the current buffer."
2006 :group 'org-link-follow
2007 :type 'boolean)
2009 (defcustom org-open-non-existing-files nil
2010 "Non-nil means `org-open-file' will open non-existing files.
2011 When nil, an error will be generated.
2012 This variable applies only to external applications because they
2013 might choke on non-existing files. If the link is to a file that
2014 will be opened in Emacs, the variable is ignored."
2015 :group 'org-link-follow
2016 :type 'boolean)
2018 (defcustom org-open-directory-means-index-dot-org nil
2019 "Non-nil means a link to a directory really means to index.org.
2020 When nil, following a directory link will run dired or open a finder/explorer
2021 window on that directory."
2022 :group 'org-link-follow
2023 :type 'boolean)
2025 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2026 "Non-nil means ask for confirmation before executing shell links.
2027 Shell links can be dangerous: just think about a link
2029 [[shell:rm -rf ~/*][Google Search]]
2031 This link would show up in your Org-mode document as \"Google Search\",
2032 but really it would remove your entire home directory.
2033 Therefore we advise against setting this variable to nil.
2034 Just change it to `y-or-n-p' if you want to confirm with a
2035 single keystroke rather than having to type \"yes\"."
2036 :group 'org-link-follow
2037 :type '(choice
2038 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2039 (const :tag "with y-or-n (faster)" y-or-n-p)
2040 (const :tag "no confirmation (dangerous)" nil)))
2041 (put 'org-confirm-shell-link-function
2042 'safe-local-variable
2043 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2045 (defcustom org-confirm-shell-link-not-regexp ""
2046 "A regexp to skip confirmation for shell links."
2047 :group 'org-link-follow
2048 :version "24.1"
2049 :type 'regexp)
2051 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2052 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2053 Elisp links can be dangerous: just think about a link
2055 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2057 This link would show up in your Org-mode document as \"Google Search\",
2058 but really it would remove your entire home directory.
2059 Therefore we advise against setting this variable to nil.
2060 Just change it to `y-or-n-p' if you want to confirm with a
2061 single keystroke rather than having to type \"yes\"."
2062 :group 'org-link-follow
2063 :type '(choice
2064 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2065 (const :tag "with y-or-n (faster)" y-or-n-p)
2066 (const :tag "no confirmation (dangerous)" nil)))
2067 (put 'org-confirm-shell-link-function
2068 'safe-local-variable
2069 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2071 (defcustom org-confirm-elisp-link-not-regexp ""
2072 "A regexp to skip confirmation for Elisp links."
2073 :group 'org-link-follow
2074 :version "24.1"
2075 :type 'regexp)
2077 (defconst org-file-apps-defaults-gnu
2078 '((remote . emacs)
2079 (system . mailcap)
2080 (t . mailcap))
2081 "Default file applications on a UNIX or GNU/Linux system.
2082 See `org-file-apps'.")
2084 (defconst org-file-apps-defaults-macosx
2085 '((remote . emacs)
2086 (t . "open %s")
2087 (system . "open %s")
2088 ("ps.gz" . "gv %s")
2089 ("eps.gz" . "gv %s")
2090 ("dvi" . "xdvi %s")
2091 ("fig" . "xfig %s"))
2092 "Default file applications on a MacOS X system.
2093 The system \"open\" is known as a default, but we use X11 applications
2094 for some files for which the OS does not have a good default.
2095 See `org-file-apps'.")
2097 (defconst org-file-apps-defaults-windowsnt
2098 (list
2099 '(remote . emacs)
2100 (cons t
2101 (list (if (featurep 'xemacs)
2102 'mswindows-shell-execute
2103 'w32-shell-execute)
2104 "open" 'file))
2105 (cons 'system
2106 (list (if (featurep 'xemacs)
2107 'mswindows-shell-execute
2108 'w32-shell-execute)
2109 "open" 'file)))
2110 "Default file applications on a Windows NT system.
2111 The system \"open\" is used for most files.
2112 See `org-file-apps'.")
2114 (defcustom org-file-apps
2115 '((auto-mode . emacs)
2116 ("\\.mm\\'" . default)
2117 ("\\.x?html?\\'" . default)
2118 ("\\.pdf\\'" . default))
2119 "External applications for opening `file:path' items in a document.
2120 Org-mode uses system defaults for different file types, but
2121 you can use this variable to set the application for a given file
2122 extension. The entries in this list are cons cells where the car identifies
2123 files and the cdr the corresponding command. Possible values for the
2124 file identifier are
2125 \"string\" A string as a file identifier can be interpreted in different
2126 ways, depending on its contents:
2128 - Alphanumeric characters only:
2129 Match links with this file extension.
2130 Example: (\"pdf\" . \"evince %s\")
2131 to open PDFs with evince.
2133 - Regular expression: Match links where the
2134 filename matches the regexp. If you want to
2135 use groups here, use shy groups.
2137 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2138 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2139 to open *.html and *.xhtml with firefox.
2141 - Regular expression which contains (non-shy) groups:
2142 Match links where the whole link, including \"::\", and
2143 anything after that, matches the regexp.
2144 In a custom command string, %1, %2, etc. are replaced with
2145 the parts of the link that were matched by the groups.
2146 For backwards compatibility, if a command string is given
2147 that does not use any of the group matches, this case is
2148 handled identically to the second one (i.e. match against
2149 file name only).
2150 In a custom lisp form, you can access the group matches with
2151 (match-string n link).
2153 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2154 to open [[file:document.pdf::5]] with evince at page 5.
2156 `directory' Matches a directory
2157 `remote' Matches a remote file, accessible through tramp or efs.
2158 Remote files most likely should be visited through Emacs
2159 because external applications cannot handle such paths.
2160 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2161 so all files Emacs knows how to handle. Using this with
2162 command `emacs' will open most files in Emacs. Beware that this
2163 will also open html files inside Emacs, unless you add
2164 (\"html\" . default) to the list as well.
2165 t Default for files not matched by any of the other options.
2166 `system' The system command to open files, like `open' on Windows
2167 and Mac OS X, and mailcap under GNU/Linux. This is the command
2168 that will be selected if you call `C-c C-o' with a double
2169 \\[universal-argument] \\[universal-argument] prefix.
2171 Possible values for the command are:
2172 `emacs' The file will be visited by the current Emacs process.
2173 `default' Use the default application for this file type, which is the
2174 association for t in the list, most likely in the system-specific
2175 part.
2176 This can be used to overrule an unwanted setting in the
2177 system-specific variable.
2178 `system' Use the system command for opening files, like \"open\".
2179 This command is specified by the entry whose car is `system'.
2180 Most likely, the system-specific version of this variable
2181 does define this command, but you can overrule/replace it
2182 here.
2183 string A command to be executed by a shell; %s will be replaced
2184 by the path to the file.
2185 sexp A Lisp form which will be evaluated. The file path will
2186 be available in the Lisp variable `file'.
2187 For more examples, see the system specific constants
2188 `org-file-apps-defaults-macosx'
2189 `org-file-apps-defaults-windowsnt'
2190 `org-file-apps-defaults-gnu'."
2191 :group 'org-link-follow
2192 :type '(repeat
2193 (cons (choice :value ""
2194 (string :tag "Extension")
2195 (const :tag "System command to open files" system)
2196 (const :tag "Default for unrecognized files" t)
2197 (const :tag "Remote file" remote)
2198 (const :tag "Links to a directory" directory)
2199 (const :tag "Any files that have Emacs modes"
2200 auto-mode))
2201 (choice :value ""
2202 (const :tag "Visit with Emacs" emacs)
2203 (const :tag "Use default" default)
2204 (const :tag "Use the system command" system)
2205 (string :tag "Command")
2206 (sexp :tag "Lisp form")))))
2208 (defcustom org-doi-server-url "http://dx.doi.org/"
2209 "The URL of the DOI server."
2210 :type 'string
2211 :version "24.3"
2212 :group 'org-link-follow)
2214 (defgroup org-refile nil
2215 "Options concerning refiling entries in Org-mode."
2216 :tag "Org Refile"
2217 :group 'org)
2219 (defcustom org-directory "~/org"
2220 "Directory with org files.
2221 This is just a default location to look for Org files. There is no need
2222 at all to put your files into this directory. It is only used in the
2223 following situations:
2225 1. When a capture template specifies a target file that is not an
2226 absolute path. The path will then be interpreted relative to
2227 `org-directory'
2228 2. When a capture note is filed away in an interactive way (when exiting the
2229 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2230 with `org-directory' as the default path."
2231 :group 'org-refile
2232 :group 'org-capture
2233 :type 'directory)
2235 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2236 "Default target for storing notes.
2237 Used as a fall back file for org-capture.el, for templates that
2238 do not specify a target file."
2239 :group 'org-refile
2240 :group 'org-capture
2241 :type '(choice
2242 (const :tag "Default from remember-data-file" nil)
2243 file))
2245 (defcustom org-goto-interface 'outline
2246 "The default interface to be used for `org-goto'.
2247 Allowed values are:
2248 outline The interface shows an outline of the relevant file
2249 and the correct heading is found by moving through
2250 the outline or by searching with incremental search.
2251 outline-path-completion Headlines in the current buffer are offered via
2252 completion. This is the interface also used by
2253 the refile command."
2254 :group 'org-refile
2255 :type '(choice
2256 (const :tag "Outline" outline)
2257 (const :tag "Outline-path-completion" outline-path-completion)))
2259 (defcustom org-goto-max-level 5
2260 "Maximum target level when running `org-goto' with refile interface."
2261 :group 'org-refile
2262 :type 'integer)
2264 (defcustom org-reverse-note-order nil
2265 "Non-nil means store new notes at the beginning of a file or entry.
2266 When nil, new notes will be filed to the end of a file or entry.
2267 This can also be a list with cons cells of regular expressions that
2268 are matched against file names, and values."
2269 :group 'org-capture
2270 :group 'org-refile
2271 :type '(choice
2272 (const :tag "Reverse always" t)
2273 (const :tag "Reverse never" nil)
2274 (repeat :tag "By file name regexp"
2275 (cons regexp boolean))))
2277 (defcustom org-log-refile nil
2278 "Information to record when a task is refiled.
2280 Possible values are:
2282 nil Don't add anything
2283 time Add a time stamp to the task
2284 note Prompt for a note and add it with template `org-log-note-headings'
2286 This option can also be set with on a per-file-basis with
2288 #+STARTUP: nologrefile
2289 #+STARTUP: logrefile
2290 #+STARTUP: lognoterefile
2292 You can have local logging settings for a subtree by setting the LOGGING
2293 property to one or more of these keywords.
2295 When bulk-refiling from the agenda, the value `note' is forbidden and
2296 will temporarily be changed to `time'."
2297 :group 'org-refile
2298 :group 'org-progress
2299 :version "24.1"
2300 :type '(choice
2301 (const :tag "No logging" nil)
2302 (const :tag "Record timestamp" time)
2303 (const :tag "Record timestamp with note." note)))
2305 (defcustom org-refile-targets nil
2306 "Targets for refiling entries with \\[org-refile].
2307 This is a list of cons cells. Each cell contains:
2308 - a specification of the files to be considered, either a list of files,
2309 or a symbol whose function or variable value will be used to retrieve
2310 a file name or a list of file names. If you use `org-agenda-files' for
2311 that, all agenda files will be scanned for targets. Nil means consider
2312 headings in the current buffer.
2313 - A specification of how to find candidate refile targets. This may be
2314 any of:
2315 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2316 This tag has to be present in all target headlines, inheritance will
2317 not be considered.
2318 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2319 todo keyword.
2320 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2321 headlines that are refiling targets.
2322 - a cons cell (:level . N). Any headline of level N is considered a target.
2323 Note that, when `org-odd-levels-only' is set, level corresponds to
2324 order in hierarchy, not to the number of stars.
2325 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2326 Note that, when `org-odd-levels-only' is set, level corresponds to
2327 order in hierarchy, not to the number of stars.
2329 Each element of this list generates a set of possible targets.
2330 The union of these sets is presented (with completion) to
2331 the user by `org-refile'.
2333 You can set the variable `org-refile-target-verify-function' to a function
2334 to verify each headline found by the simple criteria above.
2336 When this variable is nil, all top-level headlines in the current buffer
2337 are used, equivalent to the value `((nil . (:level . 1))'."
2338 :group 'org-refile
2339 :type '(repeat
2340 (cons
2341 (choice :value org-agenda-files
2342 (const :tag "All agenda files" org-agenda-files)
2343 (const :tag "Current buffer" nil)
2344 (function) (variable) (file))
2345 (choice :tag "Identify target headline by"
2346 (cons :tag "Specific tag" (const :value :tag) (string))
2347 (cons :tag "TODO keyword" (const :value :todo) (string))
2348 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2349 (cons :tag "Level number" (const :value :level) (integer))
2350 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2352 (defcustom org-refile-target-verify-function nil
2353 "Function to verify if the headline at point should be a refile target.
2354 The function will be called without arguments, with point at the
2355 beginning of the headline. It should return t and leave point
2356 where it is if the headline is a valid target for refiling.
2358 If the target should not be selected, the function must return nil.
2359 In addition to this, it may move point to a place from where the search
2360 should be continued. For example, the function may decide that the entire
2361 subtree of the current entry should be excluded and move point to the end
2362 of the subtree."
2363 :group 'org-refile
2364 :type '(choice
2365 (const nil)
2366 (function)))
2368 (defcustom org-refile-use-cache nil
2369 "Non-nil means cache refile targets to speed up the process.
2370 The cache for a particular file will be updated automatically when
2371 the buffer has been killed, or when any of the marker used for flagging
2372 refile targets no longer points at a live buffer.
2373 If you have added new entries to a buffer that might themselves be targets,
2374 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2375 find that easier, `C-u C-u C-u C-c C-w'."
2376 :group 'org-refile
2377 :version "24.1"
2378 :type 'boolean)
2380 (defcustom org-refile-use-outline-path nil
2381 "Non-nil means provide refile targets as paths.
2382 So a level 3 headline will be available as level1/level2/level3.
2384 When the value is `file', also include the file name (without directory)
2385 into the path. In this case, you can also stop the completion after
2386 the file name, to get entries inserted as top level in the file.
2388 When `full-file-path', include the full file path."
2389 :group 'org-refile
2390 :type '(choice
2391 (const :tag "Not" nil)
2392 (const :tag "Yes" t)
2393 (const :tag "Start with file name" file)
2394 (const :tag "Start with full file path" full-file-path)))
2396 (defcustom org-outline-path-complete-in-steps t
2397 "Non-nil means complete the outline path in hierarchical steps.
2398 When Org-mode uses the refile interface to select an outline path
2399 \(see variable `org-refile-use-outline-path'), the completion of
2400 the path can be done is a single go, or if can be done in steps down
2401 the headline hierarchy. Going in steps is probably the best if you
2402 do not use a special completion package like `ido' or `icicles'.
2403 However, when using these packages, going in one step can be very
2404 fast, while still showing the whole path to the entry."
2405 :group 'org-refile
2406 :type 'boolean)
2408 (defcustom org-refile-allow-creating-parent-nodes nil
2409 "Non-nil means allow to create new nodes as refile targets.
2410 New nodes are then created by adding \"/new node name\" to the completion
2411 of an existing node. When the value of this variable is `confirm',
2412 new node creation must be confirmed by the user (recommended).
2413 When nil, the completion must match an existing entry.
2415 Note that, if the new heading is not seen by the criteria
2416 listed in `org-refile-targets', multiple instances of the same
2417 heading would be created by trying again to file under the new
2418 heading."
2419 :group 'org-refile
2420 :type '(choice
2421 (const :tag "Never" nil)
2422 (const :tag "Always" t)
2423 (const :tag "Prompt for confirmation" confirm)))
2425 (defcustom org-refile-active-region-within-subtree nil
2426 "Non-nil means also refile active region within a subtree.
2428 By default `org-refile' doesn't allow refiling regions if they
2429 don't contain a set of subtrees, but it might be convenient to
2430 do so sometimes: in that case, the first line of the region is
2431 converted to a headline before refiling."
2432 :group 'org-refile
2433 :version "24.1"
2434 :type 'boolean)
2436 (defgroup org-todo nil
2437 "Options concerning TODO items in Org-mode."
2438 :tag "Org TODO"
2439 :group 'org)
2441 (defgroup org-progress nil
2442 "Options concerning Progress logging in Org-mode."
2443 :tag "Org Progress"
2444 :group 'org-time)
2446 (defvar org-todo-interpretation-widgets
2447 '((:tag "Sequence (cycling hits every state)" sequence)
2448 (:tag "Type (cycling directly to DONE)" type))
2449 "The available interpretation symbols for customizing `org-todo-keywords'.
2450 Interested libraries should add to this list.")
2452 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2453 "List of TODO entry keyword sequences and their interpretation.
2454 \\<org-mode-map>This is a list of sequences.
2456 Each sequence starts with a symbol, either `sequence' or `type',
2457 indicating if the keywords should be interpreted as a sequence of
2458 action steps, or as different types of TODO items. The first
2459 keywords are states requiring action - these states will select a headline
2460 for inclusion into the global TODO list Org-mode produces. If one of
2461 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2462 signify that no further action is necessary. If \"|\" is not found,
2463 the last keyword is treated as the only DONE state of the sequence.
2465 The command \\[org-todo] cycles an entry through these states, and one
2466 additional state where no keyword is present. For details about this
2467 cycling, see the manual.
2469 TODO keywords and interpretation can also be set on a per-file basis with
2470 the special #+SEQ_TODO and #+TYP_TODO lines.
2472 Each keyword can optionally specify a character for fast state selection
2473 \(in combination with the variable `org-use-fast-todo-selection')
2474 and specifiers for state change logging, using the same syntax that
2475 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2476 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2477 indicates to record a time stamp each time this state is selected.
2479 Each keyword may also specify if a timestamp or a note should be
2480 recorded when entering or leaving the state, by adding additional
2481 characters in the parenthesis after the keyword. This looks like this:
2482 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2483 record only the time of the state change. With X and Y being either
2484 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2485 Y when leaving the state if and only if the *target* state does not
2486 define X. You may omit any of the fast-selection key or X or /Y,
2487 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2489 For backward compatibility, this variable may also be just a list
2490 of keywords. In this case the interpretation (sequence or type) will be
2491 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2492 :group 'org-todo
2493 :group 'org-keywords
2494 :type '(choice
2495 (repeat :tag "Old syntax, just keywords"
2496 (string :tag "Keyword"))
2497 (repeat :tag "New syntax"
2498 (cons
2499 (choice
2500 :tag "Interpretation"
2501 ;;Quick and dirty way to see
2502 ;;`org-todo-interpretations'. This takes the
2503 ;;place of item arguments
2504 :convert-widget
2505 (lambda (widget)
2506 (widget-put widget
2507 :args (mapcar
2508 (lambda (x)
2509 (widget-convert
2510 (cons 'const x)))
2511 org-todo-interpretation-widgets))
2512 widget))
2513 (repeat
2514 (string :tag "Keyword"))))))
2516 (defvar org-todo-keywords-1 nil
2517 "All TODO and DONE keywords active in a buffer.")
2518 (make-variable-buffer-local 'org-todo-keywords-1)
2519 (defvar org-todo-keywords-for-agenda nil)
2520 (defvar org-done-keywords-for-agenda nil)
2521 (defvar org-todo-keyword-alist-for-agenda nil)
2522 (defvar org-tag-alist-for-agenda nil
2523 "Alist of all tags from all agenda files.")
2524 (defvar org-tag-groups-alist-for-agenda nil
2525 "Alist of all groups tags from all current agenda files.")
2526 (defvar org-tag-groups-alist nil)
2527 (make-variable-buffer-local 'org-tag-groups-alist)
2528 (defvar org-agenda-contributing-files nil)
2529 (defvar org-not-done-keywords nil)
2530 (make-variable-buffer-local 'org-not-done-keywords)
2531 (defvar org-done-keywords nil)
2532 (make-variable-buffer-local 'org-done-keywords)
2533 (defvar org-todo-heads nil)
2534 (make-variable-buffer-local 'org-todo-heads)
2535 (defvar org-todo-sets nil)
2536 (make-variable-buffer-local 'org-todo-sets)
2537 (defvar org-todo-log-states nil)
2538 (make-variable-buffer-local 'org-todo-log-states)
2539 (defvar org-todo-kwd-alist nil)
2540 (make-variable-buffer-local 'org-todo-kwd-alist)
2541 (defvar org-todo-key-alist nil)
2542 (make-variable-buffer-local 'org-todo-key-alist)
2543 (defvar org-todo-key-trigger nil)
2544 (make-variable-buffer-local 'org-todo-key-trigger)
2546 (defcustom org-todo-interpretation 'sequence
2547 "Controls how TODO keywords are interpreted.
2548 This variable is in principle obsolete and is only used for
2549 backward compatibility, if the interpretation of todo keywords is
2550 not given already in `org-todo-keywords'. See that variable for
2551 more information."
2552 :group 'org-todo
2553 :group 'org-keywords
2554 :type '(choice (const sequence)
2555 (const type)))
2557 (defcustom org-use-fast-todo-selection t
2558 "Non-nil means use the fast todo selection scheme with C-c C-t.
2559 This variable describes if and under what circumstances the cycling
2560 mechanism for TODO keywords will be replaced by a single-key, direct
2561 selection scheme.
2563 When nil, fast selection is never used.
2565 When the symbol `prefix', it will be used when `org-todo' is called
2566 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2567 `C-u t' in an agenda buffer.
2569 When t, fast selection is used by default. In this case, the prefix
2570 argument forces cycling instead.
2572 In all cases, the special interface is only used if access keys have
2573 actually been assigned by the user, i.e. if keywords in the configuration
2574 are followed by a letter in parenthesis, like TODO(t)."
2575 :group 'org-todo
2576 :type '(choice
2577 (const :tag "Never" nil)
2578 (const :tag "By default" t)
2579 (const :tag "Only with C-u C-c C-t" prefix)))
2581 (defcustom org-provide-todo-statistics t
2582 "Non-nil means update todo statistics after insert and toggle.
2583 ALL-HEADLINES means update todo statistics by including headlines
2584 with no TODO keyword as well, counting them as not done.
2585 A list of TODO keywords means the same, but skip keywords that are
2586 not in this list.
2587 When set to a list of two lists, the first list contains keywords
2588 to consider as TODO keywords, the second list contains keywords
2589 to consider as DONE keywords.
2591 When this is set, todo statistics is updated in the parent of the
2592 current entry each time a todo state is changed."
2593 :group 'org-todo
2594 :type '(choice
2595 (const :tag "Yes, only for TODO entries" t)
2596 (const :tag "Yes, including all entries" all-headlines)
2597 (repeat :tag "Yes, for TODOs in this list"
2598 (string :tag "TODO keyword"))
2599 (list :tag "Yes, for TODOs and DONEs in these lists"
2600 (repeat (string :tag "TODO keyword"))
2601 (repeat (string :tag "DONE keyword")))
2602 (other :tag "No TODO statistics" nil)))
2604 (defcustom org-hierarchical-todo-statistics t
2605 "Non-nil means TODO statistics covers just direct children.
2606 When nil, all entries in the subtree are considered.
2607 This has only an effect if `org-provide-todo-statistics' is set.
2608 To set this to nil for only a single subtree, use a COOKIE_DATA
2609 property and include the word \"recursive\" into the value."
2610 :group 'org-todo
2611 :type 'boolean)
2613 (defcustom org-after-todo-state-change-hook nil
2614 "Hook which is run after the state of a TODO item was changed.
2615 The new state (a string with a TODO keyword, or nil) is available in the
2616 Lisp variable `org-state'."
2617 :group 'org-todo
2618 :type 'hook)
2620 (defvar org-blocker-hook nil
2621 "Hook for functions that are allowed to block a state change.
2623 Functions in this hook should not modify the buffer.
2624 Each function gets as its single argument a property list,
2625 see `org-trigger-hook' for more information about this list.
2627 If any of the functions in this hook returns nil, the state change
2628 is blocked.")
2630 (defvar org-trigger-hook nil
2631 "Hook for functions that are triggered by a state change.
2633 Each function gets as its single argument a property list with at
2634 least the following elements:
2636 (:type type-of-change :position pos-at-entry-start
2637 :from old-state :to new-state)
2639 Depending on the type, more properties may be present.
2641 This mechanism is currently implemented for:
2643 TODO state changes
2644 ------------------
2645 :type todo-state-change
2646 :from previous state (keyword as a string), or nil, or a symbol
2647 'todo' or 'done', to indicate the general type of state.
2648 :to new state, like in :from")
2650 (defcustom org-enforce-todo-dependencies nil
2651 "Non-nil means undone TODO entries will block switching the parent to DONE.
2652 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2653 be blocked if any prior sibling is not yet done.
2654 Finally, if the parent is blocked because of ordered siblings of its own,
2655 the child will also be blocked."
2656 :set (lambda (var val)
2657 (set var val)
2658 (if val
2659 (add-hook 'org-blocker-hook
2660 'org-block-todo-from-children-or-siblings-or-parent)
2661 (remove-hook 'org-blocker-hook
2662 'org-block-todo-from-children-or-siblings-or-parent)))
2663 :group 'org-todo
2664 :type 'boolean)
2666 (defcustom org-enforce-todo-checkbox-dependencies nil
2667 "Non-nil means unchecked boxes will block switching the parent to DONE.
2668 When this is nil, checkboxes have no influence on switching TODO states.
2669 When non-nil, you first need to check off all check boxes before the TODO
2670 entry can be switched to DONE.
2671 This variable needs to be set before org.el is loaded, and you need to
2672 restart Emacs after a change to make the change effective. The only way
2673 to change is while Emacs is running is through the customize interface."
2674 :set (lambda (var val)
2675 (set var val)
2676 (if val
2677 (add-hook 'org-blocker-hook
2678 'org-block-todo-from-checkboxes)
2679 (remove-hook 'org-blocker-hook
2680 'org-block-todo-from-checkboxes)))
2681 :group 'org-todo
2682 :type 'boolean)
2684 (defcustom org-treat-insert-todo-heading-as-state-change nil
2685 "Non-nil means inserting a TODO heading is treated as state change.
2686 So when the command \\[org-insert-todo-heading] is used, state change
2687 logging will apply if appropriate. When nil, the new TODO item will
2688 be inserted directly, and no logging will take place."
2689 :group 'org-todo
2690 :type 'boolean)
2692 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2693 "Non-nil means switching TODO states with S-cursor counts as state change.
2694 This is the default behavior. However, setting this to nil allows a
2695 convenient way to select a TODO state and bypass any logging associated
2696 with that."
2697 :group 'org-todo
2698 :type 'boolean)
2700 (defcustom org-todo-state-tags-triggers nil
2701 "Tag changes that should be triggered by TODO state changes.
2702 This is a list. Each entry is
2704 (state-change (tag . flag) .......)
2706 State-change can be a string with a state, and empty string to indicate the
2707 state that has no TODO keyword, or it can be one of the symbols `todo'
2708 or `done', meaning any not-done or done state, respectively."
2709 :group 'org-todo
2710 :group 'org-tags
2711 :type '(repeat
2712 (cons (choice :tag "When changing to"
2713 (const :tag "Not-done state" todo)
2714 (const :tag "Done state" done)
2715 (string :tag "State"))
2716 (repeat
2717 (cons :tag "Tag action"
2718 (string :tag "Tag")
2719 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2721 (defcustom org-log-done nil
2722 "Information to record when a task moves to the DONE state.
2724 Possible values are:
2726 nil Don't add anything, just change the keyword
2727 time Add a time stamp to the task
2728 note Prompt for a note and add it with template `org-log-note-headings'
2730 This option can also be set with on a per-file-basis with
2732 #+STARTUP: nologdone
2733 #+STARTUP: logdone
2734 #+STARTUP: lognotedone
2736 You can have local logging settings for a subtree by setting the LOGGING
2737 property to one or more of these keywords."
2738 :group 'org-todo
2739 :group 'org-progress
2740 :type '(choice
2741 (const :tag "No logging" nil)
2742 (const :tag "Record CLOSED timestamp" time)
2743 (const :tag "Record CLOSED timestamp with note." note)))
2745 ;; Normalize old uses of org-log-done.
2746 (cond
2747 ((eq org-log-done t) (setq org-log-done 'time))
2748 ((and (listp org-log-done) (memq 'done org-log-done))
2749 (setq org-log-done 'note)))
2751 (defcustom org-log-reschedule nil
2752 "Information to record when the scheduling date of a tasks is modified.
2754 Possible values are:
2756 nil Don't add anything, just change the date
2757 time Add a time stamp to the task
2758 note Prompt for a note and add it with template `org-log-note-headings'
2760 This option can also be set with on a per-file-basis with
2762 #+STARTUP: nologreschedule
2763 #+STARTUP: logreschedule
2764 #+STARTUP: lognotereschedule"
2765 :group 'org-todo
2766 :group 'org-progress
2767 :type '(choice
2768 (const :tag "No logging" nil)
2769 (const :tag "Record timestamp" time)
2770 (const :tag "Record timestamp with note." note)))
2772 (defcustom org-log-redeadline nil
2773 "Information to record when the deadline date of a tasks is modified.
2775 Possible values are:
2777 nil Don't add anything, just change the date
2778 time Add a time stamp to the task
2779 note Prompt for a note and add it with template `org-log-note-headings'
2781 This option can also be set with on a per-file-basis with
2783 #+STARTUP: nologredeadline
2784 #+STARTUP: logredeadline
2785 #+STARTUP: lognoteredeadline
2787 You can have local logging settings for a subtree by setting the LOGGING
2788 property to one or more of these keywords."
2789 :group 'org-todo
2790 :group 'org-progress
2791 :type '(choice
2792 (const :tag "No logging" nil)
2793 (const :tag "Record timestamp" time)
2794 (const :tag "Record timestamp with note." note)))
2796 (defcustom org-log-note-clock-out nil
2797 "Non-nil means record a note when clocking out of an item.
2798 This can also be configured on a per-file basis by adding one of
2799 the following lines anywhere in the buffer:
2801 #+STARTUP: lognoteclock-out
2802 #+STARTUP: nolognoteclock-out"
2803 :group 'org-todo
2804 :group 'org-progress
2805 :type 'boolean)
2807 (defcustom org-log-done-with-time t
2808 "Non-nil means the CLOSED time stamp will contain date and time.
2809 When nil, only the date will be recorded."
2810 :group 'org-progress
2811 :type 'boolean)
2813 (defcustom org-log-note-headings
2814 '((done . "CLOSING NOTE %t")
2815 (state . "State %-12s from %-12S %t")
2816 (note . "Note taken on %t")
2817 (reschedule . "Rescheduled from %S on %t")
2818 (delschedule . "Not scheduled, was %S on %t")
2819 (redeadline . "New deadline from %S on %t")
2820 (deldeadline . "Removed deadline, was %S on %t")
2821 (refile . "Refiled on %t")
2822 (clock-out . ""))
2823 "Headings for notes added to entries.
2824 The value is an alist, with the car being a symbol indicating the note
2825 context, and the cdr is the heading to be used. The heading may also be the
2826 empty string.
2827 %t in the heading will be replaced by a time stamp.
2828 %T will be an active time stamp instead the default inactive one
2829 %d will be replaced by a short-format time stamp.
2830 %D will be replaced by an active short-format time stamp.
2831 %s will be replaced by the new TODO state, in double quotes.
2832 %S will be replaced by the old TODO state, in double quotes.
2833 %u will be replaced by the user name.
2834 %U will be replaced by the full user name.
2836 In fact, it is not a good idea to change the `state' entry, because
2837 agenda log mode depends on the format of these entries."
2838 :group 'org-todo
2839 :group 'org-progress
2840 :type '(list :greedy t
2841 (cons (const :tag "Heading when closing an item" done) string)
2842 (cons (const :tag
2843 "Heading when changing todo state (todo sequence only)"
2844 state) string)
2845 (cons (const :tag "Heading when just taking a note" note) string)
2846 (cons (const :tag "Heading when rescheduling" reschedule) string)
2847 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2848 (cons (const :tag "Heading when changing deadline" redeadline) string)
2849 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2850 (cons (const :tag "Heading when refiling" refile) string)
2851 (cons (const :tag "Heading when clocking out" clock-out) string)))
2853 (unless (assq 'note org-log-note-headings)
2854 (push '(note . "%t") org-log-note-headings))
2856 (defcustom org-log-into-drawer nil
2857 "Non-nil means insert state change notes and time stamps into a drawer.
2858 When nil, state changes notes will be inserted after the headline and
2859 any scheduling and clock lines, but not inside a drawer.
2861 The value of this variable should be the name of the drawer to use.
2862 LOGBOOK is proposed as the default drawer for this purpose, you can
2863 also set this to a string to define the drawer of your choice.
2865 A value of t is also allowed, representing \"LOGBOOK\".
2867 A value of t or nil can also be set with on a per-file-basis with
2869 #+STARTUP: logdrawer
2870 #+STARTUP: nologdrawer
2872 If this variable is set, `org-log-state-notes-insert-after-drawers'
2873 will be ignored.
2875 You can set the property LOG_INTO_DRAWER to overrule this setting for
2876 a subtree."
2877 :group 'org-todo
2878 :group 'org-progress
2879 :type '(choice
2880 (const :tag "Not into a drawer" nil)
2881 (const :tag "LOGBOOK" t)
2882 (string :tag "Other")))
2884 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2886 (defun org-log-into-drawer ()
2887 "Return the value of `org-log-into-drawer', but let properties overrule.
2888 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2889 used instead of the default value."
2890 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2891 (cond
2892 ((not p) org-log-into-drawer)
2893 ((equal p "nil") nil)
2894 ((equal p "t") "LOGBOOK")
2895 (t p))))
2897 (defcustom org-log-state-notes-insert-after-drawers nil
2898 "Non-nil means insert state change notes after any drawers in entry.
2899 Only the drawers that *immediately* follow the headline and the
2900 deadline/scheduled line are skipped.
2901 When nil, insert notes right after the heading and perhaps the line
2902 with deadline/scheduling if present.
2904 This variable will have no effect if `org-log-into-drawer' is
2905 set."
2906 :group 'org-todo
2907 :group 'org-progress
2908 :type 'boolean)
2910 (defcustom org-log-states-order-reversed t
2911 "Non-nil means the latest state note will be directly after heading.
2912 When nil, the state change notes will be ordered according to time.
2914 This option can also be set with on a per-file-basis with
2916 #+STARTUP: logstatesreversed
2917 #+STARTUP: nologstatesreversed"
2918 :group 'org-todo
2919 :group 'org-progress
2920 :type 'boolean)
2922 (defcustom org-todo-repeat-to-state nil
2923 "The TODO state to which a repeater should return the repeating task.
2924 By default this is the first task in a TODO sequence, or the previous state
2925 in a TODO_TYP set. But you can specify another task here.
2926 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2927 :group 'org-todo
2928 :version "24.1"
2929 :type '(choice (const :tag "Head of sequence" nil)
2930 (string :tag "Specific state")))
2932 (defcustom org-log-repeat 'time
2933 "Non-nil means record moving through the DONE state when triggering repeat.
2934 An auto-repeating task is immediately switched back to TODO when
2935 marked DONE. If you are not logging state changes (by adding \"@\"
2936 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2937 record a closing note, there will be no record of the task moving
2938 through DONE. This variable forces taking a note anyway.
2940 nil Don't force a record
2941 time Record a time stamp
2942 note Prompt for a note and add it with template `org-log-note-headings'
2944 This option can also be set with on a per-file-basis with
2946 #+STARTUP: nologrepeat
2947 #+STARTUP: logrepeat
2948 #+STARTUP: lognoterepeat
2950 You can have local logging settings for a subtree by setting the LOGGING
2951 property to one or more of these keywords."
2952 :group 'org-todo
2953 :group 'org-progress
2954 :type '(choice
2955 (const :tag "Don't force a record" nil)
2956 (const :tag "Force recording the DONE state" time)
2957 (const :tag "Force recording a note with the DONE state" note)))
2960 (defgroup org-priorities nil
2961 "Priorities in Org-mode."
2962 :tag "Org Priorities"
2963 :group 'org-todo)
2965 (defcustom org-enable-priority-commands t
2966 "Non-nil means priority commands are active.
2967 When nil, these commands will be disabled, so that you never accidentally
2968 set a priority."
2969 :group 'org-priorities
2970 :type 'boolean)
2972 (defcustom org-highest-priority ?A
2973 "The highest priority of TODO items. A character like ?A, ?B etc.
2974 Must have a smaller ASCII number than `org-lowest-priority'."
2975 :group 'org-priorities
2976 :type 'character)
2978 (defcustom org-lowest-priority ?C
2979 "The lowest priority of TODO items. A character like ?A, ?B etc.
2980 Must have a larger ASCII number than `org-highest-priority'."
2981 :group 'org-priorities
2982 :type 'character)
2984 (defcustom org-default-priority ?B
2985 "The default priority of TODO items.
2986 This is the priority an item gets if no explicit priority is given.
2987 When starting to cycle on an empty priority the first step in the cycle
2988 depends on `org-priority-start-cycle-with-default'. The resulting first
2989 step priority must not exceed the range from `org-highest-priority' to
2990 `org-lowest-priority' which means that `org-default-priority' has to be
2991 in this range exclusive or inclusive the range boundaries. Else the
2992 first step refuses to set the default and the second will fall back
2993 to (depending on the command used) the highest or lowest priority."
2994 :group 'org-priorities
2995 :type 'character)
2997 (defcustom org-priority-start-cycle-with-default t
2998 "Non-nil means start with default priority when starting to cycle.
2999 When this is nil, the first step in the cycle will be (depending on the
3000 command used) one higher or lower than the default priority.
3001 See also `org-default-priority'."
3002 :group 'org-priorities
3003 :type 'boolean)
3005 (defcustom org-get-priority-function nil
3006 "Function to extract the priority from a string.
3007 The string is normally the headline. If this is nil Org computes the
3008 priority from the priority cookie like [#A] in the headline. It returns
3009 an integer, increasing by 1000 for each priority level.
3010 The user can set a different function here, which should take a string
3011 as an argument and return the numeric priority."
3012 :group 'org-priorities
3013 :version "24.1"
3014 :type '(choice
3015 (const nil)
3016 (function)))
3018 (defgroup org-time nil
3019 "Options concerning time stamps and deadlines in Org-mode."
3020 :tag "Org Time"
3021 :group 'org)
3023 (defcustom org-insert-labeled-timestamps-at-point nil
3024 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3025 When nil, these labeled time stamps are forces into the second line of an
3026 entry, just after the headline. When scheduling from the global TODO list,
3027 the time stamp will always be forced into the second line."
3028 :group 'org-time
3029 :type 'boolean)
3031 (defcustom org-time-stamp-rounding-minutes '(0 5)
3032 "Number of minutes to round time stamps to.
3033 These are two values, the first applies when first creating a time stamp.
3034 The second applies when changing it with the commands `S-up' and `S-down'.
3035 When changing the time stamp, this means that it will change in steps
3036 of N minutes, as given by the second value.
3038 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3039 numbers should be factors of 60, so for example 5, 10, 15.
3041 When this is larger than 1, you can still force an exact time stamp by using
3042 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3043 and by using a prefix arg to `S-up/down' to specify the exact number
3044 of minutes to shift."
3045 :group 'org-time
3046 :get (lambda (var) ; Make sure both elements are there
3047 (if (integerp (default-value var))
3048 (list (default-value var) 5)
3049 (default-value var)))
3050 :type '(list
3051 (integer :tag "when inserting times")
3052 (integer :tag "when modifying times")))
3054 ;; Normalize old customizations of this variable.
3055 (when (integerp org-time-stamp-rounding-minutes)
3056 (setq org-time-stamp-rounding-minutes
3057 (list org-time-stamp-rounding-minutes
3058 org-time-stamp-rounding-minutes)))
3060 (defcustom org-display-custom-times nil
3061 "Non-nil means overlay custom formats over all time stamps.
3062 The formats are defined through the variable `org-time-stamp-custom-formats'.
3063 To turn this on on a per-file basis, insert anywhere in the file:
3064 #+STARTUP: customtime"
3065 :group 'org-time
3066 :set 'set-default
3067 :type 'sexp)
3068 (make-variable-buffer-local 'org-display-custom-times)
3070 (defcustom org-time-stamp-custom-formats
3071 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3072 "Custom formats for time stamps. See `format-time-string' for the syntax.
3073 These are overlaid over the default ISO format if the variable
3074 `org-display-custom-times' is set. Time like %H:%M should be at the
3075 end of the second format. The custom formats are also honored by export
3076 commands, if custom time display is turned on at the time of export."
3077 :group 'org-time
3078 :type 'sexp)
3080 (defun org-time-stamp-format (&optional long inactive)
3081 "Get the right format for a time string."
3082 (let ((f (if long (cdr org-time-stamp-formats)
3083 (car org-time-stamp-formats))))
3084 (if inactive
3085 (concat "[" (substring f 1 -1) "]")
3086 f)))
3088 (defcustom org-time-clocksum-format
3089 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3090 "The format string used when creating CLOCKSUM lines.
3091 This is also used when Org mode generates a time duration.
3093 The value can be a single format string containing two
3094 %-sequences, which will be filled with the number of hours and
3095 minutes in that order.
3097 Alternatively, the value can be a plist associating any of the
3098 keys :years, :months, :weeks, :days, :hours or :minutes with
3099 format strings. The time duration is formatted using only the
3100 time components that are needed and concatenating the results.
3101 If a time unit in absent, it falls back to the next smallest
3102 unit.
3104 The keys :require-years, :require-months, :require-days,
3105 :require-weeks, :require-hours, :require-minutes are also
3106 meaningful. A non-nil value for these keys indicates that the
3107 corresponding time component should always be included, even if
3108 its value is 0.
3111 For example,
3113 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3114 :require-minutes t)
3116 means durations longer than a day will be expressed in days,
3117 hours and minutes, and durations less than a day will always be
3118 expressed in hours and minutes (even for durations less than an
3119 hour).
3121 The value
3123 \(:days \"%dd\" :minutes \"%dm\")
3125 means durations longer than a day will be expressed in days and
3126 minutes, and durations less than a day will be expressed entirely
3127 in minutes (even for durations longer than an hour)."
3128 :group 'org-time
3129 :group 'org-clock
3130 :version "24.4"
3131 :package-version '(Org . "8.0")
3132 :type '(choice (string :tag "Format string")
3133 (set :tag "Plist"
3134 (group :inline t (const :tag "Years" :years)
3135 (string :tag "Format string"))
3136 (group :inline t
3137 (const :tag "Always show years" :require-years)
3138 (const t))
3139 (group :inline t (const :tag "Months" :months)
3140 (string :tag "Format string"))
3141 (group :inline t
3142 (const :tag "Always show months" :require-months)
3143 (const t))
3144 (group :inline t (const :tag "Weeks" :weeks)
3145 (string :tag "Format string"))
3146 (group :inline t
3147 (const :tag "Always show weeks" :require-weeks)
3148 (const t))
3149 (group :inline t (const :tag "Days" :days)
3150 (string :tag "Format string"))
3151 (group :inline t
3152 (const :tag "Always show days" :require-days)
3153 (const t))
3154 (group :inline t (const :tag "Hours" :hours)
3155 (string :tag "Format string"))
3156 (group :inline t
3157 (const :tag "Always show hours" :require-hours)
3158 (const t))
3159 (group :inline t (const :tag "Minutes" :minutes)
3160 (string :tag "Format string"))
3161 (group :inline t
3162 (const :tag "Always show minutes" :require-minutes)
3163 (const t)))))
3165 (defcustom org-time-clocksum-use-fractional nil
3166 "When non-nil, \\[org-clock-display] uses fractional times.
3167 See `org-time-clocksum-format' for more on time clock formats."
3168 :group 'org-time
3169 :group 'org-clock
3170 :version "24.3"
3171 :type 'boolean)
3173 (defcustom org-time-clocksum-use-effort-durations nil
3174 "When non-nil, \\[org-clock-display] uses effort durations.
3175 E.g. by default, one day is considered to be a 8 hours effort,
3176 so a task that has been clocked for 16 hours will be displayed
3177 as during 2 days in the clock display or in the clocktable.
3179 See `org-effort-durations' on how to set effort durations
3180 and `org-time-clocksum-format' for more on time clock formats."
3181 :group 'org-time
3182 :group 'org-clock
3183 :version "24.4"
3184 :package-version '(Org . "8.0")
3185 :type 'boolean)
3187 (defcustom org-time-clocksum-fractional-format "%.2f"
3188 "The format string used when creating CLOCKSUM lines,
3189 or when Org mode generates a time duration, if
3190 `org-time-clocksum-use-fractional' is enabled.
3192 The value can be a single format string containing one
3193 %-sequence, which will be filled with the number of hours as
3194 a float.
3196 Alternatively, the value can be a plist associating any of the
3197 keys :years, :months, :weeks, :days, :hours or :minutes with
3198 a format string. The time duration is formatted using the
3199 largest time unit which gives a non-zero integer part. If all
3200 specified formats have zero integer part, the smallest time unit
3201 is used."
3202 :group 'org-time
3203 :type '(choice (string :tag "Format string")
3204 (set (group :inline t (const :tag "Years" :years)
3205 (string :tag "Format string"))
3206 (group :inline t (const :tag "Months" :months)
3207 (string :tag "Format string"))
3208 (group :inline t (const :tag "Weeks" :weeks)
3209 (string :tag "Format string"))
3210 (group :inline t (const :tag "Days" :days)
3211 (string :tag "Format string"))
3212 (group :inline t (const :tag "Hours" :hours)
3213 (string :tag "Format string"))
3214 (group :inline t (const :tag "Minutes" :minutes)
3215 (string :tag "Format string")))))
3217 (defcustom org-deadline-warning-days 14
3218 "Number of days before expiration during which a deadline becomes active.
3219 This variable governs the display in sparse trees and in the agenda.
3220 When 0 or negative, it means use this number (the absolute value of it)
3221 even if a deadline has a different individual lead time specified.
3223 Custom commands can set this variable in the options section."
3224 :group 'org-time
3225 :group 'org-agenda-daily/weekly
3226 :type 'integer)
3228 (defcustom org-scheduled-delay-days 0
3229 "Number of days before a scheduled item becomes active.
3230 This variable governs the display in sparse trees and in the agenda.
3231 The default value (i.e. 0) means: don't delay scheduled item.
3232 When negative, it means use this number (the absolute value of it)
3233 even if a scheduled item has a different individual delay time
3234 specified.
3236 Custom commands can set this variable in the options section."
3237 :group 'org-time
3238 :group 'org-agenda-daily/weekly
3239 :version "24.4"
3240 :package-version '(Org . "8.0")
3241 :type 'integer)
3243 (defcustom org-read-date-prefer-future t
3244 "Non-nil means assume future for incomplete date input from user.
3245 This affects the following situations:
3246 1. The user gives a month but not a year.
3247 For example, if it is April and you enter \"feb 2\", this will be read
3248 as Feb 2, *next* year. \"May 5\", however, will be this year.
3249 2. The user gives a day, but no month.
3250 For example, if today is the 15th, and you enter \"3\", Org-mode will
3251 read this as the third of *next* month. However, if you enter \"17\",
3252 it will be considered as *this* month.
3254 If you set this variable to the symbol `time', then also the following
3255 will work:
3257 3. If the user gives a time.
3258 If the time is before now, it will be interpreted as tomorrow.
3260 Currently none of this works for ISO week specifications.
3262 When this option is nil, the current day, month and year will always be
3263 used as defaults.
3265 See also `org-agenda-jump-prefer-future'."
3266 :group 'org-time
3267 :type '(choice
3268 (const :tag "Never" nil)
3269 (const :tag "Check month and day" t)
3270 (const :tag "Check month, day, and time" time)))
3272 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3273 "Should the agenda jump command prefer the future for incomplete dates?
3274 The default is to do the same as configured in `org-read-date-prefer-future'.
3275 But you can also set a deviating value here.
3276 This may t or nil, or the symbol `org-read-date-prefer-future'."
3277 :group 'org-agenda
3278 :group 'org-time
3279 :version "24.1"
3280 :type '(choice
3281 (const :tag "Use org-read-date-prefer-future"
3282 org-read-date-prefer-future)
3283 (const :tag "Never" nil)
3284 (const :tag "Always" t)))
3286 (defcustom org-read-date-force-compatible-dates t
3287 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3289 Depending on the system Emacs is running on, certain dates cannot
3290 be represented with the type used internally to represent time.
3291 Dates between 1970-1-1 and 2038-1-1 can always be represented
3292 correctly. Some systems allow for earlier dates, some for later,
3293 some for both. One way to find out it to insert any date into an
3294 Org buffer, putting the cursor on the year and hitting S-up and
3295 S-down to test the range.
3297 When this variable is set to t, the date/time prompt will not let
3298 you specify dates outside the 1970-2037 range, so it is certain that
3299 these dates will work in whatever version of Emacs you are
3300 running, and also that you can move a file from one Emacs implementation
3301 to another. WHenever Org is forcing the year for you, it will display
3302 a message and beep.
3304 When this variable is nil, Org will check if the date is
3305 representable in the specific Emacs implementation you are using.
3306 If not, it will force a year, usually the current year, and beep
3307 to remind you. Currently this setting is not recommended because
3308 the likelihood that you will open your Org files in an Emacs that
3309 has limited date range is not negligible.
3311 A workaround for this problem is to use diary sexp dates for time
3312 stamps outside of this range."
3313 :group 'org-time
3314 :version "24.1"
3315 :type 'boolean)
3317 (defcustom org-read-date-display-live t
3318 "Non-nil means display current interpretation of date prompt live.
3319 This display will be in an overlay, in the minibuffer."
3320 :group 'org-time
3321 :type 'boolean)
3323 (defcustom org-read-date-popup-calendar t
3324 "Non-nil means pop up a calendar when prompting for a date.
3325 In the calendar, the date can be selected with mouse-1. However, the
3326 minibuffer will also be active, and you can simply enter the date as well.
3327 When nil, only the minibuffer will be available."
3328 :group 'org-time
3329 :type 'boolean)
3330 (org-defvaralias 'org-popup-calendar-for-date-prompt
3331 'org-read-date-popup-calendar)
3333 (make-obsolete-variable
3334 'org-read-date-minibuffer-setup-hook
3335 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3336 (defcustom org-read-date-minibuffer-setup-hook nil
3337 "Hook to be used to set up keys for the date/time interface.
3338 Add key definitions to `minibuffer-local-map', which will be a
3339 temporary copy.
3341 WARNING: This option is obsolete, you should use
3342 `org-read-date-minibuffer-local-map' to set up keys."
3343 :group 'org-time
3344 :type 'hook)
3346 (defcustom org-extend-today-until 0
3347 "The hour when your day really ends. Must be an integer.
3348 This has influence for the following applications:
3349 - When switching the agenda to \"today\". It it is still earlier than
3350 the time given here, the day recognized as TODAY is actually yesterday.
3351 - When a date is read from the user and it is still before the time given
3352 here, the current date and time will be assumed to be yesterday, 23:59.
3353 Also, timestamps inserted in capture templates follow this rule.
3355 IMPORTANT: This is a feature whose implementation is and likely will
3356 remain incomplete. Really, it is only here because past midnight seems to
3357 be the favorite working time of John Wiegley :-)"
3358 :group 'org-time
3359 :type 'integer)
3361 (defcustom org-use-effective-time nil
3362 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3363 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3364 \"effective time\" of any timestamps between midnight and 8am will be
3365 23:59 of the previous day."
3366 :group 'org-time
3367 :version "24.1"
3368 :type 'boolean)
3370 (defcustom org-use-last-clock-out-time-as-effective-time nil
3371 "When non-nil, use the last clock out time for `org-todo'.
3372 Note that this option has precedence over the combined use of
3373 `org-use-effective-time' and `org-extend-today-until'."
3374 :group 'org-time
3375 :version "24.4"
3376 :package-version '(Org . "8.0")
3377 :type 'boolean)
3379 (defcustom org-edit-timestamp-down-means-later nil
3380 "Non-nil means S-down will increase the time in a time stamp.
3381 When nil, S-up will increase."
3382 :group 'org-time
3383 :type 'boolean)
3385 (defcustom org-calendar-follow-timestamp-change t
3386 "Non-nil means make the calendar window follow timestamp changes.
3387 When a timestamp is modified and the calendar window is visible, it will be
3388 moved to the new date."
3389 :group 'org-time
3390 :type 'boolean)
3392 (defgroup org-tags nil
3393 "Options concerning tags in Org-mode."
3394 :tag "Org Tags"
3395 :group 'org)
3397 (defcustom org-tag-alist nil
3398 "List of tags allowed in Org-mode files.
3399 When this list is nil, Org-mode will base TAG input on what is already in the
3400 buffer.
3401 The value of this variable is an alist, the car of each entry must be a
3402 keyword as a string, the cdr may be a character that is used to select
3403 that tag through the fast-tag-selection interface.
3404 See the manual for details."
3405 :group 'org-tags
3406 :type '(repeat
3407 (choice
3408 (cons (string :tag "Tag name")
3409 (character :tag "Access char"))
3410 (list :tag "Start radio group"
3411 (const :startgroup)
3412 (option (string :tag "Group description")))
3413 (list :tag "Group tags delimiter"
3414 (const :grouptags))
3415 (list :tag "End radio group"
3416 (const :endgroup)
3417 (option (string :tag "Group description")))
3418 (const :tag "New line" (:newline)))))
3420 (defcustom org-tag-persistent-alist nil
3421 "List of tags that will always appear in all Org-mode files.
3422 This is in addition to any in buffer settings or customizations
3423 of `org-tag-alist'.
3424 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3425 The value of this variable is an alist, the car of each entry must be a
3426 keyword as a string, the cdr may be a character that is used to select
3427 that tag through the fast-tag-selection interface.
3428 See the manual for details.
3429 To disable these tags on a per-file basis, insert anywhere in the file:
3430 #+STARTUP: noptag"
3431 :group 'org-tags
3432 :type '(repeat
3433 (choice
3434 (cons (string :tag "Tag name")
3435 (character :tag "Access char"))
3436 (const :tag "Start radio group" (:startgroup))
3437 (const :tag "Group tags delimiter" (:grouptags))
3438 (const :tag "End radio group" (:endgroup))
3439 (const :tag "New line" (:newline)))))
3441 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3442 "If non-nil, always offer completion for all tags of all agenda files.
3443 Instead of customizing this variable directly, you might want to
3444 set it locally for capture buffers, because there no list of
3445 tags in that file can be created dynamically (there are none).
3447 (add-hook 'org-capture-mode-hook
3448 (lambda ()
3449 (set (make-local-variable
3450 'org-complete-tags-always-offer-all-agenda-tags)
3451 t)))"
3452 :group 'org-tags
3453 :version "24.1"
3454 :type 'boolean)
3456 (defvar org-file-tags nil
3457 "List of tags that can be inherited by all entries in the file.
3458 The tags will be inherited if the variable `org-use-tag-inheritance'
3459 says they should be.
3460 This variable is populated from #+FILETAGS lines.")
3462 (defcustom org-use-fast-tag-selection 'auto
3463 "Non-nil means use fast tag selection scheme.
3464 This is a special interface to select and deselect tags with single keys.
3465 When nil, fast selection is never used.
3466 When the symbol `auto', fast selection is used if and only if selection
3467 characters for tags have been configured, either through the variable
3468 `org-tag-alist' or through a #+TAGS line in the buffer.
3469 When t, fast selection is always used and selection keys are assigned
3470 automatically if necessary."
3471 :group 'org-tags
3472 :type '(choice
3473 (const :tag "Always" t)
3474 (const :tag "Never" nil)
3475 (const :tag "When selection characters are configured" auto)))
3477 (defcustom org-fast-tag-selection-single-key nil
3478 "Non-nil means fast tag selection exits after first change.
3479 When nil, you have to press RET to exit it.
3480 During fast tag selection, you can toggle this flag with `C-c'.
3481 This variable can also have the value `expert'. In this case, the window
3482 displaying the tags menu is not even shown, until you press C-c again."
3483 :group 'org-tags
3484 :type '(choice
3485 (const :tag "No" nil)
3486 (const :tag "Yes" t)
3487 (const :tag "Expert" expert)))
3489 (defvar org-fast-tag-selection-include-todo nil
3490 "Non-nil means fast tags selection interface will also offer TODO states.
3491 This is an undocumented feature, you should not rely on it.")
3493 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3494 "The column to which tags should be indented in a headline.
3495 If this number is positive, it specifies the column. If it is negative,
3496 it means that the tags should be flushright to that column. For example,
3497 -80 works well for a normal 80 character screen.
3498 When 0, place tags directly after headline text, with only one space in
3499 between."
3500 :group 'org-tags
3501 :type 'integer)
3503 (defcustom org-auto-align-tags t
3504 "Non-nil keeps tags aligned when modifying headlines.
3505 Some operations (i.e. demoting) change the length of a headline and
3506 therefore shift the tags around. With this option turned on, after
3507 each such operation the tags are again aligned to `org-tags-column'."
3508 :group 'org-tags
3509 :type 'boolean)
3511 (defcustom org-use-tag-inheritance t
3512 "Non-nil means tags in levels apply also for sublevels.
3513 When nil, only the tags directly given in a specific line apply there.
3514 This may also be a list of tags that should be inherited, or a regexp that
3515 matches tags that should be inherited. Additional control is possible
3516 with the variable `org-tags-exclude-from-inheritance' which gives an
3517 explicit list of tags to be excluded from inheritance, even if the value of
3518 `org-use-tag-inheritance' would select it for inheritance.
3520 If this option is t, a match early-on in a tree can lead to a large
3521 number of matches in the subtree when constructing the agenda or creating
3522 a sparse tree. If you only want to see the first match in a tree during
3523 a search, check out the variable `org-tags-match-list-sublevels'."
3524 :group 'org-tags
3525 :type '(choice
3526 (const :tag "Not" nil)
3527 (const :tag "Always" t)
3528 (repeat :tag "Specific tags" (string :tag "Tag"))
3529 (regexp :tag "Tags matched by regexp")))
3531 (defcustom org-tags-exclude-from-inheritance nil
3532 "List of tags that should never be inherited.
3533 This is a way to exclude a few tags from inheritance. For way to do
3534 the opposite, to actively allow inheritance for selected tags,
3535 see the variable `org-use-tag-inheritance'."
3536 :group 'org-tags
3537 :type '(repeat (string :tag "Tag")))
3539 (defun org-tag-inherit-p (tag)
3540 "Check if TAG is one that should be inherited."
3541 (cond
3542 ((member tag org-tags-exclude-from-inheritance) nil)
3543 ((eq org-use-tag-inheritance t) t)
3544 ((not org-use-tag-inheritance) nil)
3545 ((stringp org-use-tag-inheritance)
3546 (string-match org-use-tag-inheritance tag))
3547 ((listp org-use-tag-inheritance)
3548 (member tag org-use-tag-inheritance))
3549 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3551 (defcustom org-tags-match-list-sublevels t
3552 "Non-nil means list also sublevels of headlines matching a search.
3553 This variable applies to tags/property searches, and also to stuck
3554 projects because this search is based on a tags match as well.
3556 When set to the symbol `indented', sublevels are indented with
3557 leading dots.
3559 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3560 the sublevels of a headline matching a tag search often also match
3561 the same search. Listing all of them can create very long lists.
3562 Setting this variable to nil causes subtrees of a match to be skipped.
3564 This variable is semi-obsolete and probably should always be true. It
3565 is better to limit inheritance to certain tags using the variables
3566 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3567 :group 'org-tags
3568 :type '(choice
3569 (const :tag "No, don't list them" nil)
3570 (const :tag "Yes, do list them" t)
3571 (const :tag "List them, indented with leading dots" indented)))
3573 (defcustom org-tags-sort-function nil
3574 "When set, tags are sorted using this function as a comparator."
3575 :group 'org-tags
3576 :type '(choice
3577 (const :tag "No sorting" nil)
3578 (const :tag "Alphabetical" string<)
3579 (const :tag "Reverse alphabetical" string>)
3580 (function :tag "Custom function" nil)))
3582 (defvar org-tags-history nil
3583 "History of minibuffer reads for tags.")
3584 (defvar org-last-tags-completion-table nil
3585 "The last used completion table for tags.")
3586 (defvar org-after-tags-change-hook nil
3587 "Hook that is run after the tags in a line have changed.")
3589 (defgroup org-properties nil
3590 "Options concerning properties in Org-mode."
3591 :tag "Org Properties"
3592 :group 'org)
3594 (defcustom org-property-format "%-10s %s"
3595 "How property key/value pairs should be formatted by `indent-line'.
3596 When `indent-line' hits a property definition, it will format the line
3597 according to this format, mainly to make sure that the values are
3598 lined-up with respect to each other."
3599 :group 'org-properties
3600 :type 'string)
3602 (defcustom org-properties-postprocess-alist nil
3603 "Alist of properties and functions to adjust inserted values.
3604 Elements of this alist must be of the form
3606 ([string] [function])
3608 where [string] must be a property name and [function] must be a
3609 lambda expression: this lambda expression must take one argument,
3610 the value to adjust, and return the new value as a string.
3612 For example, this element will allow the property \"Remaining\"
3613 to be updated wrt the relation between the \"Effort\" property
3614 and the clock summary:
3616 ((\"Remaining\" (lambda(value)
3617 (let ((clocksum (org-clock-sum-current-item))
3618 (effort (org-duration-string-to-minutes
3619 (org-entry-get (point) \"Effort\"))))
3620 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3621 :group 'org-properties
3622 :version "24.1"
3623 :type '(alist :key-type (string :tag "Property")
3624 :value-type (function :tag "Function")))
3626 (defcustom org-use-property-inheritance nil
3627 "Non-nil means properties apply also for sublevels.
3629 This setting is chiefly used during property searches. Turning it on can
3630 cause significant overhead when doing a search, which is why it is not
3631 on by default.
3633 When nil, only the properties directly given in the current entry count.
3634 When t, every property is inherited. The value may also be a list of
3635 properties that should have inheritance, or a regular expression matching
3636 properties that should be inherited.
3638 However, note that some special properties use inheritance under special
3639 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3640 and the properties ending in \"_ALL\" when they are used as descriptor
3641 for valid values of a property.
3643 Note for programmers:
3644 When querying an entry with `org-entry-get', you can control if inheritance
3645 should be used. By default, `org-entry-get' looks only at the local
3646 properties. You can request inheritance by setting the inherit argument
3647 to t (to force inheritance) or to `selective' (to respect the setting
3648 in this variable)."
3649 :group 'org-properties
3650 :type '(choice
3651 (const :tag "Not" nil)
3652 (const :tag "Always" t)
3653 (repeat :tag "Specific properties" (string :tag "Property"))
3654 (regexp :tag "Properties matched by regexp")))
3656 (defun org-property-inherit-p (property)
3657 "Check if PROPERTY is one that should be inherited."
3658 (cond
3659 ((eq org-use-property-inheritance t) t)
3660 ((not org-use-property-inheritance) nil)
3661 ((stringp org-use-property-inheritance)
3662 (string-match org-use-property-inheritance property))
3663 ((listp org-use-property-inheritance)
3664 (member property org-use-property-inheritance))
3665 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3667 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3668 "The default column format, if no other format has been defined.
3669 This variable can be set on the per-file basis by inserting a line
3671 #+COLUMNS: %25ITEM ....."
3672 :group 'org-properties
3673 :type 'string)
3675 (defcustom org-columns-ellipses ".."
3676 "The ellipses to be used when a field in column view is truncated.
3677 When this is the empty string, as many characters as possible are shown,
3678 but then there will be no visual indication that the field has been truncated.
3679 When this is a string of length N, the last N characters of a truncated
3680 field are replaced by this string. If the column is narrower than the
3681 ellipses string, only part of the ellipses string will be shown."
3682 :group 'org-properties
3683 :type 'string)
3685 (defcustom org-columns-modify-value-for-display-function nil
3686 "Function that modifies values for display in column view.
3687 For example, it can be used to cut out a certain part from a time stamp.
3688 The function must take 2 arguments:
3690 column-title The title of the column (*not* the property name)
3691 value The value that should be modified.
3693 The function should return the value that should be displayed,
3694 or nil if the normal value should be used."
3695 :group 'org-properties
3696 :type '(choice (const nil) (function)))
3698 (defconst org-global-properties-fixed
3699 '(("VISIBILITY_ALL" . "folded children content all")
3700 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3701 "List of property/value pairs that can be inherited by any entry.
3703 These are fixed values, for the preset properties. The user variable
3704 that can be used to add to this list is `org-global-properties'.
3706 The entries in this list are cons cells where the car is a property
3707 name and cdr is a string with the value. If the value represents
3708 multiple items like an \"_ALL\" property, separate the items by
3709 spaces.")
3711 (defcustom org-global-properties nil
3712 "List of property/value pairs that can be inherited by any entry.
3714 This list will be combined with the constant `org-global-properties-fixed'.
3716 The entries in this list are cons cells where the car is a property
3717 name and cdr is a string with the value.
3719 You can set buffer-local values for the same purpose in the variable
3720 `org-file-properties' this by adding lines like
3722 #+PROPERTY: NAME VALUE"
3723 :group 'org-properties
3724 :type '(repeat
3725 (cons (string :tag "Property")
3726 (string :tag "Value"))))
3728 (defvar org-file-properties nil
3729 "List of property/value pairs that can be inherited by any entry.
3730 Valid for the current buffer.
3731 This variable is populated from #+PROPERTY lines.")
3732 (make-variable-buffer-local 'org-file-properties)
3734 (defgroup org-agenda nil
3735 "Options concerning agenda views in Org-mode."
3736 :tag "Org Agenda"
3737 :group 'org)
3739 (defvar org-category nil
3740 "Variable used by org files to set a category for agenda display.
3741 Such files should use a file variable to set it, for example
3743 # -*- mode: org; org-category: \"ELisp\"
3745 or contain a special line
3747 #+CATEGORY: ELisp
3749 If the file does not specify a category, then file's base name
3750 is used instead.")
3751 (make-variable-buffer-local 'org-category)
3752 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3754 (defcustom org-agenda-files nil
3755 "The files to be used for agenda display.
3756 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3757 \\[org-remove-file]. You can also use customize to edit the list.
3759 If an entry is a directory, all files in that directory that are matched by
3760 `org-agenda-file-regexp' will be part of the file list.
3762 If the value of the variable is not a list but a single file name, then
3763 the list of agenda files is actually stored and maintained in that file, one
3764 agenda file per line. In this file paths can be given relative to
3765 `org-directory'. Tilde expansion and environment variable substitution
3766 are also made."
3767 :group 'org-agenda
3768 :type '(choice
3769 (repeat :tag "List of files and directories" file)
3770 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3772 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3773 "Regular expression to match files for `org-agenda-files'.
3774 If any element in the list in that variable contains a directory instead
3775 of a normal file, all files in that directory that are matched by this
3776 regular expression will be included."
3777 :group 'org-agenda
3778 :type 'regexp)
3780 (defcustom org-agenda-text-search-extra-files nil
3781 "List of extra files to be searched by text search commands.
3782 These files will be searched in addition to the agenda files by the
3783 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3784 Note that these files will only be searched for text search commands,
3785 not for the other agenda views like todo lists, tag searches or the weekly
3786 agenda. This variable is intended to list notes and possibly archive files
3787 that should also be searched by these two commands.
3788 In fact, if the first element in the list is the symbol `agenda-archives',
3789 then all archive files of all agenda files will be added to the search
3790 scope."
3791 :group 'org-agenda
3792 :type '(set :greedy t
3793 (const :tag "Agenda Archives" agenda-archives)
3794 (repeat :inline t (file))))
3796 (org-defvaralias 'org-agenda-multi-occur-extra-files
3797 'org-agenda-text-search-extra-files)
3799 (defcustom org-agenda-skip-unavailable-files nil
3800 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3801 A nil value means to remove them, after a query, from the list."
3802 :group 'org-agenda
3803 :type 'boolean)
3805 (defcustom org-calendar-to-agenda-key [?c]
3806 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3807 The command `org-calendar-goto-agenda' will be bound to this key. The
3808 default is the character `c' because then `c' can be used to switch back and
3809 forth between agenda and calendar."
3810 :group 'org-agenda
3811 :type 'sexp)
3813 (defcustom org-calendar-insert-diary-entry-key [?i]
3814 "The key to be installed in `calendar-mode-map' for adding diary entries.
3815 This option is irrelevant until `org-agenda-diary-file' has been configured
3816 to point to an Org-mode file. When that is the case, the command
3817 `org-agenda-diary-entry' will be bound to the key given here, by default
3818 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3819 if you want to continue doing this, you need to change this to a different
3820 key."
3821 :group 'org-agenda
3822 :type 'sexp)
3824 (defcustom org-agenda-diary-file 'diary-file
3825 "File to which to add new entries with the `i' key in agenda and calendar.
3826 When this is the symbol `diary-file', the functionality in the Emacs
3827 calendar will be used to add entries to the `diary-file'. But when this
3828 points to a file, `org-agenda-diary-entry' will be used instead."
3829 :group 'org-agenda
3830 :type '(choice
3831 (const :tag "The standard Emacs diary file" diary-file)
3832 (file :tag "Special Org file diary entries")))
3834 (eval-after-load "calendar"
3835 '(progn
3836 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3837 'org-calendar-goto-agenda)
3838 (add-hook 'calendar-mode-hook
3839 (lambda ()
3840 (unless (eq org-agenda-diary-file 'diary-file)
3841 (define-key calendar-mode-map
3842 org-calendar-insert-diary-entry-key
3843 'org-agenda-diary-entry))))))
3845 (defgroup org-latex nil
3846 "Options for embedding LaTeX code into Org-mode."
3847 :tag "Org LaTeX"
3848 :group 'org)
3850 (defcustom org-format-latex-options
3851 '(:foreground default :background default :scale 1.0
3852 :html-foreground "Black" :html-background "Transparent"
3853 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3854 "Options for creating images from LaTeX fragments.
3855 This is a property list with the following properties:
3856 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3857 `default' means use the foreground of the default face.
3858 `auto' means use the foreground from the text face.
3859 :background the background color, or \"Transparent\".
3860 `default' means use the background of the default face.
3861 `auto' means use the background from the text face.
3862 :scale a scaling factor for the size of the images, to get more pixels
3863 :html-foreground, :html-background, :html-scale
3864 the same numbers for HTML export.
3865 :matchers a list indicating which matchers should be used to
3866 find LaTeX fragments. Valid members of this list are:
3867 \"begin\" find environments
3868 \"$1\" find single characters surrounded by $.$
3869 \"$\" find math expressions surrounded by $...$
3870 \"$$\" find math expressions surrounded by $$....$$
3871 \"\\(\" find math expressions surrounded by \\(...\\)
3872 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3873 :group 'org-latex
3874 :type 'plist)
3876 (defcustom org-format-latex-signal-error t
3877 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3878 When nil, just push out a message."
3879 :group 'org-latex
3880 :version "24.1"
3881 :type 'boolean)
3883 (defcustom org-latex-to-mathml-jar-file nil
3884 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3885 Use this to specify additional executable file say a jar file.
3887 When using MathToWeb as the converter, specify the full-path to
3888 your mathtoweb.jar file."
3889 :group 'org-latex
3890 :version "24.1"
3891 :type '(choice
3892 (const :tag "None" nil)
3893 (file :tag "JAR file" :must-match t)))
3895 (defcustom org-latex-to-mathml-convert-command nil
3896 "Command to convert LaTeX fragments to MathML.
3897 Replace format-specifiers in the command as noted below and use
3898 `shell-command' to convert LaTeX to MathML.
3899 %j: Executable file in fully expanded form as specified by
3900 `org-latex-to-mathml-jar-file'.
3901 %I: Input LaTeX file in fully expanded form
3902 %o: Output MathML file
3903 This command is used by `org-create-math-formula'.
3905 When using MathToWeb as the converter, set this to
3906 \"java -jar %j -unicode -force -df %o %I\"."
3907 :group 'org-latex
3908 :version "24.1"
3909 :type '(choice
3910 (const :tag "None" nil)
3911 (string :tag "\nShell command")))
3913 (defcustom org-latex-create-formula-image-program 'dvipng
3914 "Program to convert LaTeX fragments with.
3916 dvipng Process the LaTeX fragments to dvi file, then convert
3917 dvi files to png files using dvipng.
3918 This will also include processing of non-math environments.
3919 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3920 to convert pdf files to png files"
3921 :group 'org-latex
3922 :version "24.1"
3923 :type '(choice
3924 (const :tag "dvipng" dvipng)
3925 (const :tag "imagemagick" imagemagick)))
3927 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3928 "Path to store latex preview images.
3929 A relative path here creates many directories relative to the
3930 processed org files paths. An absolute path puts all preview
3931 images at the same place."
3932 :group 'org-latex
3933 :version "24.3"
3934 :type 'string)
3936 (defun org-format-latex-mathml-available-p ()
3937 "Return t if `org-latex-to-mathml-convert-command' is usable."
3938 (save-match-data
3939 (when (and (boundp 'org-latex-to-mathml-convert-command)
3940 org-latex-to-mathml-convert-command)
3941 (let ((executable (car (split-string
3942 org-latex-to-mathml-convert-command))))
3943 (when (executable-find executable)
3944 (if (string-match
3945 "%j" org-latex-to-mathml-convert-command)
3946 (file-readable-p org-latex-to-mathml-jar-file)
3947 t))))))
3949 (defcustom org-format-latex-header "\\documentclass{article}
3950 \\usepackage[usenames]{color}
3951 \[PACKAGES]
3952 \[DEFAULT-PACKAGES]
3953 \\pagestyle{empty} % do not remove
3954 % The settings below are copied from fullpage.sty
3955 \\setlength{\\textwidth}{\\paperwidth}
3956 \\addtolength{\\textwidth}{-3cm}
3957 \\setlength{\\oddsidemargin}{1.5cm}
3958 \\addtolength{\\oddsidemargin}{-2.54cm}
3959 \\setlength{\\evensidemargin}{\\oddsidemargin}
3960 \\setlength{\\textheight}{\\paperheight}
3961 \\addtolength{\\textheight}{-\\headheight}
3962 \\addtolength{\\textheight}{-\\headsep}
3963 \\addtolength{\\textheight}{-\\footskip}
3964 \\addtolength{\\textheight}{-3cm}
3965 \\setlength{\\topmargin}{1.5cm}
3966 \\addtolength{\\topmargin}{-2.54cm}"
3967 "The document header used for processing LaTeX fragments.
3968 It is imperative that this header make sure that no page number
3969 appears on the page. The package defined in the variables
3970 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3971 will either replace the placeholder \"[PACKAGES]\" in this
3972 header, or they will be appended."
3973 :group 'org-latex
3974 :type 'string)
3976 (defun org-set-packages-alist (var val)
3977 "Set the packages alist and make sure it has 3 elements per entry."
3978 (set var (mapcar (lambda (x)
3979 (if (and (consp x) (= (length x) 2))
3980 (list (car x) (nth 1 x) t)
3982 val)))
3984 (defun org-get-packages-alist (var)
3985 "Get the packages alist and make sure it has 3 elements per entry."
3986 (mapcar (lambda (x)
3987 (if (and (consp x) (= (length x) 2))
3988 (list (car x) (nth 1 x) t)
3990 (default-value var)))
3992 (defcustom org-latex-default-packages-alist
3993 '(("AUTO" "inputenc" t)
3994 ("T1" "fontenc" t)
3995 ("" "fixltx2e" nil)
3996 ("" "graphicx" t)
3997 ("" "longtable" nil)
3998 ("" "float" nil)
3999 ("" "wrapfig" nil)
4000 ("" "rotating" nil)
4001 ("normalem" "ulem" t)
4002 ("" "amsmath" t)
4003 ("" "textcomp" t)
4004 ("" "marvosym" t)
4005 ("" "wasysym" t)
4006 ("" "amssymb" t)
4007 ("" "capt-of" nil)
4008 ("" "hyperref" nil)
4009 "\\tolerance=1000")
4010 "Alist of default packages to be inserted in the header.
4012 Change this only if one of the packages here causes an
4013 incompatibility with another package you are using.
4015 The packages in this list are needed by one part or another of
4016 Org mode to function properly:
4018 - inputenc, fontenc: for basic font and character selection
4019 - fixltx2e: Important patches of LaTeX itself
4020 - graphicx: for including images
4021 - longtable: For multipage tables
4022 - float, wrapfig: for figure placement
4023 - rotating: for sideways figures and tables
4024 - ulem: for underline and strike-through
4025 - amsmath: for subscript and superscript and math environments
4026 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4027 for interpreting the entities in `org-entities'. You can skip
4028 some of these packages if you don't use any of their symbols.
4029 - capt-of: for captions outside of floats
4030 - hyperref: for cross references
4032 Therefore you should not modify this variable unless you know
4033 what you are doing. The one reason to change it anyway is that
4034 you might be loading some other package that conflicts with one
4035 of the default packages. Each element is either a cell or
4036 a string.
4038 A cell is of the format:
4040 \( \"options\" \"package\" SNIPPET-FLAG).
4042 If SNIPPET-FLAG is non-nil, the package also needs to be included
4043 when compiling LaTeX snippets into images for inclusion into
4044 non-LaTeX output.
4046 A string will be inserted as-is in the header of the document."
4047 :group 'org-latex
4048 :group 'org-export-latex
4049 :set 'org-set-packages-alist
4050 :get 'org-get-packages-alist
4051 :version "24.1"
4052 :type '(repeat
4053 (choice
4054 (list :tag "options/package pair"
4055 (string :tag "options")
4056 (string :tag "package")
4057 (boolean :tag "Snippet"))
4058 (string :tag "A line of LaTeX"))))
4060 (defcustom org-latex-packages-alist nil
4061 "Alist of packages to be inserted in every LaTeX header.
4063 These will be inserted after `org-latex-default-packages-alist'.
4064 Each element is either a cell or a string.
4066 A cell is of the format:
4068 \(\"options\" \"package\" SNIPPET-FLAG)
4070 SNIPPET-FLAG, when non-nil, indicates that this package is also
4071 needed when turning LaTeX snippets into images for inclusion into
4072 non-LaTeX output.
4074 A string will be inserted as-is in the header of the document.
4076 Make sure that you only list packages here which:
4078 - you want in every file;
4079 - do not conflict with the setup in `org-format-latex-header';
4080 - do not conflict with the default packages in
4081 `org-latex-default-packages-alist'."
4082 :group 'org-latex
4083 :group 'org-export-latex
4084 :set 'org-set-packages-alist
4085 :get 'org-get-packages-alist
4086 :type '(repeat
4087 (choice
4088 (list :tag "options/package pair"
4089 (string :tag "options")
4090 (string :tag "package")
4091 (boolean :tag "Snippet"))
4092 (string :tag "A line of LaTeX"))))
4094 (defgroup org-appearance nil
4095 "Settings for Org-mode appearance."
4096 :tag "Org Appearance"
4097 :group 'org)
4099 (defcustom org-level-color-stars-only nil
4100 "Non-nil means fontify only the stars in each headline.
4101 When nil, the entire headline is fontified.
4102 Changing it requires restart of `font-lock-mode' to become effective
4103 also in regions already fontified."
4104 :group 'org-appearance
4105 :type 'boolean)
4107 (defcustom org-hide-leading-stars nil
4108 "Non-nil means hide the first N-1 stars in a headline.
4109 This works by using the face `org-hide' for these stars. This
4110 face is white for a light background, and black for a dark
4111 background. You may have to customize the face `org-hide' to
4112 make this work.
4113 Changing it requires restart of `font-lock-mode' to become effective
4114 also in regions already fontified.
4115 You may also set this on a per-file basis by adding one of the following
4116 lines to the buffer:
4118 #+STARTUP: hidestars
4119 #+STARTUP: showstars"
4120 :group 'org-appearance
4121 :type 'boolean)
4123 (defcustom org-hidden-keywords nil
4124 "List of symbols corresponding to keywords to be hidden the org buffer.
4125 For example, a value '(title) for this list will make the document's title
4126 appear in the buffer without the initial #+TITLE: keyword."
4127 :group 'org-appearance
4128 :version "24.1"
4129 :type '(set (const :tag "#+AUTHOR" author)
4130 (const :tag "#+DATE" date)
4131 (const :tag "#+EMAIL" email)
4132 (const :tag "#+TITLE" title)))
4134 (defcustom org-custom-properties nil
4135 "List of properties (as strings) with a special meaning.
4136 The default use of these custom properties is to let the user
4137 hide them with `org-toggle-custom-properties-visibility'."
4138 :group 'org-properties
4139 :group 'org-appearance
4140 :version "24.3"
4141 :type '(repeat (string :tag "Property Name")))
4143 (defcustom org-fontify-done-headline nil
4144 "Non-nil means change the face of a headline if it is marked DONE.
4145 Normally, only the TODO/DONE keyword indicates the state of a headline.
4146 When this is non-nil, the headline after the keyword is set to the
4147 `org-headline-done' as an additional indication."
4148 :group 'org-appearance
4149 :type 'boolean)
4151 (defcustom org-fontify-emphasized-text t
4152 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4153 Changing this variable requires a restart of Emacs to take effect."
4154 :group 'org-appearance
4155 :type 'boolean)
4157 (defcustom org-fontify-whole-heading-line nil
4158 "Non-nil means fontify the whole line for headings.
4159 This is useful when setting a background color for the
4160 org-level-* faces."
4161 :group 'org-appearance
4162 :type 'boolean)
4164 (defcustom org-highlight-latex-and-related nil
4165 "Non-nil means highlight LaTeX related syntax in the buffer.
4166 When non nil, the value should be a list containing any of the
4167 following symbols:
4168 `latex' Highlight LaTeX snippets and environments.
4169 `script' Highlight subscript and superscript.
4170 `entities' Highlight entities."
4171 :group 'org-appearance
4172 :version "24.4"
4173 :package-version '(Org . "8.0")
4174 :type '(choice
4175 (const :tag "No highlighting" nil)
4176 (set :greedy t :tag "Highlight"
4177 (const :tag "LaTeX snippets and environments" latex)
4178 (const :tag "Subscript and superscript" script)
4179 (const :tag "Entities" entities))))
4181 (defcustom org-hide-emphasis-markers nil
4182 "Non-nil mean font-lock should hide the emphasis marker characters."
4183 :group 'org-appearance
4184 :type 'boolean)
4186 (defcustom org-hide-macro-markers nil
4187 "Non-nil mean font-lock should hide the brackets marking macro calls."
4188 :group 'org-appearance
4189 :type 'boolean)
4191 (defcustom org-pretty-entities nil
4192 "Non-nil means show entities as UTF8 characters.
4193 When nil, the \\name form remains in the buffer."
4194 :group 'org-appearance
4195 :version "24.1"
4196 :type 'boolean)
4198 (defcustom org-pretty-entities-include-sub-superscripts t
4199 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4200 :group 'org-appearance
4201 :version "24.1"
4202 :type 'boolean)
4204 (defvar org-emph-re nil
4205 "Regular expression for matching emphasis.
4206 After a match, the match groups contain these elements:
4207 0 The match of the full regular expression, including the characters
4208 before and after the proper match
4209 1 The character before the proper match, or empty at beginning of line
4210 2 The proper match, including the leading and trailing markers
4211 3 The leading marker like * or /, indicating the type of highlighting
4212 4 The text between the emphasis markers, not including the markers
4213 5 The character after the match, empty at the end of a line")
4214 (defvar org-verbatim-re nil
4215 "Regular expression for matching verbatim text.")
4216 (defvar org-emphasis-regexp-components) ; defined just below
4217 (defvar org-emphasis-alist) ; defined just below
4218 (defun org-set-emph-re (var val)
4219 "Set variable and compute the emphasis regular expression."
4220 (set var val)
4221 (when (and (boundp 'org-emphasis-alist)
4222 (boundp 'org-emphasis-regexp-components)
4223 org-emphasis-alist org-emphasis-regexp-components)
4224 (let* ((e org-emphasis-regexp-components)
4225 (pre (car e))
4226 (post (nth 1 e))
4227 (border (nth 2 e))
4228 (body (nth 3 e))
4229 (nl (nth 4 e))
4230 (body1 (concat body "*?"))
4231 (markers (mapconcat 'car org-emphasis-alist ""))
4232 (vmarkers (mapconcat
4233 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4234 org-emphasis-alist "")))
4235 ;; make sure special characters appear at the right position in the class
4236 (if (string-match "\\^" markers)
4237 (setq markers (concat (replace-match "" t t markers) "^")))
4238 (if (string-match "-" markers)
4239 (setq markers (concat (replace-match "" t t markers) "-")))
4240 (if (string-match "\\^" vmarkers)
4241 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4242 (if (string-match "-" vmarkers)
4243 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4244 (if (> nl 0)
4245 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4246 (int-to-string nl) "\\}")))
4247 ;; Make the regexp
4248 (setq org-emph-re
4249 (concat "\\([" pre "]\\|^\\)"
4250 "\\("
4251 "\\([" markers "]\\)"
4252 "\\("
4253 "[^" border "]\\|"
4254 "[^" border "]"
4255 body1
4256 "[^" border "]"
4257 "\\)"
4258 "\\3\\)"
4259 "\\([" post "]\\|$\\)"))
4260 (setq org-verbatim-re
4261 (concat "\\([" pre "]\\|^\\)"
4262 "\\("
4263 "\\([" vmarkers "]\\)"
4264 "\\("
4265 "[^" border "]\\|"
4266 "[^" border "]"
4267 body1
4268 "[^" border "]"
4269 "\\)"
4270 "\\3\\)"
4271 "\\([" post "]\\|$\\)")))))
4273 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4274 ;; set this option proved cumbersome. See this message/thread:
4275 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4276 (defvar org-emphasis-regexp-components
4277 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4278 "Components used to build the regular expression for emphasis.
4279 This is a list with five entries. Terminology: In an emphasis string
4280 like \" *strong word* \", we call the initial space PREMATCH, the final
4281 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4282 and \"trong wor\" is the body. The different components in this variable
4283 specify what is allowed/forbidden in each part:
4285 pre Chars allowed as prematch. Beginning of line will be allowed too.
4286 post Chars allowed as postmatch. End of line will be allowed too.
4287 border The chars *forbidden* as border characters.
4288 body-regexp A regexp like \".\" to match a body character. Don't use
4289 non-shy groups here, and don't allow newline here.
4290 newline The maximum number of newlines allowed in an emphasis exp.
4292 You need to reload Org or to restart Emacs after customizing this.")
4294 (defcustom org-emphasis-alist
4295 `(("*" bold)
4296 ("/" italic)
4297 ("_" underline)
4298 ("=" org-verbatim verbatim)
4299 ("~" org-code verbatim)
4300 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4301 "Alist of characters and faces to emphasize text.
4302 Text starting and ending with a special character will be emphasized,
4303 for example *bold*, _underlined_ and /italic/. This variable sets the
4304 marker characters and the face to be used by font-lock for highlighting
4305 in Org-mode Emacs buffers.
4307 You need to reload Org or to restart Emacs after customizing this."
4308 :group 'org-appearance
4309 :set 'org-set-emph-re
4310 :version "24.4"
4311 :package-version '(Org . "8.0")
4312 :type '(repeat
4313 (list
4314 (string :tag "Marker character")
4315 (choice
4316 (face :tag "Font-lock-face")
4317 (plist :tag "Face property list"))
4318 (option (const verbatim)))))
4320 (defvar org-protecting-blocks
4321 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4322 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4323 This is needed for font-lock setup.")
4325 ;;; Miscellaneous options
4327 (defgroup org-completion nil
4328 "Completion in Org-mode."
4329 :tag "Org Completion"
4330 :group 'org)
4332 (defcustom org-completion-use-ido nil
4333 "Non-nil means use ido completion wherever possible.
4334 Note that `ido-mode' must be active for this variable to be relevant.
4335 If you decide to turn this variable on, you might well want to turn off
4336 `org-outline-path-complete-in-steps'.
4337 See also `org-completion-use-iswitchb'."
4338 :group 'org-completion
4339 :type 'boolean)
4341 (defcustom org-completion-use-iswitchb nil
4342 "Non-nil means use iswitchb completion wherever possible.
4343 Note that `iswitchb-mode' must be active for this variable to be relevant.
4344 If you decide to turn this variable on, you might well want to turn off
4345 `org-outline-path-complete-in-steps'.
4346 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4347 :group 'org-completion
4348 :type 'boolean)
4350 (defcustom org-completion-fallback-command 'hippie-expand
4351 "The expansion command called by \\[pcomplete] in normal context.
4352 Normal means, no org-mode-specific context."
4353 :group 'org-completion
4354 :type 'function)
4356 ;;; Functions and variables from their packages
4357 ;; Declared here to avoid compiler warnings
4359 ;; XEmacs only
4360 (defvar outline-mode-menu-heading)
4361 (defvar outline-mode-menu-show)
4362 (defvar outline-mode-menu-hide)
4363 (defvar zmacs-regions) ; XEmacs regions
4365 ;; Emacs only
4366 (defvar mark-active)
4368 ;; Various packages
4369 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4370 (declare-function calendar-forward-day "cal-move" (arg))
4371 (declare-function calendar-goto-date "cal-move" (date))
4372 (declare-function calendar-goto-today "cal-move" ())
4373 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4374 (defvar calc-embedded-close-formula)
4375 (defvar calc-embedded-open-formula)
4376 (declare-function cdlatex-tab "ext:cdlatex" ())
4377 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4378 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4379 (defvar font-lock-unfontify-region-function)
4380 (declare-function iswitchb-read-buffer "iswitchb"
4381 (prompt &optional default require-match start matches-set))
4382 (defvar iswitchb-temp-buflist)
4383 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4384 (defvar org-agenda-tags-todo-honor-ignore-options)
4385 (declare-function org-agenda-skip "org-agenda" ())
4386 (declare-function
4387 org-agenda-format-item "org-agenda"
4388 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4389 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4390 (declare-function org-agenda-change-all-lines "org-agenda"
4391 (newhead hdmarker &optional fixface just-this))
4392 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4393 (declare-function org-agenda-maybe-redo "org-agenda" ())
4394 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4395 (beg end))
4396 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4397 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4398 "org-agenda" (&optional end))
4399 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4400 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4401 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4402 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4403 (declare-function org-indent-mode "org-indent" (&optional arg))
4404 (declare-function parse-time-string "parse-time" (string))
4405 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4406 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4407 (defvar remember-data-file)
4408 (defvar texmathp-why)
4409 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4410 (declare-function table--at-cell-p "table" (position &optional object at-column))
4411 (declare-function calc-eval "calc" (str &optional separator &rest args))
4413 ;;;###autoload
4414 (defun turn-on-orgtbl ()
4415 "Unconditionally turn on `orgtbl-mode'."
4416 (require 'org-table)
4417 (orgtbl-mode 1))
4419 (defun org-at-table-p (&optional table-type)
4420 "Return t if the cursor is inside an org-type table.
4421 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4422 (if org-enable-table-editor
4423 (save-excursion
4424 (beginning-of-line 1)
4425 (looking-at (if table-type org-table-any-line-regexp
4426 org-table-line-regexp)))
4427 nil))
4428 (defsubst org-table-p () (org-at-table-p))
4430 (defun org-at-table.el-p ()
4431 "Return t if and only if we are at a table.el table."
4432 (and (org-at-table-p 'any)
4433 (save-excursion
4434 (goto-char (org-table-begin 'any))
4435 (looking-at org-table1-hline-regexp))))
4437 (defun org-table-recognize-table.el ()
4438 "If there is a table.el table nearby, recognize it and move into it."
4439 (if org-table-tab-recognizes-table.el
4440 (if (org-at-table.el-p)
4441 (progn
4442 (beginning-of-line 1)
4443 (if (looking-at org-table-dataline-regexp)
4445 (if (looking-at org-table1-hline-regexp)
4446 (progn
4447 (beginning-of-line 2)
4448 (if (looking-at org-table-any-border-regexp)
4449 (beginning-of-line -1)))))
4450 (if (re-search-forward "|" (org-table-end t) t)
4451 (progn
4452 (require 'table)
4453 (if (table--at-cell-p (point))
4455 (message "recognizing table.el table...")
4456 (table-recognize-table)
4457 (message "recognizing table.el table...done")))
4458 (error "This should not happen"))
4460 nil)
4461 nil))
4463 (defun org-at-table-hline-p ()
4464 "Return t if the cursor is inside a hline in a table."
4465 (if org-enable-table-editor
4466 (save-excursion
4467 (beginning-of-line 1)
4468 (looking-at org-table-hline-regexp))
4469 nil))
4471 (defun org-table-map-tables (function &optional quietly)
4472 "Apply FUNCTION to the start of all tables in the buffer."
4473 (save-excursion
4474 (save-restriction
4475 (widen)
4476 (goto-char (point-min))
4477 (while (re-search-forward org-table-any-line-regexp nil t)
4478 (unless quietly
4479 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4480 (beginning-of-line 1)
4481 (when (and (looking-at org-table-line-regexp)
4482 ;; Exclude tables in src/example/verbatim/clocktable blocks
4483 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4484 (save-excursion (funcall function))
4485 (or (looking-at org-table-line-regexp)
4486 (forward-char 1)))
4487 (re-search-forward org-table-any-border-regexp nil 1))))
4488 (unless quietly (message "Mapping tables: done")))
4490 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4491 (declare-function org-clock-update-mode-line "org-clock" ())
4492 (declare-function org-resolve-clocks "org-clock"
4493 (&optional also-non-dangling-p prompt last-valid))
4495 (defun org-at-TBLFM-p (&optional pos)
4496 "Return t when point (or POS) is in #+TBLFM line."
4497 (save-excursion
4498 (let ((pos pos)))
4499 (goto-char (or pos (point)))
4500 (beginning-of-line 1)
4501 (looking-at org-TBLFM-regexp)))
4503 (defvar org-clock-start-time)
4504 (defvar org-clock-marker (make-marker)
4505 "Marker recording the last clock-in.")
4506 (defvar org-clock-hd-marker (make-marker)
4507 "Marker recording the last clock-in, but the headline position.")
4508 (defvar org-clock-heading ""
4509 "The heading of the current clock entry.")
4510 (defun org-clock-is-active ()
4511 "Return the buffer where the clock is currently running.
4512 Return nil if no clock is running."
4513 (marker-buffer org-clock-marker))
4515 (defun org-check-running-clock ()
4516 "Check if the current buffer contains the running clock.
4517 If yes, offer to stop it and to save the buffer with the changes."
4518 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4519 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4520 (buffer-name))))
4521 (org-clock-out)
4522 (when (y-or-n-p "Save changed buffer?")
4523 (save-buffer))))
4525 (defun org-clocktable-try-shift (dir n)
4526 "Check if this line starts a clock table, if yes, shift the time block."
4527 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4528 (org-clocktable-shift dir n)))
4530 ;;;###autoload
4531 (defun org-clock-persistence-insinuate ()
4532 "Set up hooks for clock persistence."
4533 (require 'org-clock)
4534 (add-hook 'org-mode-hook 'org-clock-load)
4535 (add-hook 'kill-emacs-hook 'org-clock-save))
4537 (defgroup org-archive nil
4538 "Options concerning archiving in Org-mode."
4539 :tag "Org Archive"
4540 :group 'org-structure)
4542 (defcustom org-archive-location "%s_archive::"
4543 "The location where subtrees should be archived.
4545 The value of this variable is a string, consisting of two parts,
4546 separated by a double-colon. The first part is a filename and
4547 the second part is a headline.
4549 When the filename is omitted, archiving happens in the same file.
4550 %s in the filename will be replaced by the current file
4551 name (without the directory part). Archiving to a different file
4552 is useful to keep archived entries from contributing to the
4553 Org-mode Agenda.
4555 The archived entries will be filed as subtrees of the specified
4556 headline. When the headline is omitted, the subtrees are simply
4557 filed away at the end of the file, as top-level entries. Also in
4558 the heading you can use %s to represent the file name, this can be
4559 useful when using the same archive for a number of different files.
4561 Here are a few examples:
4562 \"%s_archive::\"
4563 If the current file is Projects.org, archive in file
4564 Projects.org_archive, as top-level trees. This is the default.
4566 \"::* Archived Tasks\"
4567 Archive in the current file, under the top-level headline
4568 \"* Archived Tasks\".
4570 \"~/org/archive.org::\"
4571 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4573 \"~/org/archive.org::* From %s\"
4574 Archive in file ~/org/archive.org (absolute path), under headlines
4575 \"From FILENAME\" where file name is the current file name.
4577 \"~/org/datetree.org::datetree/* Finished Tasks\"
4578 The \"datetree/\" string is special, signifying to archive
4579 items to the datetree. Items are placed in either the CLOSED
4580 date of the item, or the current date if there is no CLOSED date.
4581 The heading will be a subentry to the current date. There doesn't
4582 need to be a heading, but there always needs to be a slash after
4583 datetree. For example, to store archived items directly in the
4584 datetree, use \"~/org/datetree.org::datetree/\".
4586 \"basement::** Finished Tasks\"
4587 Archive in file ./basement (relative path), as level 3 trees
4588 below the level 2 heading \"** Finished Tasks\".
4590 You may set this option on a per-file basis by adding to the buffer a
4591 line like
4593 #+ARCHIVE: basement::** Finished Tasks
4595 You may also define it locally for a subtree by setting an ARCHIVE property
4596 in the entry. If such a property is found in an entry, or anywhere up
4597 the hierarchy, it will be used."
4598 :group 'org-archive
4599 :type 'string)
4601 (defcustom org-agenda-skip-archived-trees t
4602 "Non-nil means the agenda will skip any items located in archived trees.
4603 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4604 variable is no longer recommended, you should leave it at the value t.
4605 Instead, use the key `v' to cycle the archives-mode in the agenda."
4606 :group 'org-archive
4607 :group 'org-agenda-skip
4608 :type 'boolean)
4610 (defcustom org-columns-skip-archived-trees t
4611 "Non-nil means ignore archived trees when creating column view."
4612 :group 'org-archive
4613 :group 'org-properties
4614 :type 'boolean)
4616 (defcustom org-cycle-open-archived-trees nil
4617 "Non-nil means `org-cycle' will open archived trees.
4618 An archived tree is a tree marked with the tag ARCHIVE.
4619 When nil, archived trees will stay folded. You can still open them with
4620 normal outline commands like `show-all', but not with the cycling commands."
4621 :group 'org-archive
4622 :group 'org-cycle
4623 :type 'boolean)
4625 (defcustom org-sparse-tree-open-archived-trees nil
4626 "Non-nil means sparse tree construction shows matches in archived trees.
4627 When nil, matches in these trees are highlighted, but the trees are kept in
4628 collapsed state."
4629 :group 'org-archive
4630 :group 'org-sparse-trees
4631 :type 'boolean)
4633 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4634 "The default date type when building a sparse tree.
4635 When this is nil, a date is a scheduled or a deadline timestamp.
4636 Otherwise, these types are allowed:
4638 all: all timestamps
4639 active: only active timestamps (<...>)
4640 inactive: only inactive timestamps (<...)
4641 scheduled: only scheduled timestamps
4642 deadline: only deadline timestamps"
4643 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4644 (const :tag "All timestamps" all)
4645 (const :tag "Only active timestamps" active)
4646 (const :tag "Only inactive timestamps" inactive)
4647 (const :tag "Only scheduled timestamps" scheduled)
4648 (const :tag "Only deadline timestamps" deadline)
4649 (const :tag "Only closed timestamps" closed))
4650 :version "24.3"
4651 :group 'org-sparse-trees)
4653 (defun org-cycle-hide-archived-subtrees (state)
4654 "Re-hide all archived subtrees after a visibility state change."
4655 (when (and (not org-cycle-open-archived-trees)
4656 (not (memq state '(overview folded))))
4657 (save-excursion
4658 (let* ((globalp (memq state '(contents all)))
4659 (beg (if globalp (point-min) (point)))
4660 (end (if globalp (point-max) (org-end-of-subtree t))))
4661 (org-hide-archived-subtrees beg end)
4662 (goto-char beg)
4663 (if (looking-at (concat ".*:" org-archive-tag ":"))
4664 (message "%s" (substitute-command-keys
4665 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4667 (defun org-force-cycle-archived ()
4668 "Cycle subtree even if it is archived."
4669 (interactive)
4670 (setq this-command 'org-cycle)
4671 (let ((org-cycle-open-archived-trees t))
4672 (call-interactively 'org-cycle)))
4674 (defun org-hide-archived-subtrees (beg end)
4675 "Re-hide all archived subtrees after a visibility state change."
4676 (save-excursion
4677 (let* ((re (concat ":" org-archive-tag ":")))
4678 (goto-char beg)
4679 (while (re-search-forward re end t)
4680 (when (org-at-heading-p)
4681 (org-flag-subtree t)
4682 (org-end-of-subtree t))))))
4684 (declare-function outline-end-of-heading "outline" ())
4685 (declare-function outline-flag-region "outline" (from to flag))
4686 (defun org-flag-subtree (flag)
4687 (save-excursion
4688 (org-back-to-heading t)
4689 (outline-end-of-heading)
4690 (outline-flag-region (point)
4691 (progn (org-end-of-subtree t) (point))
4692 flag)))
4694 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4696 ;; Declare Column View Code
4698 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4699 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4700 (declare-function org-columns-compute "org-colview" (property))
4702 ;; Declare ID code
4704 (declare-function org-id-store-link "org-id")
4705 (declare-function org-id-locations-load "org-id")
4706 (declare-function org-id-locations-save "org-id")
4707 (defvar org-id-track-globally)
4709 ;;; Variables for pre-computed regular expressions, all buffer local
4711 (defvar org-todo-regexp nil
4712 "Matches any of the TODO state keywords.")
4713 (make-variable-buffer-local 'org-todo-regexp)
4714 (defvar org-not-done-regexp nil
4715 "Matches any of the TODO state keywords except the last one.")
4716 (make-variable-buffer-local 'org-not-done-regexp)
4717 (defvar org-not-done-heading-regexp nil
4718 "Matches a TODO headline that is not done.")
4719 (make-variable-buffer-local 'org-not-done-regexp)
4720 (defvar org-todo-line-regexp nil
4721 "Matches a headline and puts TODO state into group 2 if present.")
4722 (make-variable-buffer-local 'org-todo-line-regexp)
4723 (defvar org-complex-heading-regexp nil
4724 "Matches a headline and puts everything into groups:
4725 group 1: the stars
4726 group 2: The todo keyword, maybe
4727 group 3: Priority cookie
4728 group 4: True headline
4729 group 5: Tags")
4730 (make-variable-buffer-local 'org-complex-heading-regexp)
4731 (defvar org-complex-heading-regexp-format nil
4732 "Printf format to make regexp to match an exact headline.
4733 This regexp will match the headline of any node which has the
4734 exact headline text that is put into the format, but may have any
4735 TODO state, priority and tags.")
4736 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4737 (defvar org-todo-line-tags-regexp nil
4738 "Matches a headline and puts TODO state into group 2 if present.
4739 Also put tags into group 4 if tags are present.")
4740 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4741 (defvar org-ds-keyword-length 12
4742 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4743 (make-variable-buffer-local 'org-ds-keyword-length)
4744 (defvar org-deadline-regexp nil
4745 "Matches the DEADLINE keyword.")
4746 (make-variable-buffer-local 'org-deadline-regexp)
4747 (defvar org-deadline-time-regexp nil
4748 "Matches the DEADLINE keyword together with a time stamp.")
4749 (make-variable-buffer-local 'org-deadline-time-regexp)
4750 (defvar org-deadline-time-hour-regexp nil
4751 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4752 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4753 (defvar org-deadline-line-regexp nil
4754 "Matches the DEADLINE keyword and the rest of the line.")
4755 (make-variable-buffer-local 'org-deadline-line-regexp)
4756 (defvar org-scheduled-regexp nil
4757 "Matches the SCHEDULED keyword.")
4758 (make-variable-buffer-local 'org-scheduled-regexp)
4759 (defvar org-scheduled-time-regexp nil
4760 "Matches the SCHEDULED keyword together with a time stamp.")
4761 (make-variable-buffer-local 'org-scheduled-time-regexp)
4762 (defvar org-scheduled-time-hour-regexp nil
4763 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4764 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4765 (defvar org-closed-time-regexp nil
4766 "Matches the CLOSED keyword together with a time stamp.")
4767 (make-variable-buffer-local 'org-closed-time-regexp)
4769 (defvar org-keyword-time-regexp nil
4770 "Matches any of the 4 keywords, together with the time stamp.")
4771 (make-variable-buffer-local 'org-keyword-time-regexp)
4772 (defvar org-keyword-time-not-clock-regexp nil
4773 "Matches any of the 3 keywords, together with the time stamp.")
4774 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4775 (defvar org-maybe-keyword-time-regexp nil
4776 "Matches a timestamp, possibly preceded by a keyword.")
4777 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4778 (defvar org-all-time-keywords nil
4779 "List of time keywords.")
4780 (make-variable-buffer-local 'org-all-time-keywords)
4782 (defconst org-plain-time-of-day-regexp
4783 (concat
4784 "\\(\\<[012]?[0-9]"
4785 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4786 "\\(--?"
4787 "\\(\\<[012]?[0-9]"
4788 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4789 "\\)?")
4790 "Regular expression to match a plain time or time range.
4791 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4792 groups carry important information:
4793 0 the full match
4794 1 the first time, range or not
4795 8 the second time, if it is a range.")
4797 (defconst org-plain-time-extension-regexp
4798 (concat
4799 "\\(\\<[012]?[0-9]"
4800 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4801 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4802 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4803 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4804 groups carry important information:
4805 0 the full match
4806 7 hours of duration
4807 9 minutes of duration")
4809 (defconst org-stamp-time-of-day-regexp
4810 (concat
4811 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4812 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4813 "\\(--?"
4814 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4815 "Regular expression to match a timestamp time or time range.
4816 After a match, the following groups carry important information:
4817 0 the full match
4818 1 date plus weekday, for back referencing to make sure both times are on the same day
4819 2 the first time, range or not
4820 4 the second time, if it is a range.")
4822 (defconst org-startup-options
4823 '(("fold" org-startup-folded t)
4824 ("overview" org-startup-folded t)
4825 ("nofold" org-startup-folded nil)
4826 ("showall" org-startup-folded nil)
4827 ("showeverything" org-startup-folded showeverything)
4828 ("content" org-startup-folded content)
4829 ("indent" org-startup-indented t)
4830 ("noindent" org-startup-indented nil)
4831 ("hidestars" org-hide-leading-stars t)
4832 ("showstars" org-hide-leading-stars nil)
4833 ("odd" org-odd-levels-only t)
4834 ("oddeven" org-odd-levels-only nil)
4835 ("align" org-startup-align-all-tables t)
4836 ("noalign" org-startup-align-all-tables nil)
4837 ("inlineimages" org-startup-with-inline-images t)
4838 ("noinlineimages" org-startup-with-inline-images nil)
4839 ("latexpreview" org-startup-with-latex-preview t)
4840 ("nolatexpreview" org-startup-with-latex-preview nil)
4841 ("customtime" org-display-custom-times t)
4842 ("logdone" org-log-done time)
4843 ("lognotedone" org-log-done note)
4844 ("nologdone" org-log-done nil)
4845 ("lognoteclock-out" org-log-note-clock-out t)
4846 ("nolognoteclock-out" org-log-note-clock-out nil)
4847 ("logrepeat" org-log-repeat state)
4848 ("lognoterepeat" org-log-repeat note)
4849 ("logdrawer" org-log-into-drawer t)
4850 ("nologdrawer" org-log-into-drawer nil)
4851 ("logstatesreversed" org-log-states-order-reversed t)
4852 ("nologstatesreversed" org-log-states-order-reversed nil)
4853 ("nologrepeat" org-log-repeat nil)
4854 ("logreschedule" org-log-reschedule time)
4855 ("lognotereschedule" org-log-reschedule note)
4856 ("nologreschedule" org-log-reschedule nil)
4857 ("logredeadline" org-log-redeadline time)
4858 ("lognoteredeadline" org-log-redeadline note)
4859 ("nologredeadline" org-log-redeadline nil)
4860 ("logrefile" org-log-refile time)
4861 ("lognoterefile" org-log-refile note)
4862 ("nologrefile" org-log-refile nil)
4863 ("fninline" org-footnote-define-inline t)
4864 ("nofninline" org-footnote-define-inline nil)
4865 ("fnlocal" org-footnote-section nil)
4866 ("fnauto" org-footnote-auto-label t)
4867 ("fnprompt" org-footnote-auto-label nil)
4868 ("fnconfirm" org-footnote-auto-label confirm)
4869 ("fnplain" org-footnote-auto-label plain)
4870 ("fnadjust" org-footnote-auto-adjust t)
4871 ("nofnadjust" org-footnote-auto-adjust nil)
4872 ("constcgs" constants-unit-system cgs)
4873 ("constSI" constants-unit-system SI)
4874 ("noptag" org-tag-persistent-alist nil)
4875 ("hideblocks" org-hide-block-startup t)
4876 ("nohideblocks" org-hide-block-startup nil)
4877 ("beamer" org-startup-with-beamer-mode t)
4878 ("entitiespretty" org-pretty-entities t)
4879 ("entitiesplain" org-pretty-entities nil))
4880 "Variable associated with STARTUP options for org-mode.
4881 Each element is a list of three items: the startup options (as written
4882 in the #+STARTUP line), the corresponding variable, and the value to set
4883 this variable to if the option is found. An optional forth element PUSH
4884 means to push this value onto the list in the variable.")
4886 (defcustom org-group-tags t
4887 "When non-nil (the default), use group tags.
4888 This can be turned on/off through `org-toggle-tags-groups'."
4889 :group 'org-tags
4890 :group 'org-startup
4891 :type 'boolean)
4893 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4895 (defun org-toggle-tags-groups ()
4896 "Toggle support for group tags.
4897 Support for group tags is controlled by the option
4898 `org-group-tags', which is non-nil by default."
4899 (interactive)
4900 (setq org-group-tags (not org-group-tags))
4901 (cond ((and (derived-mode-p 'org-agenda-mode)
4902 org-group-tags)
4903 (org-agenda-redo))
4904 ((derived-mode-p 'org-mode)
4905 (let ((org-inhibit-startup t)) (org-mode))))
4906 (message "Groups tags support has been turned %s"
4907 (if org-group-tags "on" "off")))
4909 (defun org-set-regexps-and-options-for-tags ()
4910 "Precompute variables used for tags."
4911 (when (derived-mode-p 'org-mode)
4912 (org-set-local 'org-file-tags nil)
4913 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4914 (splitre "[ \t]+")
4915 (start 0)
4916 tags ftags key value)
4917 (save-excursion
4918 (save-restriction
4919 (widen)
4920 (goto-char (point-min))
4921 (while (re-search-forward re nil t)
4922 (setq key (upcase (org-match-string-no-properties 1))
4923 value (org-match-string-no-properties 2))
4924 (if (stringp value) (setq value (org-trim value)))
4925 (cond
4926 ((equal key "TAGS")
4927 (setq tags (append tags (if tags '("\\n") nil)
4928 (org-split-string value splitre))))
4929 ((equal key "FILETAGS")
4930 (when (string-match "\\S-" value)
4931 (setq ftags
4932 (append
4933 ftags
4934 (apply 'append
4935 (mapcar (lambda (x) (org-split-string x ":"))
4936 (org-split-string value)))))))))))
4937 ;; Process the file tags.
4938 (and ftags (org-set-local 'org-file-tags
4939 (mapcar 'org-add-prop-inherited ftags)))
4940 (org-set-local 'org-tag-groups-alist nil)
4941 ;; Process the tags.
4942 (when (and (not tags) org-tag-alist)
4943 (setq tags
4944 (mapcar
4945 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4946 ((eq (car tg) :endgroup) "}")
4947 ((eq (car tg) :grouptags) ":")
4948 ((eq (car tg) :newline) "\n")
4949 (t (concat (car tg)
4950 (if (characterp (cdr tg))
4951 (format "(%s)" (char-to-string (cdr tg))) "")))))
4952 org-tag-alist)))
4953 (let (e tgs g)
4954 (while (setq e (pop tags))
4955 (cond
4956 ((equal e "{")
4957 (progn (push '(:startgroup) tgs)
4958 (when (equal (nth 1 tags) ":")
4959 (push (list (replace-regexp-in-string
4960 "(.+)$" "" (nth 0 tags)))
4961 org-tag-groups-alist)
4962 (setq g 0))))
4963 ((equal e ":") (push '(:grouptags) tgs))
4964 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4965 ((equal e "\\n") (push '(:newline) tgs))
4966 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4967 (push (cons (match-string 1 e)
4968 (string-to-char (match-string 2 e))) tgs)
4969 (if (and g (> g 0))
4970 (setcar org-tag-groups-alist
4971 (append (car org-tag-groups-alist)
4972 (list (match-string 1 e)))))
4973 (if g (setq g (1+ g))))
4974 (t (push (list e) tgs)
4975 (if (and g (> g 0))
4976 (setcar org-tag-groups-alist
4977 (append (car org-tag-groups-alist) (list e))))
4978 (if g (setq g (1+ g))))))
4979 (org-set-local 'org-tag-alist nil)
4980 (while (setq e (pop tgs))
4981 (or (and (stringp (car e))
4982 (assoc (car e) org-tag-alist))
4983 (push e org-tag-alist)))
4984 ;; Return a list with tag variables
4985 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4987 (defvar org-ota nil)
4988 (defun org-set-regexps-and-options ()
4989 "Precompute regular expressions used in the current buffer."
4990 (when (derived-mode-p 'org-mode)
4991 (org-set-local 'org-todo-kwd-alist nil)
4992 (org-set-local 'org-todo-key-alist nil)
4993 (org-set-local 'org-todo-key-trigger nil)
4994 (org-set-local 'org-todo-keywords-1 nil)
4995 (org-set-local 'org-done-keywords nil)
4996 (org-set-local 'org-todo-heads nil)
4997 (org-set-local 'org-todo-sets nil)
4998 (org-set-local 'org-todo-log-states nil)
4999 (org-set-local 'org-file-properties nil)
5000 (let ((re (org-make-options-regexp
5001 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
5002 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
5003 "SETUPFILE" "OPTIONS")
5004 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
5005 (splitre "[ \t]+")
5006 (scripts org-use-sub-superscripts)
5007 kwds kws0 kwsa key log value cat arch const links hw dws
5008 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
5009 (start 0))
5010 (save-excursion
5011 (save-restriction
5012 (widen)
5013 (goto-char (point-min))
5014 (while
5015 (or (and
5016 ext-setup-or-nil
5017 (not org-ota)
5018 (let (ret)
5019 (with-temp-buffer
5020 (insert ext-setup-or-nil)
5021 (let ((major-mode 'org-mode) org-ota)
5022 (setq ret (save-match-data
5023 (org-set-regexps-and-options-for-tags)))))
5024 ;; Append setupfile tags to existing tags
5025 (setq org-ota t)
5026 (setq org-file-tags
5027 (delq nil (append org-file-tags (nth 0 ret)))
5028 org-tag-alist
5029 (delq nil (append org-tag-alist (nth 1 ret)))
5030 org-tag-groups-alist
5031 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5032 (and ext-setup-or-nil
5033 (string-match re ext-setup-or-nil start)
5034 (setq start (match-end 0)))
5035 (and (setq ext-setup-or-nil nil start 0)
5036 (re-search-forward re nil t)))
5037 (setq key (upcase (match-string 1 ext-setup-or-nil))
5038 value (org-match-string-no-properties 2 ext-setup-or-nil))
5039 (if (stringp value) (setq value (org-trim value)))
5040 (cond
5041 ((equal key "CATEGORY")
5042 (setq cat value))
5043 ((member key '("SEQ_TODO" "TODO"))
5044 (push (cons 'sequence (org-split-string value splitre)) kwds))
5045 ((equal key "TYP_TODO")
5046 (push (cons 'type (org-split-string value splitre)) kwds))
5047 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5048 ;; general TODO-like setup
5049 (push (cons (intern (downcase (match-string 1 key)))
5050 (org-split-string value splitre)) kwds))
5051 ((equal key "COLUMNS")
5052 (org-set-local 'org-columns-default-format value))
5053 ((equal key "LINK")
5054 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5055 (push (cons (match-string 1 value)
5056 (org-trim (match-string 2 value)))
5057 links)))
5058 ((equal key "PRIORITIES")
5059 (setq prio (org-split-string value " +")))
5060 ((equal key "PROPERTY")
5061 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5062 (setq props (org--update-property-plist (match-string 1 value)
5063 (match-string 2 value)
5064 props))))
5065 ((equal key "CONSTANTS")
5066 (org-table-set-constants))
5067 ((equal key "STARTUP")
5068 (let ((opts (org-split-string value splitre))
5069 l var val)
5070 (while (setq l (pop opts))
5071 (when (setq l (assoc l org-startup-options))
5072 (setq var (nth 1 l) val (nth 2 l))
5073 (if (not (nth 3 l))
5074 (set (make-local-variable var) val)
5075 (if (not (listp (symbol-value var)))
5076 (set (make-local-variable var) nil))
5077 (set (make-local-variable var) (symbol-value var))
5078 (add-to-list var val))))))
5079 ((equal key "ARCHIVE")
5080 (setq arch value)
5081 (remove-text-properties 0 (length arch)
5082 '(face t fontified t) arch))
5083 ((equal key "OPTIONS")
5084 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5085 (setq scripts (read (match-string 2 value)))))
5086 ((and (equal key "SETUPFILE")
5087 ;; Prevent checking in Gnus messages
5088 (not buffer-read-only))
5089 (setq setup-contents (org-file-contents
5090 (expand-file-name
5091 (org-remove-double-quotes value))
5092 'noerror))
5093 (if (not ext-setup-or-nil)
5094 (setq ext-setup-or-nil setup-contents start 0)
5095 (setq ext-setup-or-nil
5096 (concat (substring ext-setup-or-nil 0 start)
5097 "\n" setup-contents "\n"
5098 (substring ext-setup-or-nil start)))))))))
5099 (org-set-local 'org-use-sub-superscripts scripts)
5100 (when cat
5101 (org-set-local 'org-category (intern cat))
5102 (push (cons "CATEGORY" cat) props))
5103 (when prio
5104 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5105 (setq prio (mapcar 'string-to-char prio))
5106 (org-set-local 'org-highest-priority (nth 0 prio))
5107 (org-set-local 'org-lowest-priority (nth 1 prio))
5108 (org-set-local 'org-default-priority (nth 2 prio)))
5109 (and props (org-set-local 'org-file-properties props))
5110 (and arch (org-set-local 'org-archive-location arch))
5111 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5112 ;; Process the TODO keywords
5113 (unless kwds
5114 ;; Use the global values as if they had been given locally.
5115 (setq kwds (default-value 'org-todo-keywords))
5116 (if (stringp (car kwds))
5117 (setq kwds (list (cons org-todo-interpretation
5118 (default-value 'org-todo-keywords)))))
5119 (setq kwds (reverse kwds)))
5120 (setq kwds (nreverse kwds))
5121 (let (inter kws kw)
5122 (while (setq kws (pop kwds))
5123 (let ((kws (or
5124 (run-hook-with-args-until-success
5125 'org-todo-setup-filter-hook kws)
5126 kws)))
5127 (setq inter (pop kws) sep (member "|" kws)
5128 kws0 (delete "|" (copy-sequence kws))
5129 kwsa nil
5130 kws1 (mapcar
5131 (lambda (x)
5132 ;; 1 2
5133 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5134 (progn
5135 (setq kw (match-string 1 x)
5136 key (and (match-end 2) (match-string 2 x))
5137 log (org-extract-log-state-settings x))
5138 (push (cons kw (and key (string-to-char key))) kwsa)
5139 (and log (push log org-todo-log-states))
5141 (error "Invalid TODO keyword %s" x)))
5142 kws0)
5143 kwsa (if kwsa (append '((:startgroup))
5144 (nreverse kwsa)
5145 '((:endgroup))))
5146 hw (car kws1)
5147 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5148 tail (list inter hw (car dws) (org-last dws))))
5149 (add-to-list 'org-todo-heads hw 'append)
5150 (push kws1 org-todo-sets)
5151 (setq org-done-keywords (append org-done-keywords dws nil))
5152 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5153 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5154 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5155 (setq org-todo-sets (nreverse org-todo-sets)
5156 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5157 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5158 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5159 ;; Compute the regular expressions and other local variables.
5160 ;; Using `org-outline-regexp-bol' would complicate them much,
5161 ;; because of the fixed white space at the end of that string.
5162 (if (not org-done-keywords)
5163 (setq org-done-keywords (and org-todo-keywords-1
5164 (list (org-last org-todo-keywords-1)))))
5165 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5166 (length org-scheduled-string)
5167 (length org-clock-string)
5168 (length org-closed-string)))
5169 org-not-done-keywords
5170 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5171 org-todo-regexp
5172 (concat "\\("
5173 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5174 "\\)")
5175 org-not-done-regexp
5176 (concat "\\("
5177 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5178 "\\)")
5179 org-not-done-heading-regexp
5180 (format org-heading-keyword-regexp-format org-not-done-regexp)
5181 org-todo-line-regexp
5182 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5183 org-complex-heading-regexp
5184 (concat "^\\(\\*+\\)"
5185 "\\(?: +" org-todo-regexp "\\)?"
5186 "\\(?: +\\(\\[#.\\]\\)\\)?"
5187 "\\(?: +\\(.*?\\)\\)??"
5188 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5189 "[ \t]*$")
5190 org-complex-heading-regexp-format
5191 (concat "^\\(\\*+\\)"
5192 "\\(?: +" org-todo-regexp "\\)?"
5193 "\\(?: +\\(\\[#.\\]\\)\\)?"
5194 "\\(?: +"
5195 ;; Stats cookies can be stuck to body.
5196 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5197 "\\(%s\\)"
5198 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5199 "\\)"
5200 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5201 "[ \t]*$")
5202 org-todo-line-tags-regexp
5203 (concat "^\\(\\*+\\)"
5204 "\\(?: +" org-todo-regexp "\\)?"
5205 "\\(?: +\\(.*?\\)\\)??"
5206 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5207 "[ \t]*$")
5208 org-deadline-regexp (concat "\\<" org-deadline-string)
5209 org-deadline-time-regexp
5210 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5211 org-deadline-time-hour-regexp
5212 (concat "\\<" org-deadline-string
5213 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5214 org-deadline-line-regexp
5215 (concat "\\<\\(" org-deadline-string "\\).*")
5216 org-scheduled-regexp
5217 (concat "\\<" org-scheduled-string)
5218 org-scheduled-time-regexp
5219 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5220 org-scheduled-time-hour-regexp
5221 (concat "\\<" org-scheduled-string
5222 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5223 org-closed-time-regexp
5224 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5225 org-keyword-time-regexp
5226 (concat "\\<\\(" org-scheduled-string
5227 "\\|" org-deadline-string
5228 "\\|" org-closed-string
5229 "\\|" org-clock-string "\\)"
5230 " *[[<]\\([^]>]+\\)[]>]")
5231 org-keyword-time-not-clock-regexp
5232 (concat "\\<\\(" org-scheduled-string
5233 "\\|" org-deadline-string
5234 "\\|" org-closed-string
5235 "\\)"
5236 " *[[<]\\([^]>]+\\)[]>]")
5237 org-maybe-keyword-time-regexp
5238 (concat "\\(\\<\\(" org-scheduled-string
5239 "\\|" org-deadline-string
5240 "\\|" org-closed-string
5241 "\\|" org-clock-string "\\)\\)?"
5242 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5243 org-all-time-keywords
5244 (mapcar (lambda (w) (substring w 0 -1))
5245 (list org-scheduled-string org-deadline-string
5246 org-clock-string org-closed-string)))
5247 (setq org-ota nil)
5248 (org-compute-latex-and-related-regexp))))
5250 (defun org-file-contents (file &optional noerror)
5251 "Return the contents of FILE, as a string."
5252 (if (and file (file-readable-p file))
5253 (with-temp-buffer
5254 (insert-file-contents file)
5255 (buffer-string))
5256 (funcall (if noerror 'message 'error)
5257 "Cannot read file \"%s\"%s"
5258 file
5259 (let ((from (buffer-file-name (buffer-base-buffer))))
5260 (if from (concat " (referenced in file \"" from "\")") "")))))
5262 (defun org-extract-log-state-settings (x)
5263 "Extract the log state setting from a TODO keyword string.
5264 This will extract info from a string like \"WAIT(w@/!)\"."
5265 (let (kw key log1 log2)
5266 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5267 (setq kw (match-string 1 x)
5268 key (and (match-end 2) (match-string 2 x))
5269 log1 (and (match-end 3) (match-string 3 x))
5270 log2 (and (match-end 4) (match-string 4 x)))
5271 (and (or log1 log2)
5272 (list kw
5273 (and log1 (if (equal log1 "!") 'time 'note))
5274 (and log2 (if (equal log2 "!") 'time 'note)))))))
5276 (defun org-remove-keyword-keys (list)
5277 "Remove a pair of parenthesis at the end of each string in LIST."
5278 (mapcar (lambda (x)
5279 (if (string-match "(.*)$" x)
5280 (substring x 0 (match-beginning 0))
5282 list))
5284 (defun org-assign-fast-keys (alist)
5285 "Assign fast keys to a keyword-key alist.
5286 Respect keys that are already there."
5287 (let (new e (alt ?0))
5288 (while (setq e (pop alist))
5289 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5290 (cdr e)) ;; Key already assigned.
5291 (push e new)
5292 (let ((clist (string-to-list (downcase (car e))))
5293 (used (append new alist)))
5294 (when (= (car clist) ?@)
5295 (pop clist))
5296 (while (and clist (rassoc (car clist) used))
5297 (pop clist))
5298 (unless clist
5299 (while (rassoc alt used)
5300 (incf alt)))
5301 (push (cons (car e) (or (car clist) alt)) new))))
5302 (nreverse new)))
5304 ;;; Some variables used in various places
5306 (defvar org-window-configuration nil
5307 "Used in various places to store a window configuration.")
5308 (defvar org-selected-window nil
5309 "Used in various places to store a window configuration.")
5310 (defvar org-finish-function nil
5311 "Function to be called when `C-c C-c' is used.
5312 This is for getting out of special buffers like capture.")
5315 ;; FIXME: Occasionally check by commenting these, to make sure
5316 ;; no other functions uses these, forgetting to let-bind them.
5317 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5318 (defvar org-last-state)
5319 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5321 ;; Defined somewhere in this file, but used before definition.
5322 (defvar org-entities) ;; defined in org-entities.el
5323 (defvar org-struct-menu)
5324 (defvar org-org-menu)
5325 (defvar org-tbl-menu)
5327 ;;;; Define the Org-mode
5329 ;; We use a before-change function to check if a table might need
5330 ;; an update.
5331 (defvar org-table-may-need-update t
5332 "Indicates that a table might need an update.
5333 This variable is set by `org-before-change-function'.
5334 `org-table-align' sets it back to nil.")
5335 (defun org-before-change-function (beg end)
5336 "Every change indicates that a table might need an update."
5337 (setq org-table-may-need-update t))
5338 (defvar org-mode-map)
5339 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5340 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5341 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5342 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5343 (defvar org-table-buffer-is-an nil)
5345 (defvar bidi-paragraph-direction)
5346 (defvar buffer-face-mode-face)
5348 (require 'outline)
5349 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5350 (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"))
5351 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5353 ;; Other stuff we need.
5354 (require 'time-date)
5355 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5356 (require 'easymenu)
5357 (require 'overlay)
5359 ;; (require 'org-macs) moved higher up in the file before it is first used
5360 (require 'org-entities)
5361 ;; (require 'org-compat) moved higher up in the file before it is first used
5362 (require 'org-faces)
5363 (require 'org-list)
5364 (require 'org-pcomplete)
5365 (require 'org-src)
5366 (require 'org-footnote)
5367 (require 'org-macro)
5369 ;; babel
5370 (require 'ob)
5372 ;;;###autoload
5373 (define-derived-mode org-mode outline-mode "Org"
5374 "Outline-based notes management and organizer, alias
5375 \"Carsten's outline-mode for keeping track of everything.\"
5377 Org-mode develops organizational tasks around a NOTES file which
5378 contains information about projects as plain text. Org-mode is
5379 implemented on top of outline-mode, which is ideal to keep the content
5380 of large files well structured. It supports ToDo items, deadlines and
5381 time stamps, which magically appear in the diary listing of the Emacs
5382 calendar. Tables are easily created with a built-in table editor.
5383 Plain text URL-like links connect to websites, emails (VM), Usenet
5384 messages (Gnus), BBDB entries, and any files related to the project.
5385 For printing and sharing of notes, an Org-mode file (or a part of it)
5386 can be exported as a structured ASCII or HTML file.
5388 The following commands are available:
5390 \\{org-mode-map}"
5392 ;; Get rid of Outline menus, they are not needed
5393 ;; Need to do this here because define-derived-mode sets up
5394 ;; the keymap so late. Still, it is a waste to call this each time
5395 ;; we switch another buffer into org-mode.
5396 (if (featurep 'xemacs)
5397 (when (boundp 'outline-mode-menu-heading)
5398 ;; Assume this is Greg's port, it uses easymenu
5399 (easy-menu-remove outline-mode-menu-heading)
5400 (easy-menu-remove outline-mode-menu-show)
5401 (easy-menu-remove outline-mode-menu-hide))
5402 (define-key org-mode-map [menu-bar headings] 'undefined)
5403 (define-key org-mode-map [menu-bar hide] 'undefined)
5404 (define-key org-mode-map [menu-bar show] 'undefined))
5406 (org-load-modules-maybe)
5407 (easy-menu-add org-org-menu)
5408 (easy-menu-add org-tbl-menu)
5409 (org-install-agenda-files-menu)
5410 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5411 (add-to-invisibility-spec '(org-cwidth))
5412 (add-to-invisibility-spec '(org-hide-block . t))
5413 (when (featurep 'xemacs)
5414 (org-set-local 'line-move-ignore-invisible t))
5415 (org-set-local 'outline-regexp org-outline-regexp)
5416 (org-set-local 'outline-level 'org-outline-level)
5417 (setq bidi-paragraph-direction 'left-to-right)
5418 (when (and org-ellipsis
5419 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5420 (fboundp 'make-glyph-code))
5421 (unless org-display-table
5422 (setq org-display-table (make-display-table)))
5423 (set-display-table-slot
5424 org-display-table 4
5425 (vconcat (mapcar
5426 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5427 org-ellipsis)))
5428 (if (stringp org-ellipsis) org-ellipsis "..."))))
5429 (setq buffer-display-table org-display-table))
5430 (org-set-regexps-and-options-for-tags)
5431 (org-set-regexps-and-options)
5432 (org-set-font-lock-defaults)
5433 (when (and org-tag-faces (not org-tags-special-faces-re))
5434 ;; tag faces set outside customize.... force initialization.
5435 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5436 ;; Calc embedded
5437 (org-set-local 'calc-embedded-open-mode "# ")
5438 ;; Modify a few syntax entries
5439 (modify-syntax-entry ?@ "w")
5440 (modify-syntax-entry ?\" "\"")
5441 (modify-syntax-entry ?\\ "_")
5442 (modify-syntax-entry ?~ "_")
5443 (if org-startup-truncated (setq truncate-lines t))
5444 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5445 (org-set-local 'font-lock-unfontify-region-function
5446 'org-unfontify-region)
5447 ;; Activate before-change-function
5448 (org-set-local 'org-table-may-need-update t)
5449 (org-add-hook 'before-change-functions 'org-before-change-function nil
5450 'local)
5451 ;; Check for running clock before killing a buffer
5452 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5453 ;; Initialize macros templates.
5454 (org-macro-initialize-templates)
5455 ;; Initialize radio targets.
5456 (org-update-radio-target-regexp)
5457 ;; Indentation.
5458 (org-set-local 'indent-line-function 'org-indent-line)
5459 (org-set-local 'indent-region-function 'org-indent-region)
5460 ;; Filling and auto-filling.
5461 (org-setup-filling)
5462 ;; Comments.
5463 (org-setup-comments-handling)
5464 ;; Initialize cache.
5465 (org-element-cache-reset)
5466 ;; Beginning/end of defun
5467 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5468 (org-set-local 'end-of-defun-function
5469 (lambda ()
5470 (if (not (org-at-heading-p))
5471 (org-forward-element)
5472 (org-forward-element)
5473 (forward-char -1))))
5474 ;; Next error for sparse trees
5475 (org-set-local 'next-error-function 'org-occur-next-match)
5476 ;; Make sure dependence stuff works reliably, even for users who set it
5477 ;; too late :-(
5478 (if org-enforce-todo-dependencies
5479 (add-hook 'org-blocker-hook
5480 'org-block-todo-from-children-or-siblings-or-parent)
5481 (remove-hook 'org-blocker-hook
5482 'org-block-todo-from-children-or-siblings-or-parent))
5483 (if org-enforce-todo-checkbox-dependencies
5484 (add-hook 'org-blocker-hook
5485 'org-block-todo-from-checkboxes)
5486 (remove-hook 'org-blocker-hook
5487 'org-block-todo-from-checkboxes))
5489 ;; Align options lines
5490 (org-set-local
5491 'align-mode-rules-list
5492 '((org-in-buffer-settings
5493 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5494 (modes . '(org-mode)))))
5496 ;; Imenu
5497 (org-set-local 'imenu-create-index-function
5498 'org-imenu-get-tree)
5500 ;; Make isearch reveal context
5501 (if (or (featurep 'xemacs)
5502 (not (boundp 'outline-isearch-open-invisible-function)))
5503 ;; Emacs 21 and XEmacs make use of the hook
5504 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5505 ;; Emacs 22 deals with this through a special variable
5506 (org-set-local 'outline-isearch-open-invisible-function
5507 (lambda (&rest ignore) (org-show-context 'isearch))))
5509 ;; Setup the pcomplete hooks
5510 (set (make-local-variable 'pcomplete-command-completion-function)
5511 'org-pcomplete-initial)
5512 (set (make-local-variable 'pcomplete-command-name-function)
5513 'org-command-at-point)
5514 (set (make-local-variable 'pcomplete-default-completion-function)
5515 'ignore)
5516 (set (make-local-variable 'pcomplete-parse-arguments-function)
5517 'org-parse-arguments)
5518 (set (make-local-variable 'pcomplete-termination-string) "")
5519 (when (>= emacs-major-version 23)
5520 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5522 ;; If empty file that did not turn on org-mode automatically, make it to.
5523 (if (and org-insert-mode-line-in-empty-file
5524 (org-called-interactively-p 'any)
5525 (= (point-min) (point-max)))
5526 (insert "# -*- mode: org -*-\n\n"))
5527 (unless org-inhibit-startup
5528 (org-unmodified
5529 (and org-startup-with-beamer-mode (org-beamer-mode))
5530 (when org-startup-align-all-tables
5531 (org-table-map-tables 'org-table-align 'quietly))
5532 (when org-startup-with-inline-images
5533 (org-display-inline-images))
5534 (when org-startup-with-latex-preview
5535 (org-toggle-latex-fragment))
5536 (unless org-inhibit-startup-visibility-stuff
5537 (org-set-startup-visibility))
5538 (org-refresh-effort-properties)))
5539 ;; Try to set org-hide correctly
5540 (let ((foreground (org-find-invisible-foreground)))
5541 (if foreground
5542 (set-face-foreground 'org-hide foreground))))
5544 ;; Update `customize-package-emacs-version-alist'
5545 (add-to-list 'customize-package-emacs-version-alist
5546 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5547 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5548 ("8.2.6" . "24.4")))
5550 (defvar org-mode-transpose-word-syntax-table
5551 (let ((st (make-syntax-table)))
5552 (mapc (lambda(c) (modify-syntax-entry
5553 (string-to-char (car c)) "w p" st))
5554 org-emphasis-alist)
5555 st))
5557 (when (fboundp 'abbrev-table-put)
5558 (abbrev-table-put org-mode-abbrev-table
5559 :parents (list text-mode-abbrev-table)))
5561 (defun org-find-invisible-foreground ()
5562 (let ((candidates (remove
5563 "unspecified-bg"
5564 (nconc
5565 (list (face-background 'default)
5566 (face-background 'org-default))
5567 (mapcar
5568 (lambda (alist)
5569 (when (boundp alist)
5570 (cdr (assoc 'background-color (symbol-value alist)))))
5571 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5572 (list (face-foreground 'org-hide))))))
5573 (car (remove nil candidates))))
5575 (defun org-current-time (&optional rounding-minutes past)
5576 "Current time, possibly rounded to ROUNDING-MINUTES.
5577 When ROUNDING-MINUTES is not an integer, fall back on the car of
5578 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5579 the rounding returns a past time."
5580 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5581 (car org-time-stamp-rounding-minutes)))
5582 (time (decode-time)) res)
5583 (if (< r 1)
5584 (current-time)
5585 (setq res
5586 (apply 'encode-time
5587 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5588 (nthcdr 2 time))))
5589 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5590 (seconds-to-time (- (org-float-time res) (* r 60)))
5591 res))))
5593 (defun org-today ()
5594 "Return today date, considering `org-extend-today-until'."
5595 (time-to-days
5596 (time-subtract (current-time)
5597 (list 0 (* 3600 org-extend-today-until) 0))))
5599 ;;;; Font-Lock stuff, including the activators
5601 (defvar org-mouse-map (make-sparse-keymap))
5602 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5603 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5604 (when org-mouse-1-follows-link
5605 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5606 (when org-tab-follows-link
5607 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5608 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5610 (require 'font-lock)
5612 (defconst org-non-link-chars "]\t\n\r<>")
5613 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5614 "file+sys" "news" "shell" "elisp" "doi" "message"
5615 "help"))
5616 (defvar org-link-types-re nil
5617 "Matches a link that has a url-like prefix like \"http:\"")
5618 (defvar org-link-re-with-space nil
5619 "Matches a link with spaces, optional angular brackets around it.")
5620 (defvar org-link-re-with-space2 nil
5621 "Matches a link with spaces, optional angular brackets around it.")
5622 (defvar org-link-re-with-space3 nil
5623 "Matches a link with spaces, only for internal part in bracket links.")
5624 (defvar org-angle-link-re nil
5625 "Matches link with angular brackets, spaces are allowed.")
5626 (defvar org-plain-link-re nil
5627 "Matches plain link, without spaces.")
5628 (defvar org-bracket-link-regexp nil
5629 "Matches a link in double brackets.")
5630 (defvar org-bracket-link-analytic-regexp nil
5631 "Regular expression used to analyze links.
5632 Here is what the match groups contain after a match:
5633 1: http:
5634 2: http
5635 3: path
5636 4: [desc]
5637 5: desc")
5638 (defvar org-bracket-link-analytic-regexp++ nil
5639 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5640 (defvar org-any-link-re nil
5641 "Regular expression matching any link.")
5643 (defconst org-match-sexp-depth 3
5644 "Number of stacked braces for sub/superscript matching.")
5646 (defun org-create-multibrace-regexp (left right n)
5647 "Create a regular expression which will match a balanced sexp.
5648 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5649 as single character strings.
5650 The regexp returned will match the entire expression including the
5651 delimiters. It will also define a single group which contains the
5652 match except for the outermost delimiters. The maximum depth of
5653 stacked delimiters is N. Escaping delimiters is not possible."
5654 (let* ((nothing (concat "[^" left right "]*?"))
5655 (or "\\|")
5656 (re nothing)
5657 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5658 (while (> n 1)
5659 (setq n (1- n)
5660 re (concat re or next)
5661 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5662 (concat left "\\(" re "\\)" right)))
5664 (defconst org-match-substring-regexp
5665 (concat
5666 "\\(\\S-\\)\\([_^]\\)\\("
5667 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5668 "\\|"
5669 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5670 "\\|"
5671 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5672 "The regular expression matching a sub- or superscript.")
5674 (defconst org-match-substring-with-braces-regexp
5675 (concat
5676 "\\(\\S-\\)\\([_^]\\)"
5677 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5678 "The regular expression matching a sub- or superscript, forcing braces.")
5680 (defun org-make-link-regexps ()
5681 "Update the link regular expressions.
5682 This should be called after the variable `org-link-types' has changed."
5683 (let ((types-re (regexp-opt org-link-types t)))
5684 (setq org-link-types-re
5685 (concat "\\`" types-re ":")
5686 org-link-re-with-space
5687 (concat "<?" types-re ":"
5688 "\\([^" org-non-link-chars " ]"
5689 "[^" org-non-link-chars "]*"
5690 "[^" org-non-link-chars " ]\\)>?")
5691 org-link-re-with-space2
5692 (concat "<?" types-re ":"
5693 "\\([^" org-non-link-chars " ]"
5694 "[^\t\n\r]*"
5695 "[^" org-non-link-chars " ]\\)>?")
5696 org-link-re-with-space3
5697 (concat "<?" types-re ":"
5698 "\\([^" org-non-link-chars " ]"
5699 "[^\t\n\r]*\\)")
5700 org-angle-link-re
5701 (concat "<" types-re ":"
5702 "\\([^" org-non-link-chars " ]"
5703 "[^" org-non-link-chars "]*"
5704 "\\)>")
5705 org-plain-link-re
5706 (concat
5707 "\\<" types-re ":"
5708 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5709 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5710 org-bracket-link-regexp
5711 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5712 org-bracket-link-analytic-regexp
5713 (concat
5714 "\\[\\["
5715 "\\(" types-re ":\\)?"
5716 "\\([^]]+\\)"
5717 "\\]"
5718 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5719 "\\]")
5720 org-bracket-link-analytic-regexp++
5721 (concat
5722 "\\[\\["
5723 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5724 "\\([^]]+\\)"
5725 "\\]"
5726 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5727 "\\]")
5728 org-any-link-re
5729 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5730 org-angle-link-re "\\)\\|\\("
5731 org-plain-link-re "\\)"))))
5733 (org-make-link-regexps)
5735 (defvar org-emph-face nil)
5737 (defun org-do-emphasis-faces (limit)
5738 "Run through the buffer and emphasize strings."
5739 (let (rtn a)
5740 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5741 (let* ((border (char-after (match-beginning 3)))
5742 (bre (regexp-quote (char-to-string border))))
5743 (if (and (not (= border (char-after (match-beginning 4))))
5744 (not (save-match-data
5745 (string-match (concat bre ".*" bre)
5746 (replace-regexp-in-string
5747 "\n" " "
5748 (substring (match-string 2) 1 -1))))))
5749 (progn
5750 (setq rtn t)
5751 (setq a (assoc (match-string 3) org-emphasis-alist))
5752 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5753 'face
5754 (nth 1 a))
5755 (and (nth 2 a)
5756 (org-remove-flyspell-overlays-in
5757 (match-beginning 0) (match-end 0)))
5758 (add-text-properties (match-beginning 2) (match-end 2)
5759 '(font-lock-multiline t org-emphasis t))
5760 (when org-hide-emphasis-markers
5761 (add-text-properties (match-end 4) (match-beginning 5)
5762 '(invisible org-link))
5763 (add-text-properties (match-beginning 3) (match-end 3)
5764 '(invisible org-link))))))
5765 (goto-char (1+ (match-beginning 0))))
5766 rtn))
5768 (defun org-emphasize (&optional char)
5769 "Insert or change an emphasis, i.e. a font like bold or italic.
5770 If there is an active region, change that region to a new emphasis.
5771 If there is no region, just insert the marker characters and position
5772 the cursor between them.
5773 CHAR should be the marker character. If it is a space, it means to
5774 remove the emphasis of the selected region.
5775 If CHAR is not given (for example in an interactive call) it will be
5776 prompted for."
5777 (interactive)
5778 (let ((erc org-emphasis-regexp-components)
5779 (prompt "")
5780 (string "") beg end move c s)
5781 (if (org-region-active-p)
5782 (setq beg (region-beginning) end (region-end)
5783 string (buffer-substring beg end))
5784 (setq move t))
5786 (unless char
5787 (message "Emphasis marker or tag: [%s]"
5788 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5789 (setq char (read-char-exclusive)))
5790 (if (equal char ?\ )
5791 (setq s "" move nil)
5792 (unless (assoc (char-to-string char) org-emphasis-alist)
5793 (user-error "No such emphasis marker: \"%c\"" char))
5794 (setq s (char-to-string char)))
5795 (while (and (> (length string) 1)
5796 (equal (substring string 0 1) (substring string -1))
5797 (assoc (substring string 0 1) org-emphasis-alist))
5798 (setq string (substring string 1 -1)))
5799 (setq string (concat s string s))
5800 (if beg (delete-region beg end))
5801 (unless (or (bolp)
5802 (string-match (concat "[" (nth 0 erc) "\n]")
5803 (char-to-string (char-before (point)))))
5804 (insert " "))
5805 (unless (or (eobp)
5806 (string-match (concat "[" (nth 1 erc) "\n]")
5807 (char-to-string (char-after (point)))))
5808 (insert " ") (backward-char 1))
5809 (insert string)
5810 (and move (backward-char 1))))
5812 (defconst org-nonsticky-props
5813 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5815 (defsubst org-rear-nonsticky-at (pos)
5816 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5818 (defun org-activate-plain-links (limit)
5819 "Add link properties for plain links."
5820 (let (f hl)
5821 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5822 (not (member 'org-tag
5823 (get-text-property (1- (match-beginning 0)) 'face)))
5824 (not (org-in-src-block-p)))
5825 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5826 (setq f (get-text-property (match-beginning 0) 'face))
5827 (setq hl (org-match-string-no-properties 0))
5828 (if (or (eq f 'org-tag)
5829 (and (listp f) (memq 'org-tag f)))
5831 (add-text-properties (match-beginning 0) (match-end 0)
5832 (list 'mouse-face 'highlight
5833 'face 'org-link
5834 'htmlize-link `(:uri ,hl)
5835 'keymap org-mouse-map))
5836 (org-rear-nonsticky-at (match-end 0)))
5837 t)))
5839 (defun org-activate-code (limit)
5840 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5841 (progn
5842 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5843 (remove-text-properties (match-beginning 0) (match-end 0)
5844 '(display t invisible t intangible t))
5845 t)))
5847 (defcustom org-src-fontify-natively t
5848 "When non-nil, fontify code in code blocks."
5849 :type 'boolean
5850 :version "24.4"
5851 :package-version '(Org . "8.3")
5852 :group 'org-appearance
5853 :group 'org-babel)
5855 (defcustom org-allow-promoting-top-level-subtree nil
5856 "When non-nil, allow promoting a top level subtree.
5857 The leading star of the top level headline will be replaced
5858 by a #."
5859 :type 'boolean
5860 :version "24.1"
5861 :group 'org-appearance)
5863 (defun org-fontify-meta-lines-and-blocks (limit)
5864 (condition-case nil
5865 (org-fontify-meta-lines-and-blocks-1 limit)
5866 (error (message "org-mode fontification error"))))
5868 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5869 "Fontify #+ lines and blocks."
5870 (let ((case-fold-search t))
5871 (if (re-search-forward
5872 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5873 limit t)
5874 (let ((beg (match-beginning 0))
5875 (block-start (match-end 0))
5876 (block-end nil)
5877 (lang (match-string 7))
5878 (beg1 (line-beginning-position 2))
5879 (dc1 (downcase (match-string 2)))
5880 (dc3 (downcase (match-string 3)))
5881 end end1 quoting block-type ovl)
5882 (cond
5883 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5884 ;; a single line of backend-specific content
5885 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5886 (remove-text-properties (match-beginning 0) (match-end 0)
5887 '(display t invisible t intangible t))
5888 (add-text-properties (match-beginning 1) (match-end 3)
5889 '(font-lock-fontified t face org-meta-line))
5890 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5891 '(font-lock-fontified t face org-block))
5892 ; for backend-specific code
5894 ((and (match-end 4) (equal dc3 "+begin"))
5895 ;; Truly a block
5896 (setq block-type (downcase (match-string 5))
5897 quoting (member block-type org-protecting-blocks))
5898 (when (re-search-forward
5899 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5900 nil t) ;; on purpose, we look further than LIMIT
5901 (setq end (min (point-max) (match-end 0))
5902 end1 (min (point-max) (1- (match-beginning 0))))
5903 (setq block-end (match-beginning 0))
5904 (when quoting
5905 (org-remove-flyspell-overlays-in beg1 end1)
5906 (remove-text-properties beg end
5907 '(display t invisible t intangible t)))
5908 (add-text-properties
5909 beg end '(font-lock-fontified t font-lock-multiline t))
5910 (add-text-properties beg beg1 '(face org-meta-line))
5911 (org-remove-flyspell-overlays-in beg beg1)
5912 (add-text-properties ; For end_src
5913 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5914 (org-remove-flyspell-overlays-in end1 end)
5915 (cond
5916 ((and lang (not (string= lang "")) org-src-fontify-natively)
5917 (org-src-font-lock-fontify-block lang block-start block-end)
5918 (add-text-properties beg1 block-end '(src-block t)))
5919 (quoting
5920 (add-text-properties beg1 (min (point-max) (1+ end1))
5921 '(face org-block))) ; end of source block
5922 ((not org-fontify-quote-and-verse-blocks))
5923 ((string= block-type "quote")
5924 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5925 ((string= block-type "verse")
5926 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5927 (add-text-properties beg beg1 '(face org-block-begin-line))
5928 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5929 '(face org-block-end-line))
5931 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5932 (org-remove-flyspell-overlays-in
5933 (match-beginning 0)
5934 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5935 (add-text-properties
5936 beg (match-end 3)
5937 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5938 '(font-lock-fontified t invisible t)
5939 '(font-lock-fontified t face org-document-info-keyword)))
5940 (add-text-properties
5941 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5942 (if (string-equal dc1 "+title:")
5943 '(font-lock-fontified t face org-document-title)
5944 '(font-lock-fontified t face org-document-info))))
5945 ((or (equal dc1 "+results")
5946 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5947 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5948 "+call:" "+header:" "+headers:" "+name:"))
5949 (and (match-end 4) (equal dc3 "+attr")))
5950 (org-remove-flyspell-overlays-in
5951 (match-beginning 0)
5952 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5953 (add-text-properties
5954 beg (match-end 0)
5955 '(font-lock-fontified t face org-meta-line))
5957 ((member dc3 '(" " ""))
5958 (org-remove-flyspell-overlays-in beg (match-end 0))
5959 (add-text-properties
5960 beg (match-end 0)
5961 '(font-lock-fontified t face font-lock-comment-face)))
5962 (t ;; just any other in-buffer setting, but not indented
5963 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5964 (add-text-properties
5965 beg (match-end 0)
5966 '(font-lock-fontified t face org-meta-line))
5967 t))))))
5969 (defun org-fontify-drawers (limit)
5970 "Fontify drawers."
5971 (when (re-search-forward org-drawer-regexp limit t)
5972 (add-text-properties
5973 (match-beginning 0) (match-end 0)
5974 '(font-lock-fontified t face org-special-keyword))
5975 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5978 (defun org-fontify-macros (limit)
5979 "Fontify macros."
5980 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5981 (add-text-properties
5982 (match-beginning 0) (match-end 0)
5983 '(font-lock-fontified t face org-macro))
5984 (when org-hide-macro-markers
5985 (add-text-properties (match-end 2) (match-beginning 2)
5986 '(invisible t))
5987 (add-text-properties (match-beginning 1) (match-end 1)
5988 '(invisible t)))
5989 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5992 (defun org-activate-angle-links (limit)
5993 "Add text properties for angle links."
5994 (if (and (re-search-forward org-angle-link-re limit t)
5995 (not (org-in-src-block-p)))
5996 (progn
5997 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5998 (add-text-properties (match-beginning 0) (match-end 0)
5999 (list 'mouse-face 'highlight
6000 'keymap org-mouse-map))
6001 (org-rear-nonsticky-at (match-end 0))
6002 t)))
6004 (defun org-activate-footnote-links (limit)
6005 "Add text properties for footnotes."
6006 (let ((fn (org-footnote-next-reference-or-definition limit)))
6007 (when fn
6008 (let* ((beg (nth 1 fn))
6009 (end (nth 2 fn))
6010 (label (car fn))
6011 (referencep (/= (line-beginning-position) beg)))
6012 (when (and referencep (nth 3 fn))
6013 (save-excursion
6014 (goto-char beg)
6015 (search-forward (or label "fn:"))
6016 (org-remove-flyspell-overlays-in beg (match-end 0))))
6017 (add-text-properties beg end
6018 (list 'mouse-face 'highlight
6019 'keymap org-mouse-map
6020 'help-echo
6021 (if referencep "Footnote reference"
6022 "Footnote definition")
6023 'font-lock-fontified t
6024 'font-lock-multiline t
6025 'face 'org-footnote))))))
6027 (defun org-activate-bracket-links (limit)
6028 "Add text properties for bracketed links."
6029 (if (and (re-search-forward org-bracket-link-regexp limit t)
6030 (not (org-in-src-block-p)))
6031 (let* ((hl (org-match-string-no-properties 1))
6032 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6033 (ip (org-maybe-intangible
6034 (list 'invisible 'org-link
6035 'keymap org-mouse-map 'mouse-face 'highlight
6036 'font-lock-multiline t 'help-echo help
6037 'htmlize-link `(:uri ,hl))))
6038 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6039 'font-lock-multiline t 'help-echo help
6040 'htmlize-link `(:uri ,hl))))
6041 ;; We need to remove the invisible property here. Table narrowing
6042 ;; may have made some of this invisible.
6043 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6044 (remove-text-properties (match-beginning 0) (match-end 0)
6045 '(invisible nil))
6046 (if (match-end 3)
6047 (progn
6048 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6049 (org-rear-nonsticky-at (match-beginning 3))
6050 (add-text-properties (match-beginning 3) (match-end 3) vp)
6051 (org-rear-nonsticky-at (match-end 3))
6052 (add-text-properties (match-end 3) (match-end 0) ip)
6053 (org-rear-nonsticky-at (match-end 0)))
6054 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6055 (org-rear-nonsticky-at (match-beginning 1))
6056 (add-text-properties (match-beginning 1) (match-end 1) vp)
6057 (org-rear-nonsticky-at (match-end 1))
6058 (add-text-properties (match-end 1) (match-end 0) ip)
6059 (org-rear-nonsticky-at (match-end 0)))
6060 t)))
6062 (defun org-activate-dates (limit)
6063 "Add text properties for dates."
6064 (if (and (re-search-forward org-tsr-regexp-both limit t)
6065 (not (equal (char-before (match-beginning 0)) 91)))
6066 (progn
6067 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6068 (add-text-properties (match-beginning 0) (match-end 0)
6069 (list 'mouse-face 'highlight
6070 'keymap org-mouse-map))
6071 (org-rear-nonsticky-at (match-end 0))
6072 (when org-display-custom-times
6073 (if (match-end 3)
6074 (org-display-custom-time (match-beginning 3) (match-end 3)))
6075 (org-display-custom-time (match-beginning 1) (match-end 1)))
6076 t)))
6078 (defvar org-target-link-regexp nil
6079 "Regular expression matching radio targets in plain text.")
6080 (make-variable-buffer-local 'org-target-link-regexp)
6082 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6083 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6084 border border border))
6085 "Regular expression matching a link target.")
6087 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6088 "Regular expression matching a radio target.")
6090 (defconst org-any-target-regexp
6091 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6092 "Regular expression matching any target.")
6094 (defun org-activate-target-links (limit)
6095 "Add text properties for target matches."
6096 (when org-target-link-regexp
6097 (let ((case-fold-search t))
6098 (if (re-search-forward org-target-link-regexp limit t)
6099 (progn
6100 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6101 (add-text-properties (match-beginning 1) (match-end 1)
6102 (list 'mouse-face 'highlight
6103 'keymap org-mouse-map
6104 'help-echo "Radio target link"
6105 'org-linked-text t))
6106 (org-rear-nonsticky-at (match-end 1))
6107 t)))))
6109 (defun org-update-radio-target-regexp ()
6110 "Find all radio targets in this file and update the regular expression.
6111 Also refresh fontification if needed."
6112 (interactive)
6113 (let ((old-regexp org-target-link-regexp)
6114 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6115 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6116 (targets
6117 (org-with-wide-buffer
6118 (goto-char (point-min))
6119 (let (rtn)
6120 (while (re-search-forward org-radio-target-regexp nil t)
6121 ;; Make sure point is really within the object.
6122 (backward-char)
6123 (let ((obj (org-element-context)))
6124 (when (eq (org-element-type obj) 'radio-target)
6125 (add-to-list 'rtn (org-element-property :value obj)))))
6126 rtn))))
6127 (setq org-target-link-regexp
6128 (and targets
6129 (concat before-re
6130 (mapconcat
6131 (lambda (x)
6132 (replace-regexp-in-string
6133 " +" "\\s-+" (regexp-quote x) t t))
6134 targets
6135 "\\|")
6136 after-re)))
6137 (unless (equal old-regexp org-target-link-regexp)
6138 ;; Clean-up cache.
6139 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6140 ((not org-target-link-regexp) old-regexp)
6142 (concat before-re
6143 (mapconcat
6144 (lambda (re)
6145 (substring re (length before-re)
6146 (- (length after-re))))
6147 (list old-regexp org-target-link-regexp)
6148 "\\|")
6149 after-re)))))
6150 (org-with-wide-buffer
6151 (goto-char (point-min))
6152 (while (re-search-forward regexp nil t)
6153 (org-element-cache-refresh (match-beginning 1)))))
6154 ;; Re fontify buffer.
6155 (when (memq 'radio org-highlight-links)
6156 (org-restart-font-lock)))))
6158 (defun org-hide-wide-columns (limit)
6159 (let (s e)
6160 (setq s (text-property-any (point) (or limit (point-max))
6161 'org-cwidth t))
6162 (when s
6163 (setq e (next-single-property-change s 'org-cwidth))
6164 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6165 (goto-char e)
6166 t)))
6168 (defvar org-latex-and-related-regexp nil
6169 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6171 (defun org-compute-latex-and-related-regexp ()
6172 "Compute regular expression for LaTeX, entities and sub/superscript.
6173 Result depends on variable `org-highlight-latex-and-related'."
6174 (org-set-local
6175 'org-latex-and-related-regexp
6176 (let* ((re-sub
6177 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6178 ((eq org-use-sub-superscripts '{})
6179 (list org-match-substring-with-braces-regexp))
6180 (org-use-sub-superscripts (list org-match-substring-regexp))))
6181 (re-latex
6182 (when (memq 'latex org-highlight-latex-and-related)
6183 (let ((matchers (plist-get org-format-latex-options :matchers)))
6184 (delq nil
6185 (mapcar (lambda (x)
6186 (and (member (car x) matchers) (nth 1 x)))
6187 org-latex-regexps)))))
6188 (re-entities
6189 (when (memq 'entities org-highlight-latex-and-related)
6190 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6191 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6193 (defun org-do-latex-and-related (limit)
6194 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6195 LIMIT bounds the search for syntax to highlight. Stop at first
6196 highlighted object, if any. Return t if some highlighting was
6197 done, nil otherwise."
6198 (when (org-string-nw-p org-latex-and-related-regexp)
6199 (catch 'found
6200 (while (re-search-forward org-latex-and-related-regexp limit t)
6201 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6202 'face))
6203 '(org-code org-verbatim underline))
6204 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6205 '(?_ ?^))
6207 0)))
6208 (font-lock-prepend-text-property
6209 (+ offset (match-beginning 0)) (match-end 0)
6210 'face 'org-latex-and-related)
6211 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6212 '(font-lock-multiline t)))
6213 (throw 'found t)))
6214 nil)))
6216 (defun org-restart-font-lock ()
6217 "Restart `font-lock-mode', to force refontification."
6218 (when (and (boundp 'font-lock-mode) font-lock-mode)
6219 (font-lock-mode -1)
6220 (font-lock-mode 1)))
6222 (defun org-activate-tags (limit)
6223 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6224 (progn
6225 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6226 (add-text-properties (match-beginning 1) (match-end 1)
6227 (list 'mouse-face 'highlight
6228 'keymap org-mouse-map))
6229 (org-rear-nonsticky-at (match-end 1))
6230 t)))
6232 (defun org-outline-level ()
6233 "Compute the outline level of the heading at point.
6234 If this is called at a normal headline, the level is the number of stars.
6235 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6236 (save-excursion
6237 (if (not (ignore-errors (org-back-to-heading t)))
6239 (looking-at org-outline-regexp)
6240 (1- (- (match-end 0) (match-beginning 0))))))
6242 (defvar org-font-lock-keywords nil)
6244 (defsubst org-re-property (property &optional literal allow-null)
6245 "Return a regexp matching a PROPERTY line.
6247 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6248 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6249 non-nil, match properties even without a value.
6251 Match group 3 is set to the value when it exists. If there is no
6252 value and ALLOW-NULL is non-nil, it is set to the empty string."
6253 (concat
6254 "^\\(?4:[ \t]*\\)"
6255 (format "\\(?1::\\(?2:%s\\):\\)"
6256 (if literal property (regexp-quote property)))
6257 (if allow-null
6258 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6259 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6261 (defconst org-property-re
6262 (org-re-property "\\S-+" 'literal t)
6263 "Regular expression matching a property line.
6264 There are four matching groups:
6265 1: :PROPKEY: including the leading and trailing colon,
6266 2: PROPKEY without the leading and trailing colon,
6267 3: PROPVAL without leading or trailing spaces,
6268 4: the indentation of the current line,
6269 5: trailing whitespace.")
6271 (defvar org-font-lock-hook nil
6272 "Functions to be called for special font lock stuff.")
6274 (defvar org-font-lock-set-keywords-hook nil
6275 "Functions that can manipulate `org-font-lock-extra-keywords'.
6276 This is called after `org-font-lock-extra-keywords' is defined, but before
6277 it is installed to be used by font lock. This can be useful if something
6278 needs to be inserted at a specific position in the font-lock sequence.")
6280 (defun org-font-lock-hook (limit)
6281 "Run `org-font-lock-hook' within LIMIT."
6282 (run-hook-with-args 'org-font-lock-hook limit))
6284 (defun org-set-font-lock-defaults ()
6285 "Set font lock defaults for the current buffer."
6286 (let* ((em org-fontify-emphasized-text)
6287 (lk org-highlight-links)
6288 (org-font-lock-extra-keywords
6289 (list
6290 ;; Call the hook
6291 '(org-font-lock-hook)
6292 ;; Headlines
6293 `(,(if org-fontify-whole-heading-line
6294 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6295 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6296 (1 (org-get-level-face 1))
6297 (2 (org-get-level-face 2))
6298 (3 (org-get-level-face 3)))
6299 ;; Table lines
6300 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6301 (1 'org-table t))
6302 ;; Table internals
6303 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6304 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6305 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6306 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6307 ;; Drawers
6308 '(org-fontify-drawers)
6309 ;; Properties
6310 (list org-property-re
6311 '(1 'org-special-keyword t)
6312 '(3 'org-property-value t))
6313 ;; Links
6314 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6315 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6316 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6317 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6318 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6319 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6320 (if (memq 'footnote lk) '(org-activate-footnote-links))
6321 ;; Targets.
6322 (list org-any-target-regexp '(0 'org-target t))
6323 ;; Diary sexps.
6324 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6325 ;; Macro
6326 '(org-fontify-macros)
6327 '(org-hide-wide-columns (0 nil append))
6328 ;; TODO keyword
6329 (list (format org-heading-keyword-regexp-format
6330 org-todo-regexp)
6331 '(2 (org-get-todo-face 2) t))
6332 ;; DONE
6333 (if org-fontify-done-headline
6334 (list (format org-heading-keyword-regexp-format
6335 (concat
6336 "\\(?:"
6337 (mapconcat 'regexp-quote org-done-keywords "\\|")
6338 "\\)"))
6339 '(2 'org-headline-done t))
6340 nil)
6341 ;; Priorities
6342 '(org-font-lock-add-priority-faces)
6343 ;; Tags
6344 '(org-font-lock-add-tag-faces)
6345 ;; Tags groups
6346 (if (and org-group-tags org-tag-groups-alist)
6347 (list (concat org-outline-regexp-bol ".+\\(:"
6348 (regexp-opt (mapcar 'car org-tag-groups-alist))
6349 ":\\).*$")
6350 '(1 'org-tag-group prepend)))
6351 ;; Special keywords
6352 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6353 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6354 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6355 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6356 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6357 ;; Emphasis
6358 (if em
6359 (if (featurep 'xemacs)
6360 '(org-do-emphasis-faces (0 nil append))
6361 '(org-do-emphasis-faces)))
6362 ;; Checkboxes
6363 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6364 1 'org-checkbox prepend)
6365 (if (cdr (assq 'checkbox org-list-automatic-rules))
6366 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6367 (0 (org-get-checkbox-statistics-face) t)))
6368 ;; Description list items
6369 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6370 1 'org-list-dt prepend)
6371 ;; ARCHIVEd headings
6372 (list (concat
6373 org-outline-regexp-bol
6374 "\\(.*:" org-archive-tag ":.*\\)")
6375 '(1 'org-archived prepend))
6376 ;; Specials
6377 '(org-do-latex-and-related)
6378 '(org-fontify-entities)
6379 '(org-raise-scripts)
6380 ;; Code
6381 '(org-activate-code (1 'org-code t))
6382 ;; COMMENT
6383 (list (format
6384 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6385 org-todo-regexp
6386 org-comment-string)
6387 '(9 'org-special-keyword t))
6388 ;; Blocks and meta lines
6389 '(org-fontify-meta-lines-and-blocks))))
6390 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6391 (run-hooks 'org-font-lock-set-keywords-hook)
6392 ;; Now set the full font-lock-keywords
6393 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6394 (org-set-local 'font-lock-defaults
6395 '(org-font-lock-keywords t nil nil backward-paragraph))
6396 (kill-local-variable 'font-lock-keywords) nil))
6398 (defun org-toggle-pretty-entities ()
6399 "Toggle the composition display of entities as UTF8 characters."
6400 (interactive)
6401 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6402 (org-restart-font-lock)
6403 (if org-pretty-entities
6404 (message "Entities are now displayed as UTF8 characters")
6405 (save-restriction
6406 (widen)
6407 (org-decompose-region (point-min) (point-max))
6408 (message "Entities are now displayed as plain text"))))
6410 (defvar org-custom-properties-overlays nil
6411 "List of overlays used for custom properties.")
6412 (make-variable-buffer-local 'org-custom-properties-overlays)
6414 (defun org-toggle-custom-properties-visibility ()
6415 "Display or hide properties in `org-custom-properties'."
6416 (interactive)
6417 (if org-custom-properties-overlays
6418 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6419 (setq org-custom-properties-overlays nil))
6420 (unless (not org-custom-properties)
6421 (save-excursion
6422 (save-restriction
6423 (widen)
6424 (goto-char (point-min))
6425 (while (re-search-forward org-property-re nil t)
6426 (mapc (lambda(p)
6427 (when (equal p (substring (match-string 1) 1 -1))
6428 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6429 (overlay-put o 'invisible t)
6430 (overlay-put o 'org-custom-property t)
6431 (push o org-custom-properties-overlays))))
6432 org-custom-properties)))))))
6434 (defun org-fontify-entities (limit)
6435 "Find an entity to fontify."
6436 (let (ee)
6437 (when org-pretty-entities
6438 (catch 'match
6439 (while (re-search-forward
6440 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6441 limit t)
6442 (if (and (not (org-at-comment-p))
6443 (setq ee (org-entity-get (match-string 1)))
6444 (= (length (nth 6 ee)) 1))
6445 (let*
6446 ((end (if (equal (match-string 2) "{}")
6447 (match-end 2)
6448 (match-end 1))))
6449 (add-text-properties
6450 (match-beginning 0) end
6451 (list 'font-lock-fontified t))
6452 (compose-region (match-beginning 0) end
6453 (nth 6 ee) nil)
6454 (backward-char 1)
6455 (throw 'match t))))
6456 nil))))
6458 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6459 "Fontify string S like in Org-mode."
6460 (with-temp-buffer
6461 (insert s)
6462 (let ((org-odd-levels-only odd-levels))
6463 (org-mode)
6464 (font-lock-ensure)
6465 (buffer-string))))
6467 (defvar org-m nil)
6468 (defvar org-l nil)
6469 (defvar org-f nil)
6470 (defun org-get-level-face (n)
6471 "Get the right face for match N in font-lock matching of headlines."
6472 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6473 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6474 (if org-cycle-level-faces
6475 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6476 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6477 (cond
6478 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6479 ((eq n 2) org-f)
6480 (t (if org-level-color-stars-only nil org-f))))
6483 (defun org-get-todo-face (kwd)
6484 "Get the right face for a TODO keyword KWD.
6485 If KWD is a number, get the corresponding match group."
6486 (if (numberp kwd) (setq kwd (match-string kwd)))
6487 (or (org-face-from-face-or-color
6488 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6489 (and (member kwd org-done-keywords) 'org-done)
6490 'org-todo))
6492 (defun org-face-from-face-or-color (context inherit face-or-color)
6493 "Create a face list that inherits INHERIT, but sets the foreground color.
6494 When FACE-OR-COLOR is not a string, just return it."
6495 (if (stringp face-or-color)
6496 (list :inherit inherit
6497 (cdr (assoc context org-faces-easy-properties))
6498 face-or-color)
6499 face-or-color))
6501 (defun org-font-lock-add-tag-faces (limit)
6502 "Add the special tag faces."
6503 (when (and org-tag-faces org-tags-special-faces-re)
6504 (while (re-search-forward org-tags-special-faces-re limit t)
6505 (add-text-properties (match-beginning 1) (match-end 1)
6506 (list 'face (org-get-tag-face 1)
6507 'font-lock-fontified t))
6508 (backward-char 1))))
6510 (defun org-font-lock-add-priority-faces (limit)
6511 "Add the special priority faces."
6512 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6513 (when (save-match-data (org-at-heading-p))
6514 (add-text-properties
6515 (match-beginning 0) (match-end 0)
6516 (list 'face (or (org-face-from-face-or-color
6517 'priority 'org-priority
6518 (cdr (assoc (char-after (match-beginning 1))
6519 org-priority-faces)))
6520 'org-priority)
6521 'font-lock-fontified t)))))
6523 (defun org-get-tag-face (kwd)
6524 "Get the right face for a TODO keyword KWD.
6525 If KWD is a number, get the corresponding match group."
6526 (if (numberp kwd) (setq kwd (match-string kwd)))
6527 (or (org-face-from-face-or-color
6528 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6529 'org-tag))
6531 (defun org-unfontify-region (beg end &optional maybe_loudly)
6532 "Remove fontification and activation overlays from links."
6533 (font-lock-default-unfontify-region beg end)
6534 (let* ((buffer-undo-list t)
6535 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6536 (inhibit-modification-hooks t)
6537 deactivate-mark buffer-file-name buffer-file-truename)
6538 (org-decompose-region beg end)
6539 (remove-text-properties beg end
6540 '(mouse-face t keymap t org-linked-text t
6541 invisible t intangible t
6542 org-emphasis t))
6543 (org-remove-font-lock-display-properties beg end)))
6545 (defconst org-script-display '(((raise -0.3) (height 0.7))
6546 ((raise 0.3) (height 0.7))
6547 ((raise -0.5))
6548 ((raise 0.5)))
6549 "Display properties for showing superscripts and subscripts.")
6551 (defun org-remove-font-lock-display-properties (beg end)
6552 "Remove specific display properties that have been added by font lock.
6553 The will remove the raise properties that are used to show superscripts
6554 and subscripts."
6555 (let (next prop)
6556 (while (< beg end)
6557 (setq next (next-single-property-change beg 'display nil end)
6558 prop (get-text-property beg 'display))
6559 (if (member prop org-script-display)
6560 (put-text-property beg next 'display nil))
6561 (setq beg next))))
6563 (defun org-raise-scripts (limit)
6564 "Add raise properties to sub/superscripts."
6565 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6566 (if (re-search-forward
6567 (if (eq org-use-sub-superscripts t)
6568 org-match-substring-regexp
6569 org-match-substring-with-braces-regexp)
6570 limit t)
6571 (let* ((pos (point)) table-p comment-p
6572 (mpos (match-beginning 3))
6573 (emph-p (get-text-property mpos 'org-emphasis))
6574 (link-p (get-text-property mpos 'mouse-face))
6575 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6576 (goto-char (point-at-bol))
6577 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6578 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6579 (goto-char pos)
6580 ;; Handle a_b^c
6581 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6582 (if (or comment-p emph-p link-p keyw-p)
6584 (put-text-property (match-beginning 3) (match-end 0)
6585 'display
6586 (if (equal (char-after (match-beginning 2)) ?^)
6587 (nth (if table-p 3 1) org-script-display)
6588 (nth (if table-p 2 0) org-script-display)))
6589 (add-text-properties (match-beginning 2) (match-end 2)
6590 (list 'invisible t
6591 'org-dwidth t 'org-dwidth-n 1))
6592 (if (and (eq (char-after (match-beginning 3)) ?{)
6593 (eq (char-before (match-end 3)) ?}))
6594 (progn
6595 (add-text-properties
6596 (match-beginning 3) (1+ (match-beginning 3))
6597 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6598 (add-text-properties
6599 (1- (match-end 3)) (match-end 3)
6600 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6601 t)))))
6603 ;;;; Visibility cycling, including org-goto and indirect buffer
6605 ;;; Cycling
6607 (defvar org-cycle-global-status nil)
6608 (make-variable-buffer-local 'org-cycle-global-status)
6609 (put 'org-cycle-global-status 'org-state t)
6610 (defvar org-cycle-subtree-status nil)
6611 (make-variable-buffer-local 'org-cycle-subtree-status)
6612 (put 'org-cycle-subtree-status 'org-state t)
6614 (defvar org-inlinetask-min-level)
6616 (defun org-unlogged-message (&rest args)
6617 "Display a message, but avoid logging it in the *Messages* buffer."
6618 (let ((message-log-max nil))
6619 (apply 'message args)))
6621 ;;;###autoload
6622 (defun org-cycle (&optional arg)
6623 "TAB-action and visibility cycling for Org-mode.
6625 This is the command invoked in Org-mode by the TAB key. Its main purpose
6626 is outline visibility cycling, but it also invokes other actions
6627 in special contexts.
6629 - When this function is called with a prefix argument, rotate the entire
6630 buffer through 3 states (global cycling)
6631 1. OVERVIEW: Show only top-level headlines.
6632 2. CONTENTS: Show all headlines of all levels, but no body text.
6633 3. SHOW ALL: Show everything.
6634 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6635 determined by the variable `org-startup-folded', and by any VISIBILITY
6636 properties in the buffer.
6637 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6638 including any drawers.
6640 - When inside a table, re-align the table and move to the next field.
6642 - When point is at the beginning of a headline, rotate the subtree started
6643 by this line through 3 different states (local cycling)
6644 1. FOLDED: Only the main headline is shown.
6645 2. CHILDREN: The main headline and the direct children are shown.
6646 From this state, you can move to one of the children
6647 and zoom in further.
6648 3. SUBTREE: Show the entire subtree, including body text.
6649 If there is no subtree, switch directly from CHILDREN to FOLDED.
6651 - When point is at the beginning of an empty headline and the variable
6652 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6653 of the headline by demoting and promoting it to likely levels. This
6654 speeds up creation document structure by pressing TAB once or several
6655 times right after creating a new headline.
6657 - When there is a numeric prefix, go up to a heading with level ARG, do
6658 a `show-subtree' and return to the previous cursor position. If ARG
6659 is negative, go up that many levels.
6661 - When point is not at the beginning of a headline, execute the global
6662 binding for TAB, which is re-indenting the line. See the option
6663 `org-cycle-emulate-tab' for details.
6665 - Special case: if point is at the beginning of the buffer and there is
6666 no headline in line 1, this function will act as if called with prefix arg
6667 (C-u TAB, same as S-TAB) also when called without prefix arg.
6668 But only if also the variable `org-cycle-global-at-bob' is t."
6669 (interactive "P")
6670 (org-load-modules-maybe)
6671 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6672 (and org-cycle-level-after-item/entry-creation
6673 (or (org-cycle-level)
6674 (org-cycle-item-indentation))))
6675 (let* ((limit-level
6676 (or org-cycle-max-level
6677 (and (boundp 'org-inlinetask-min-level)
6678 org-inlinetask-min-level
6679 (1- org-inlinetask-min-level))))
6680 (nstars (and limit-level
6681 (if org-odd-levels-only
6682 (and limit-level (1- (* limit-level 2)))
6683 limit-level)))
6684 (org-outline-regexp
6685 (if (not (derived-mode-p 'org-mode))
6686 outline-regexp
6687 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6688 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6689 (not (looking-at org-outline-regexp))))
6690 (org-cycle-hook
6691 (if bob-special
6692 (delq 'org-optimize-window-after-visibility-change
6693 (copy-sequence org-cycle-hook))
6694 org-cycle-hook))
6695 (pos (point)))
6697 (if (or bob-special (equal arg '(4)))
6698 ;; special case: use global cycling
6699 (setq arg t))
6701 (cond
6703 ((equal arg '(16))
6704 (setq last-command 'dummy)
6705 (org-set-startup-visibility)
6706 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6708 ((equal arg '(64))
6709 (show-all)
6710 (org-unlogged-message "Entire buffer visible, including drawers"))
6712 ;; Try cdlatex TAB completion
6713 ((org-try-cdlatex-tab))
6715 ;; Table: enter it or move to the next field.
6716 ((org-at-table-p 'any)
6717 (if (org-at-table.el-p)
6718 (message "Use C-c ' to edit table.el tables")
6719 (if arg (org-table-edit-field t)
6720 (org-table-justify-field-maybe)
6721 (call-interactively 'org-table-next-field))))
6723 ((run-hook-with-args-until-success
6724 'org-tab-after-check-for-table-hook))
6726 ;; Global cycling: delegate to `org-cycle-internal-global'.
6727 ((eq arg t) (org-cycle-internal-global))
6729 ;; Drawers: delegate to `org-flag-drawer'.
6730 ((save-excursion
6731 (beginning-of-line 1)
6732 (looking-at org-drawer-regexp))
6733 (org-flag-drawer ; toggle block visibility
6734 (not (get-char-property (match-end 0) 'invisible))))
6736 ;; Show-subtree, ARG levels up from here.
6737 ((integerp arg)
6738 (save-excursion
6739 (org-back-to-heading)
6740 (outline-up-heading (if (< arg 0) (- arg)
6741 (- (funcall outline-level) arg)))
6742 (org-show-subtree)))
6744 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6745 ((and (featurep 'org-inlinetask)
6746 (org-inlinetask-at-task-p)
6747 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6748 (org-inlinetask-toggle-visibility))
6750 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6751 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6752 (save-excursion (beginning-of-line 1)
6753 (looking-at org-outline-regexp)))
6754 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6755 (org-cycle-internal-local))
6757 ;; From there: TAB emulation and template completion.
6758 (buffer-read-only (org-back-to-heading))
6760 ((run-hook-with-args-until-success
6761 'org-tab-after-check-for-cycling-hook))
6763 ((org-try-structure-completion))
6765 ((run-hook-with-args-until-success
6766 'org-tab-before-tab-emulation-hook))
6768 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6769 (or (not (bolp))
6770 (not (looking-at org-outline-regexp))))
6771 (call-interactively (global-key-binding "\t")))
6773 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6774 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6775 (or (and (eq org-cycle-emulate-tab 'white)
6776 (= (match-end 0) (point-at-eol)))
6777 (and (eq org-cycle-emulate-tab 'whitestart)
6778 (>= (match-end 0) pos))))
6780 (eq org-cycle-emulate-tab t))
6781 (call-interactively (global-key-binding "\t")))
6783 (t (save-excursion
6784 (org-back-to-heading)
6785 (org-cycle)))))))
6787 (defun org-cycle-internal-global ()
6788 "Do the global cycling action."
6789 ;; Hack to avoid display of messages for .org attachments in Gnus
6790 (let ((ga (string-match "\\*fontification" (buffer-name))))
6791 (cond
6792 ((and (eq last-command this-command)
6793 (eq org-cycle-global-status 'overview))
6794 ;; We just created the overview - now do table of contents
6795 ;; This can be slow in very large buffers, so indicate action
6796 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6797 (unless ga (org-unlogged-message "CONTENTS..."))
6798 (org-content)
6799 (unless ga (org-unlogged-message "CONTENTS...done"))
6800 (setq org-cycle-global-status 'contents)
6801 (run-hook-with-args 'org-cycle-hook 'contents))
6803 ((and (eq last-command this-command)
6804 (eq org-cycle-global-status 'contents))
6805 ;; We just showed the table of contents - now show everything
6806 (run-hook-with-args 'org-pre-cycle-hook 'all)
6807 (show-all)
6808 (unless ga (org-unlogged-message "SHOW ALL"))
6809 (setq org-cycle-global-status 'all)
6810 (run-hook-with-args 'org-cycle-hook 'all))
6813 ;; Default action: go to overview
6814 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6815 (org-overview)
6816 (unless ga (org-unlogged-message "OVERVIEW"))
6817 (setq org-cycle-global-status 'overview)
6818 (run-hook-with-args 'org-cycle-hook 'overview)))))
6820 (defvar org-called-with-limited-levels nil
6821 "Non-nil when `org-with-limited-levels' is currently active.")
6823 (defun org-cycle-internal-local ()
6824 "Do the local cycling action."
6825 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6826 ;; First, determine end of headline (EOH), end of subtree or item
6827 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6828 (save-excursion
6829 (if (org-at-item-p)
6830 (progn
6831 (beginning-of-line)
6832 (setq struct (org-list-struct))
6833 (setq eoh (point-at-eol))
6834 (setq eos (org-list-get-item-end-before-blank (point) struct))
6835 (setq has-children (org-list-has-child-p (point) struct)))
6836 (org-back-to-heading)
6837 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6838 (setq eos (save-excursion (org-end-of-subtree t t)
6839 (when (bolp) (backward-char)) (point)))
6840 (setq has-children
6841 (or (save-excursion
6842 (let ((level (funcall outline-level)))
6843 (outline-next-heading)
6844 (and (org-at-heading-p t)
6845 (> (funcall outline-level) level))))
6846 (save-excursion
6847 (org-list-search-forward (org-item-beginning-re) eos t)))))
6848 ;; Determine end invisible part of buffer (EOL)
6849 (beginning-of-line 2)
6850 ;; XEmacs doesn't have `next-single-char-property-change'
6851 (if (featurep 'xemacs)
6852 (while (and (not (eobp)) ;; this is like `next-line'
6853 (get-char-property (1- (point)) 'invisible))
6854 (beginning-of-line 2))
6855 (while (and (not (eobp)) ;; this is like `next-line'
6856 (get-char-property (1- (point)) 'invisible))
6857 (goto-char (next-single-char-property-change (point) 'invisible))
6858 (and (eolp) (beginning-of-line 2))))
6859 (setq eol (point)))
6860 ;; Find out what to do next and set `this-command'
6861 (cond
6862 ((= eos eoh)
6863 ;; Nothing is hidden behind this heading
6864 (unless (org-before-first-heading-p)
6865 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6866 (org-unlogged-message "EMPTY ENTRY")
6867 (setq org-cycle-subtree-status nil)
6868 (save-excursion
6869 (goto-char eos)
6870 (outline-next-heading)
6871 (if (outline-invisible-p) (org-flag-heading nil))))
6872 ((and (or (>= eol eos)
6873 (not (string-match "\\S-" (buffer-substring eol eos))))
6874 (or has-children
6875 (not (setq children-skipped
6876 org-cycle-skip-children-state-if-no-children))))
6877 ;; Entire subtree is hidden in one line: children view
6878 (unless (org-before-first-heading-p)
6879 (run-hook-with-args 'org-pre-cycle-hook 'children))
6880 (if (org-at-item-p)
6881 (org-list-set-item-visibility (point-at-bol) struct 'children)
6882 (org-show-entry)
6883 (org-with-limited-levels (show-children))
6884 ;; FIXME: This slows down the func way too much.
6885 ;; How keep drawers hidden in subtree anyway?
6886 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6887 ;; (org-cycle-hide-drawers 'subtree))
6889 ;; Fold every list in subtree to top-level items.
6890 (when (eq org-cycle-include-plain-lists 'integrate)
6891 (save-excursion
6892 (org-back-to-heading)
6893 (while (org-list-search-forward (org-item-beginning-re) eos t)
6894 (beginning-of-line 1)
6895 (let* ((struct (org-list-struct))
6896 (prevs (org-list-prevs-alist struct))
6897 (end (org-list-get-bottom-point struct)))
6898 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6899 (org-list-get-all-items (point) struct prevs))
6900 (goto-char (if (< end eos) end eos)))))))
6901 (org-unlogged-message "CHILDREN")
6902 (save-excursion
6903 (goto-char eos)
6904 (outline-next-heading)
6905 (if (outline-invisible-p) (org-flag-heading nil)))
6906 (setq org-cycle-subtree-status 'children)
6907 (unless (org-before-first-heading-p)
6908 (run-hook-with-args 'org-cycle-hook 'children)))
6909 ((or children-skipped
6910 (and (eq last-command this-command)
6911 (eq org-cycle-subtree-status 'children)))
6912 ;; We just showed the children, or no children are there,
6913 ;; now show everything.
6914 (unless (org-before-first-heading-p)
6915 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6916 (outline-flag-region eoh eos nil)
6917 (org-unlogged-message
6918 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6919 (setq org-cycle-subtree-status 'subtree)
6920 (unless (org-before-first-heading-p)
6921 (run-hook-with-args 'org-cycle-hook 'subtree)))
6923 ;; Default action: hide the subtree.
6924 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6925 (outline-flag-region eoh eos t)
6926 (org-unlogged-message "FOLDED")
6927 (setq org-cycle-subtree-status 'folded)
6928 (unless (org-before-first-heading-p)
6929 (run-hook-with-args 'org-cycle-hook 'folded))))))
6931 ;;;###autoload
6932 (defun org-global-cycle (&optional arg)
6933 "Cycle the global visibility. For details see `org-cycle'.
6934 With \\[universal-argument] prefix arg, switch to startup visibility.
6935 With a numeric prefix, show all headlines up to that level."
6936 (interactive "P")
6937 (let ((org-cycle-include-plain-lists
6938 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6939 (cond
6940 ((integerp arg)
6941 (show-all)
6942 (hide-sublevels arg)
6943 (setq org-cycle-global-status 'contents))
6944 ((equal arg '(4))
6945 (org-set-startup-visibility)
6946 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6948 (org-cycle '(4))))))
6950 (defun org-set-startup-visibility ()
6951 "Set the visibility required by startup options and properties."
6952 (cond
6953 ((eq org-startup-folded t)
6954 (org-overview))
6955 ((eq org-startup-folded 'content)
6956 (org-content))
6957 ((or (eq org-startup-folded 'showeverything)
6958 (eq org-startup-folded nil))
6959 (show-all)))
6960 (unless (eq org-startup-folded 'showeverything)
6961 (if org-hide-block-startup (org-hide-block-all))
6962 (org-set-visibility-according-to-property 'no-cleanup)
6963 (org-cycle-hide-archived-subtrees 'all)
6964 (org-cycle-hide-drawers 'all)
6965 (org-cycle-show-empty-lines t)))
6967 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6968 "Switch subtree visibilities according to :VISIBILITY: property."
6969 (interactive)
6970 (let (org-show-entry-below state)
6971 (save-excursion
6972 (goto-char (point-min))
6973 (while (re-search-forward
6974 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6975 nil t)
6976 (setq state (match-string 1))
6977 (save-excursion
6978 (org-back-to-heading t)
6979 (hide-subtree)
6980 (org-reveal)
6981 (cond
6982 ((equal state '("fold" "folded"))
6983 (hide-subtree))
6984 ((equal state "children")
6985 (org-show-hidden-entry)
6986 (show-children))
6987 ((equal state "content")
6988 (save-excursion
6989 (save-restriction
6990 (org-narrow-to-subtree)
6991 (org-content))))
6992 ((member state '("all" "showall"))
6993 (show-subtree)))))
6994 (unless no-cleanup
6995 (org-cycle-hide-archived-subtrees 'all)
6996 (org-cycle-hide-drawers 'all)
6997 (org-cycle-show-empty-lines 'all)))))
6999 ;; This function uses outline-regexp instead of the more fundamental
7000 ;; org-outline-regexp so that org-cycle-global works outside of Org
7001 ;; buffers, where outline-regexp is needed.
7002 (defun org-overview ()
7003 "Switch to overview mode, showing only top-level headlines.
7004 This shows all headlines with a level equal or greater than the level
7005 of the first headline in the buffer. This is important, because if the
7006 first headline is not level one, then (hide-sublevels 1) gives confusing
7007 results."
7008 (interactive)
7009 (save-excursion
7010 (let ((level
7011 (save-excursion
7012 (goto-char (point-min))
7013 (if (re-search-forward (concat "^" outline-regexp) nil t)
7014 (progn
7015 (goto-char (match-beginning 0))
7016 (funcall outline-level))))))
7017 (and level (hide-sublevels level)))))
7019 (defun org-content (&optional arg)
7020 "Show all headlines in the buffer, like a table of contents.
7021 With numerical argument N, show content up to level N."
7022 (interactive "P")
7023 (org-overview)
7024 (save-excursion
7025 ;; Visit all headings and show their offspring
7026 (and (integerp arg) (org-overview))
7027 (goto-char (point-max))
7028 (catch 'exit
7029 (while (and (progn (condition-case nil
7030 (outline-previous-visible-heading 1)
7031 (error (goto-char (point-min))))
7033 (looking-at org-outline-regexp))
7034 (if (integerp arg)
7035 (show-children (1- arg))
7036 (show-branches))
7037 (if (bobp) (throw 'exit nil))))))
7039 (defun org-optimize-window-after-visibility-change (state)
7040 "Adjust the window after a change in outline visibility.
7041 This function is the default value of the hook `org-cycle-hook'."
7042 (when (get-buffer-window (current-buffer))
7043 (cond
7044 ((eq state 'content) nil)
7045 ((eq state 'all) nil)
7046 ((eq state 'folded) nil)
7047 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7048 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7050 (defun org-remove-empty-overlays-at (pos)
7051 "Remove outline overlays that do not contain non-white stuff."
7052 (mapc
7053 (lambda (o)
7054 (and (eq 'outline (overlay-get o 'invisible))
7055 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7056 (overlay-end o))))
7057 (delete-overlay o)))
7058 (overlays-at pos)))
7060 (defun org-clean-visibility-after-subtree-move ()
7061 "Fix visibility issues after moving a subtree."
7062 ;; First, find a reasonable region to look at:
7063 ;; Start two siblings above, end three below
7064 (let* ((beg (save-excursion
7065 (and (org-get-last-sibling)
7066 (org-get-last-sibling))
7067 (point)))
7068 (end (save-excursion
7069 (and (org-get-next-sibling)
7070 (org-get-next-sibling)
7071 (org-get-next-sibling))
7072 (if (org-at-heading-p)
7073 (point-at-eol)
7074 (point))))
7075 (level (looking-at "\\*+"))
7076 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7077 (save-excursion
7078 (save-restriction
7079 (narrow-to-region beg end)
7080 (when re
7081 ;; Properly fold already folded siblings
7082 (goto-char (point-min))
7083 (while (re-search-forward re nil t)
7084 (if (and (not (outline-invisible-p))
7085 (save-excursion
7086 (goto-char (point-at-eol)) (outline-invisible-p)))
7087 (hide-entry))))
7088 (org-cycle-show-empty-lines 'overview)
7089 (org-cycle-hide-drawers 'overview)))))
7091 (defun org-cycle-show-empty-lines (state)
7092 "Show empty lines above all visible headlines.
7093 The region to be covered depends on STATE when called through
7094 `org-cycle-hook'. Lisp program can use t for STATE to get the
7095 entire buffer covered. Note that an empty line is only shown if there
7096 are at least `org-cycle-separator-lines' empty lines before the headline."
7097 (when (not (= org-cycle-separator-lines 0))
7098 (save-excursion
7099 (let* ((n (abs org-cycle-separator-lines))
7100 (re (cond
7101 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7102 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7103 (t (let ((ns (number-to-string (- n 2))))
7104 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7105 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7106 beg end b e)
7107 (cond
7108 ((memq state '(overview contents t))
7109 (setq beg (point-min) end (point-max)))
7110 ((memq state '(children folded))
7111 (setq beg (point) end (progn (org-end-of-subtree t t)
7112 (beginning-of-line 2)
7113 (point)))))
7114 (when beg
7115 (goto-char beg)
7116 (while (re-search-forward re end t)
7117 (unless (get-char-property (match-end 1) 'invisible)
7118 (setq e (match-end 1))
7119 (if (< org-cycle-separator-lines 0)
7120 (setq b (save-excursion
7121 (goto-char (match-beginning 0))
7122 (org-back-over-empty-lines)
7123 (if (save-excursion
7124 (goto-char (max (point-min) (1- (point))))
7125 (org-at-heading-p))
7126 (1- (point))
7127 (point))))
7128 (setq b (match-beginning 1)))
7129 (outline-flag-region b e nil)))))))
7130 ;; Never hide empty lines at the end of the file.
7131 (save-excursion
7132 (goto-char (point-max))
7133 (outline-previous-heading)
7134 (outline-end-of-heading)
7135 (if (and (looking-at "[ \t\n]+")
7136 (= (match-end 0) (point-max)))
7137 (outline-flag-region (point) (match-end 0) nil))))
7139 (defun org-show-empty-lines-in-parent ()
7140 "Move to the parent and re-show empty lines before visible headlines."
7141 (save-excursion
7142 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7143 (org-cycle-show-empty-lines context))))
7145 (defun org-files-list ()
7146 "Return `org-agenda-files' list, plus all open org-mode files.
7147 This is useful for operations that need to scan all of a user's
7148 open and agenda-wise Org files."
7149 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7150 (dolist (buf (buffer-list))
7151 (with-current-buffer buf
7152 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7153 (let ((file (expand-file-name (buffer-file-name))))
7154 (unless (member file files)
7155 (push file files))))))
7156 files))
7158 (defsubst org-entry-beginning-position ()
7159 "Return the beginning position of the current entry."
7160 (save-excursion (outline-back-to-heading t) (point)))
7162 (defsubst org-entry-end-position ()
7163 "Return the end position of the current entry."
7164 (save-excursion (outline-next-heading) (point)))
7166 (defun org-cycle-hide-drawers (state &optional exceptions)
7167 "Re-hide all drawers after a visibility state change.
7168 When non-nil, optional argument EXCEPTIONS is a list of strings
7169 specifying which drawers should not be hidden."
7170 (when (and (derived-mode-p 'org-mode)
7171 (not (memq state '(overview folded contents))))
7172 (save-excursion
7173 (let* ((globalp (memq state '(contents all)))
7174 (beg (if globalp (point-min) (point)))
7175 (end (if globalp (point-max)
7176 (if (eq state 'children)
7177 (save-excursion (outline-next-heading) (point))
7178 (org-end-of-subtree t)))))
7179 (goto-char beg)
7180 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7181 (unless (member-ignore-case (match-string 1) exceptions)
7182 (let ((drawer (org-element-at-point)))
7183 (when (memq (org-element-type drawer) '(drawer property-drawer))
7184 (org-flag-drawer t drawer)
7185 ;; Make sure to skip drawer entirely or we might flag
7186 ;; it another time when matching its ending line with
7187 ;; `org-drawer-regexp'.
7188 (goto-char (org-element-property :end drawer))))))))))
7190 (defun org-cycle-hide-inline-tasks (state)
7191 "Re-hide inline tasks when switching to 'contents or 'children
7192 visibility state."
7193 (case state
7194 (contents
7195 (when (org-bound-and-true-p org-inlinetask-min-level)
7196 (hide-sublevels (1- org-inlinetask-min-level))))
7197 (children
7198 (when (featurep 'org-inlinetask)
7199 (save-excursion
7200 (while (and (outline-next-heading)
7201 (org-inlinetask-at-task-p))
7202 (org-inlinetask-toggle-visibility)
7203 (org-inlinetask-goto-end)))))))
7205 (defun org-flag-drawer (flag &optional element)
7206 "When FLAG is non-nil, hide the drawer we are at.
7207 Otherwise make it visible. When optional argument ELEMENT is
7208 a parsed drawer, as returned by `org-element-at-point', hide or
7209 show that drawer instead."
7210 (when (save-excursion
7211 (beginning-of-line)
7212 (org-looking-at-p org-drawer-regexp))
7213 (let ((drawer (or element (org-element-at-point))))
7214 (when (memq (org-element-type drawer) '(drawer property-drawer))
7215 (let ((post (org-element-property :post-affiliated drawer)))
7216 (save-excursion
7217 (outline-flag-region
7218 (progn (goto-char post) (line-end-position))
7219 (progn (goto-char (org-element-property :end drawer))
7220 (skip-chars-backward " \r\t\n")
7221 (line-end-position))
7222 flag))
7223 ;; When the drawer is hidden away, make sure point lies in
7224 ;; a visible part of the buffer.
7225 (when (and flag (> (line-beginning-position) post))
7226 (goto-char post)))))))
7228 (defun org-subtree-end-visible-p ()
7229 "Is the end of the current subtree visible?"
7230 (pos-visible-in-window-p
7231 (save-excursion (org-end-of-subtree t) (point))))
7233 (defun org-first-headline-recenter ()
7234 "Move cursor to the first headline and recenter the headline."
7235 (goto-char (point-min))
7236 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7237 (set-window-start (selected-window) (point-at-bol))))
7239 ;;; Saving and restoring visibility
7241 (defun org-outline-overlay-data (&optional use-markers)
7242 "Return a list of the locations of all outline overlays.
7243 These are overlays with the `invisible' property value `outline'.
7244 The return value is a list of cons cells, with start and stop
7245 positions for each overlay.
7246 If USE-MARKERS is set, return the positions as markers."
7247 (let (beg end)
7248 (save-excursion
7249 (save-restriction
7250 (widen)
7251 (delq nil
7252 (mapcar (lambda (o)
7253 (when (eq (overlay-get o 'invisible) 'outline)
7254 (setq beg (overlay-start o)
7255 end (overlay-end o))
7256 (and beg end (> end beg)
7257 (if use-markers
7258 (cons (copy-marker beg)
7259 (copy-marker end t))
7260 (cons beg end)))))
7261 (overlays-in (point-min) (point-max))))))))
7263 (defun org-set-outline-overlay-data (data)
7264 "Create visibility overlays for all positions in DATA.
7265 DATA should have been made by `org-outline-overlay-data'."
7266 (let (o)
7267 (save-excursion
7268 (save-restriction
7269 (widen)
7270 (show-all)
7271 (mapc (lambda (c)
7272 (outline-flag-region (car c) (cdr c) t))
7273 data)))))
7275 ;;; Folding of blocks
7277 (defvar org-hide-block-overlays nil
7278 "Overlays hiding blocks.")
7279 (make-variable-buffer-local 'org-hide-block-overlays)
7281 (defun org-block-map (function &optional start end)
7282 "Call FUNCTION at the head of all source blocks in the current buffer.
7283 Optional arguments START and END can be used to limit the range."
7284 (let ((start (or start (point-min)))
7285 (end (or end (point-max))))
7286 (save-excursion
7287 (goto-char start)
7288 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7289 (save-excursion
7290 (save-match-data
7291 (goto-char (match-beginning 0))
7292 (funcall function)))))))
7294 (defun org-hide-block-toggle-all ()
7295 "Toggle the visibility of all blocks in the current buffer."
7296 (org-block-map 'org-hide-block-toggle))
7298 (defun org-hide-block-all ()
7299 "Fold all blocks in the current buffer."
7300 (interactive)
7301 (org-show-block-all)
7302 (org-block-map 'org-hide-block-toggle-maybe))
7304 (defun org-show-block-all ()
7305 "Unfold all blocks in the current buffer."
7306 (interactive)
7307 (mapc 'delete-overlay org-hide-block-overlays)
7308 (setq org-hide-block-overlays nil))
7310 (defun org-hide-block-toggle-maybe ()
7311 "Toggle visibility of block at point.
7312 Unlike to `org-hide-block-toggle', this function does not throw
7313 an error. Return a non-nil value when toggling is successful."
7314 (interactive)
7315 (ignore-errors (org-hide-block-toggle)))
7317 (defun org-hide-block-toggle (&optional force)
7318 "Toggle the visibility of the current block.
7319 When optional argument FORCE is `off', make block visible. If it
7320 is non-nil, hide it unconditionally. Throw an error when not at
7321 a block. Return a non-nil value when toggling is successful."
7322 (interactive)
7323 (let ((element (org-element-at-point)))
7324 (unless (memq (org-element-type element)
7325 '(center-block comment-block dynamic-block example-block
7326 export-block quote-block special-block
7327 src-block verse-block))
7328 (user-error "Not at a block"))
7329 (let* ((start (save-excursion
7330 (goto-char (org-element-property :post-affiliated element))
7331 (line-end-position)))
7332 (end (save-excursion
7333 (goto-char (org-element-property :end element))
7334 (skip-chars-backward " \r\t\n")
7335 (line-end-position)))
7336 (overlays (overlays-at start)))
7337 (cond
7338 ;; Do nothing when not before or at the block opening line or
7339 ;; at the block closing line.
7340 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7341 ((and (not (eq force 'off))
7342 (not (memq t (mapcar
7343 (lambda (o)
7344 (eq (overlay-get o 'invisible) 'org-hide-block))
7345 overlays))))
7346 (let ((ov (make-overlay start end)))
7347 (overlay-put ov 'invisible 'org-hide-block)
7348 ;; Make the block accessible to `isearch'.
7349 (overlay-put
7350 ov 'isearch-open-invisible
7351 (lambda (ov)
7352 (when (memq ov org-hide-block-overlays)
7353 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7354 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7355 (delete-overlay ov))))
7356 (push ov org-hide-block-overlays)
7357 ;; When the block is hidden away, make sure point is left in
7358 ;; a visible part of the buffer.
7359 (when (> (line-beginning-position) start)
7360 (goto-char start)
7361 (beginning-of-line))
7362 ;; Signal successful toggling.
7364 ((or (not force) (eq force 'off))
7365 (dolist (ov overlays t)
7366 (when (memq ov org-hide-block-overlays)
7367 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7368 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7369 (delete-overlay ov))))))))
7371 ;; org-tab-after-check-for-cycling-hook
7372 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7373 ;; Remove overlays when changing major mode
7374 (add-hook 'org-mode-hook
7375 (lambda () (org-add-hook 'change-major-mode-hook
7376 'org-show-block-all 'append 'local)))
7378 ;;; Org-goto
7380 (defvar org-goto-window-configuration nil)
7381 (defvar org-goto-marker nil)
7382 (defvar org-goto-map)
7383 (defun org-goto-map ()
7384 "Set the keymap `org-goto'."
7385 (setq org-goto-map
7386 (let ((map (make-sparse-keymap)))
7387 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7388 mouse-drag-region universal-argument org-occur))
7389 cmd)
7390 (while (setq cmd (pop cmds))
7391 (substitute-key-definition cmd cmd map global-map)))
7392 (suppress-keymap map)
7393 (org-defkey map "\C-m" 'org-goto-ret)
7394 (org-defkey map [(return)] 'org-goto-ret)
7395 (org-defkey map [(left)] 'org-goto-left)
7396 (org-defkey map [(right)] 'org-goto-right)
7397 (org-defkey map [(control ?g)] 'org-goto-quit)
7398 (org-defkey map "\C-i" 'org-cycle)
7399 (org-defkey map [(tab)] 'org-cycle)
7400 (org-defkey map [(down)] 'outline-next-visible-heading)
7401 (org-defkey map [(up)] 'outline-previous-visible-heading)
7402 (if org-goto-auto-isearch
7403 (if (fboundp 'define-key-after)
7404 (define-key-after map [t] 'org-goto-local-auto-isearch)
7405 nil)
7406 (org-defkey map "q" 'org-goto-quit)
7407 (org-defkey map "n" 'outline-next-visible-heading)
7408 (org-defkey map "p" 'outline-previous-visible-heading)
7409 (org-defkey map "f" 'outline-forward-same-level)
7410 (org-defkey map "b" 'outline-backward-same-level)
7411 (org-defkey map "u" 'outline-up-heading))
7412 (org-defkey map "/" 'org-occur)
7413 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7414 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7415 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7416 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7417 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7418 map)))
7420 (defconst org-goto-help
7421 "Browse buffer copy, to find location or copy text.%s
7422 RET=jump to location C-g=quit and return to previous location
7423 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7425 (defvar org-goto-start-pos) ; dynamically scoped parameter
7427 (defun org-goto (&optional alternative-interface)
7428 "Look up a different location in the current file, keeping current visibility.
7430 When you want look-up or go to a different location in a
7431 document, the fastest way is often to fold the entire buffer and
7432 then dive into the tree. This method has the disadvantage, that
7433 the previous location will be folded, which may not be what you
7434 want.
7436 This command works around this by showing a copy of the current
7437 buffer in an indirect buffer, in overview mode. You can dive
7438 into the tree in that copy, use org-occur and incremental search
7439 to find a location. When pressing RET or `Q', the command
7440 returns to the original buffer in which the visibility is still
7441 unchanged. After RET it will also jump to the location selected
7442 in the indirect buffer and expose the headline hierarchy above.
7444 With a prefix argument, use the alternative interface: e.g. if
7445 `org-goto-interface' is 'outline use 'outline-path-completion."
7446 (interactive "P")
7447 (org-goto-map)
7448 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7449 (org-refile-use-outline-path t)
7450 (org-refile-target-verify-function nil)
7451 (interface
7452 (if (not alternative-interface)
7453 org-goto-interface
7454 (if (eq org-goto-interface 'outline)
7455 'outline-path-completion
7456 'outline)))
7457 (org-goto-start-pos (point))
7458 (selected-point
7459 (if (eq interface 'outline)
7460 (car (org-get-location (current-buffer) org-goto-help))
7461 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7462 (org-refile-check-position pa)
7463 (nth 3 pa)))))
7464 (if selected-point
7465 (progn
7466 (org-mark-ring-push org-goto-start-pos)
7467 (goto-char selected-point)
7468 (if (or (outline-invisible-p) (org-invisible-p2))
7469 (org-show-context 'org-goto)))
7470 (message "Quit"))))
7472 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7473 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7474 (defvar org-goto-local-auto-isearch-map) ; defined below
7476 (defun org-get-location (buf help)
7477 "Let the user select a location in the Org-mode buffer BUF.
7478 This function uses a recursive edit. It returns the selected position
7479 or nil."
7480 (org-no-popups
7481 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7482 (isearch-hide-immediately nil)
7483 (isearch-search-fun-function
7484 (lambda () 'org-goto-local-search-headings))
7485 (org-goto-selected-point org-goto-exit-command))
7486 (save-excursion
7487 (save-window-excursion
7488 (delete-other-windows)
7489 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7490 (org-pop-to-buffer-same-window
7491 (condition-case nil
7492 (make-indirect-buffer (current-buffer) "*org-goto*")
7493 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7494 (with-output-to-temp-buffer "*Org Help*"
7495 (princ (format help (if org-goto-auto-isearch
7496 " Just type for auto-isearch."
7497 " n/p/f/b/u to navigate, q to quit."))))
7498 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7499 (setq buffer-read-only nil)
7500 (let ((org-startup-truncated t)
7501 (org-startup-folded nil)
7502 (org-startup-align-all-tables nil))
7503 (org-mode)
7504 (org-overview))
7505 (setq buffer-read-only t)
7506 (if (and (boundp 'org-goto-start-pos)
7507 (integer-or-marker-p org-goto-start-pos))
7508 (let ((org-show-hierarchy-above t)
7509 (org-show-siblings t)
7510 (org-show-following-heading t))
7511 (goto-char org-goto-start-pos)
7512 (and (outline-invisible-p) (org-show-context)))
7513 (goto-char (point-min)))
7514 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7515 (message "Select location and press RET")
7516 (use-local-map org-goto-map)
7517 (recursive-edit)))
7518 (kill-buffer "*org-goto*")
7519 (cons org-goto-selected-point org-goto-exit-command))))
7521 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7522 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7523 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7524 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7526 (defun org-goto-local-search-headings (string bound noerror)
7527 "Search and make sure that any matches are in headlines."
7528 (catch 'return
7529 (while (if isearch-forward
7530 (search-forward string bound noerror)
7531 (search-backward string bound noerror))
7532 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7533 (and (member :headline context)
7534 (not (member :tags context))))
7535 (throw 'return (point))))))
7537 (defun org-goto-local-auto-isearch ()
7538 "Start isearch."
7539 (interactive)
7540 (goto-char (point-min))
7541 (let ((keys (this-command-keys)))
7542 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7543 (isearch-mode t)
7544 (isearch-process-search-char (string-to-char keys)))))
7546 (defun org-goto-ret (&optional arg)
7547 "Finish `org-goto' by going to the new location."
7548 (interactive "P")
7549 (setq org-goto-selected-point (point)
7550 org-goto-exit-command 'return)
7551 (throw 'exit nil))
7553 (defun org-goto-left ()
7554 "Finish `org-goto' by going to the new location."
7555 (interactive)
7556 (if (org-at-heading-p)
7557 (progn
7558 (beginning-of-line 1)
7559 (setq org-goto-selected-point (point)
7560 org-goto-exit-command 'left)
7561 (throw 'exit nil))
7562 (user-error "Not on a heading")))
7564 (defun org-goto-right ()
7565 "Finish `org-goto' by going to the new location."
7566 (interactive)
7567 (if (org-at-heading-p)
7568 (progn
7569 (setq org-goto-selected-point (point)
7570 org-goto-exit-command 'right)
7571 (throw 'exit nil))
7572 (user-error "Not on a heading")))
7574 (defun org-goto-quit ()
7575 "Finish `org-goto' without cursor motion."
7576 (interactive)
7577 (setq org-goto-selected-point nil)
7578 (setq org-goto-exit-command 'quit)
7579 (throw 'exit nil))
7581 ;;; Indirect buffer display of subtrees
7583 (defvar org-indirect-dedicated-frame nil
7584 "This is the frame being used for indirect tree display.")
7585 (defvar org-last-indirect-buffer nil)
7587 (defun org-tree-to-indirect-buffer (&optional arg)
7588 "Create indirect buffer and narrow it to current subtree.
7589 With a numerical prefix ARG, go up to this level and then take that tree.
7590 If ARG is negative, go up that many levels.
7592 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7593 indirect buffer previously made with this command, to avoid proliferation of
7594 indirect buffers. However, when you call the command with a \
7595 \\[universal-argument] prefix, or
7596 when `org-indirect-buffer-display' is `new-frame', the last buffer
7597 is kept so that you can work with several indirect buffers at the same time.
7598 If `org-indirect-buffer-display' is `dedicated-frame', the \
7599 \\[universal-argument] prefix also
7600 requests that a new frame be made for the new buffer, so that the dedicated
7601 frame is not changed."
7602 (interactive "P")
7603 (let ((cbuf (current-buffer))
7604 (cwin (selected-window))
7605 (pos (point))
7606 beg end level heading ibuf)
7607 (save-excursion
7608 (org-back-to-heading t)
7609 (when (numberp arg)
7610 (setq level (org-outline-level))
7611 (if (< arg 0) (setq arg (+ level arg)))
7612 (while (> (setq level (org-outline-level)) arg)
7613 (org-up-heading-safe)))
7614 (setq beg (point)
7615 heading (org-get-heading))
7616 (org-end-of-subtree t t)
7617 (if (org-at-heading-p) (backward-char 1))
7618 (setq end (point)))
7619 (if (and (buffer-live-p org-last-indirect-buffer)
7620 (not (eq org-indirect-buffer-display 'new-frame))
7621 (not arg))
7622 (kill-buffer org-last-indirect-buffer))
7623 (setq ibuf (org-get-indirect-buffer cbuf heading)
7624 org-last-indirect-buffer ibuf)
7625 (cond
7626 ((or (eq org-indirect-buffer-display 'new-frame)
7627 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7628 (select-frame (make-frame))
7629 (delete-other-windows)
7630 (org-pop-to-buffer-same-window ibuf)
7631 (org-set-frame-title heading))
7632 ((eq org-indirect-buffer-display 'dedicated-frame)
7633 (raise-frame
7634 (select-frame (or (and org-indirect-dedicated-frame
7635 (frame-live-p org-indirect-dedicated-frame)
7636 org-indirect-dedicated-frame)
7637 (setq org-indirect-dedicated-frame (make-frame)))))
7638 (delete-other-windows)
7639 (org-pop-to-buffer-same-window ibuf)
7640 (org-set-frame-title (concat "Indirect: " heading)))
7641 ((eq org-indirect-buffer-display 'current-window)
7642 (org-pop-to-buffer-same-window ibuf))
7643 ((eq org-indirect-buffer-display 'other-window)
7644 (pop-to-buffer ibuf))
7645 (t (error "Invalid value")))
7646 (if (featurep 'xemacs)
7647 (save-excursion (org-mode) (turn-on-font-lock)))
7648 (narrow-to-region beg end)
7649 (show-all)
7650 (goto-char pos)
7651 (run-hook-with-args 'org-cycle-hook 'all)
7652 (and (window-live-p cwin) (select-window cwin))))
7654 (defun org-get-indirect-buffer (&optional buffer heading)
7655 (setq buffer (or buffer (current-buffer)))
7656 (let ((n 1) (base (buffer-name buffer)) bname)
7657 (while (buffer-live-p
7658 (get-buffer
7659 (setq bname
7660 (concat base "-"
7661 (if heading (concat heading "-" (number-to-string n))
7662 (number-to-string n))))))
7663 (setq n (1+ n)))
7664 (condition-case nil
7665 (make-indirect-buffer buffer bname 'clone)
7666 (error (make-indirect-buffer buffer bname)))))
7668 (defun org-set-frame-title (title)
7669 "Set the title of the current frame to the string TITLE."
7670 ;; FIXME: how to name a single frame in XEmacs???
7671 (unless (featurep 'xemacs)
7672 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7674 ;;;; Structure editing
7676 ;;; Inserting headlines
7678 (defun org-previous-line-empty-p (&optional next)
7679 "Is the previous line a blank line?
7680 When NEXT is non-nil, check the next line instead."
7681 (save-excursion
7682 (and (not (bobp))
7683 (or (beginning-of-line (if next 2 0)) t)
7684 (save-match-data
7685 (looking-at "[ \t]*$")))))
7687 (defun org-insert-heading (&optional arg invisible-ok)
7688 "Insert a new heading or an item with the same depth at point.
7690 If point is at the beginning of a heading or a list item, insert
7691 a new heading or a new item above the current one. If point is
7692 at the beginning of a normal line, turn the line into a heading.
7694 If point is in the middle of a headline or a list item, split the
7695 headline or the item and create a new headline/item with the text
7696 in the current line after point \(see `org-M-RET-may-split-line'
7697 on how to modify this behavior).
7699 With one universal prefix argument, set the user option
7700 `org-insert-heading-respect-content' to t for the duration of
7701 the command. This modifies the behavior described above in this
7702 ways: on list items and at the beginning of normal lines, force
7703 the insertion of a heading after the current subtree.
7705 With two universal prefix arguments, insert the heading at the
7706 end of the grandparent subtree. For example, if point is within
7707 a 2nd-level heading, then it will insert a 2nd-level heading at
7708 the end of the 1st-level parent heading.
7710 If point is at the beginning of a headline, insert a sibling
7711 before the current headline. If point is not at the beginning,
7712 split the line and create a new headline with the text in the
7713 current line after point \(see `org-M-RET-may-split-line' on how
7714 to modify this behavior).
7716 If point is at the beginning of a normal line, turn this line
7717 into a heading.
7719 When INVISIBLE-OK is set, stop at invisible headlines when going
7720 back. This is important for non-interactive uses of the
7721 command."
7722 (interactive "P")
7723 (if (org-called-interactively-p 'any) (org-reveal))
7724 (let ((itemp (org-in-item-p))
7725 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7726 (respect-content (or org-insert-heading-respect-content
7727 (equal arg '(4))))
7728 (initial-content "")
7729 (adjust-empty-lines t))
7731 (cond
7733 ((or (= (buffer-size) 0)
7734 (and (not (save-excursion
7735 (and (ignore-errors (org-back-to-heading invisible-ok))
7736 (org-at-heading-p))))
7737 (or arg (not itemp))))
7738 ;; At beginning of buffer or so high up that only a heading
7739 ;; makes sense.
7740 (cond ((and (bolp) (not respect-content)) (insert "* "))
7741 ((not respect-content)
7742 (unless may-split (end-of-line))
7743 (insert "\n* "))
7744 ((re-search-forward org-outline-regexp-bol nil t)
7745 (beginning-of-line)
7746 (insert "* \n")
7747 (backward-char))
7748 (t (goto-char (point-max))
7749 (insert "\n* ")))
7750 (run-hooks 'org-insert-heading-hook))
7752 ((and itemp (not (member arg '((4) (16)))))
7753 ;; Insert an item
7754 (org-insert-item))
7757 ;; Maybe move at the end of the subtree
7758 (when (equal arg '(16))
7759 (org-up-heading-safe)
7760 (org-end-of-subtree t))
7761 ;; Insert a heading
7762 (save-restriction
7763 (widen)
7764 (let* ((level nil)
7765 (on-heading (org-at-heading-p))
7766 (empty-line-p (if on-heading
7767 (org-previous-line-empty-p)
7768 ;; We will decide later
7769 nil))
7770 ;; Get a level string to fall back on
7771 (fix-level
7772 (if (org-before-first-heading-p) "*"
7773 (save-excursion
7774 (org-back-to-heading t)
7775 (if (org-previous-line-empty-p) (setq empty-line-p t))
7776 (looking-at org-outline-regexp)
7777 (make-string (1- (length (match-string 0))) ?*))))
7778 (stars
7779 (save-excursion
7780 (condition-case nil
7781 (progn
7782 (org-back-to-heading invisible-ok)
7783 (when (and (not on-heading)
7784 (featurep 'org-inlinetask)
7785 (integerp org-inlinetask-min-level)
7786 (>= (length (match-string 0))
7787 org-inlinetask-min-level))
7788 ;; Find a heading level before the inline task
7789 (while (and (setq level (org-up-heading-safe))
7790 (>= level org-inlinetask-min-level)))
7791 (if (org-at-heading-p)
7792 (org-back-to-heading invisible-ok)
7793 (error "This should not happen")))
7794 (unless (and (save-excursion
7795 (save-match-data
7796 (org-backward-heading-same-level
7797 1 invisible-ok))
7798 (= (point) (match-beginning 0)))
7799 (not (org-previous-line-empty-p t)))
7800 (setq empty-line-p (or empty-line-p
7801 (org-previous-line-empty-p))))
7802 (match-string 0))
7803 (error (or fix-level "* ")))))
7804 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7805 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7806 pos hide-previous previous-pos)
7808 ;; If we insert after content, move there and clean up whitespace
7809 (when (and respect-content
7810 (not (org-looking-at-p org-outline-regexp-bol)))
7811 (if (not (org-before-first-heading-p))
7812 (org-end-of-subtree nil t)
7813 (re-search-forward org-outline-regexp-bol)
7814 (beginning-of-line 0))
7815 (skip-chars-backward " \r\n")
7816 (and (not (looking-back "^\\*+"))
7817 (looking-at "[ \t]+") (replace-match ""))
7818 (unless (eobp) (forward-char 1))
7819 (when (looking-at "^\\*")
7820 (unless (bobp) (backward-char 1))
7821 (insert "\n")))
7823 ;; If we are splitting, grab the text that should be moved to the new headline
7824 (when may-split
7825 (if (org-on-heading-p)
7826 ;; This is a heading, we split intelligently (keeping tags)
7827 (let ((pos (point)))
7828 (goto-char (point-at-bol))
7829 (unless (looking-at org-complex-heading-regexp)
7830 (error "This should not happen"))
7831 (when (and (match-beginning 4)
7832 (> pos (match-beginning 4))
7833 (< pos (match-end 4)))
7834 (setq initial-content (buffer-substring pos (match-end 4)))
7835 (goto-char pos)
7836 (delete-region (point) (match-end 4))
7837 (if (looking-at "[ \t]*$")
7838 (replace-match "")
7839 (insert (make-string (length initial-content) ?\ )))
7840 (setq initial-content (org-trim initial-content)))
7841 (goto-char pos))
7842 ;; a normal line
7843 (setq initial-content
7844 (org-trim (buffer-substring (point) (point-at-eol))))
7845 (delete-region (point) (point-at-eol))))
7847 ;; If we are at the beginning of the line, insert before it. Else after
7848 (cond
7849 ((and (bolp) (looking-at "[ \t]*$")))
7850 ((and (bolp) (not (looking-at "[ \t]*$")))
7851 (open-line 1))
7853 (goto-char (point-at-eol))
7854 (insert "\n")))
7856 ;; Insert the new heading
7857 (insert stars)
7858 (just-one-space)
7859 (insert initial-content)
7860 (when adjust-empty-lines
7861 (if (or (not blank)
7862 (and blank (not (org-previous-line-empty-p))))
7863 (org-N-empty-lines-before-current (if blank 1 0))))
7864 (run-hooks 'org-insert-heading-hook)))))))
7866 (defun org-N-empty-lines-before-current (N)
7867 "Make the number of empty lines before current exactly N.
7868 So this will delete or add empty lines."
7869 (save-excursion
7870 (beginning-of-line)
7871 (let ((p (point)))
7872 (skip-chars-backward " \r\t\n")
7873 (unless (bolp) (forward-line))
7874 (delete-region (point) p))
7875 (when (> N 0) (insert (make-string N ?\n)))))
7877 (defun org-get-heading (&optional no-tags no-todo)
7878 "Return the heading of the current entry, without the stars.
7879 When NO-TAGS is non-nil, don't include tags.
7880 When NO-TODO is non-nil, don't include TODO keywords."
7881 (save-excursion
7882 (org-back-to-heading t)
7883 (cond
7884 ((and no-tags no-todo)
7885 (looking-at org-complex-heading-regexp)
7886 (match-string 4))
7887 (no-tags
7888 (looking-at (concat org-outline-regexp
7889 "\\(.*?\\)"
7890 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7891 (match-string 1))
7892 (no-todo
7893 (looking-at org-todo-line-regexp)
7894 (match-string 3))
7895 (t (looking-at org-heading-regexp)
7896 (match-string 2)))))
7898 (defvar orgstruct-mode) ; defined below
7900 (defun org-heading-components ()
7901 "Return the components of the current heading.
7902 This is a list with the following elements:
7903 - the level as an integer
7904 - the reduced level, different if `org-odd-levels-only' is set.
7905 - the TODO keyword, or nil
7906 - the priority character, like ?A, or nil if no priority is given
7907 - the headline text itself, or the tags string if no headline text
7908 - the tags string, or nil."
7909 (save-excursion
7910 (org-back-to-heading t)
7911 (if (let (case-fold-search)
7912 (looking-at
7913 (if orgstruct-mode
7914 org-heading-regexp
7915 org-complex-heading-regexp)))
7916 (if orgstruct-mode
7917 (list (length (match-string 1))
7918 (org-reduced-level (length (match-string 1)))
7921 (match-string 2)
7922 nil)
7923 (list (length (match-string 1))
7924 (org-reduced-level (length (match-string 1)))
7925 (org-match-string-no-properties 2)
7926 (and (match-end 3) (aref (match-string 3) 2))
7927 (org-match-string-no-properties 4)
7928 (org-match-string-no-properties 5))))))
7930 (defun org-get-entry ()
7931 "Get the entry text, after heading, entire subtree."
7932 (save-excursion
7933 (org-back-to-heading t)
7934 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7936 (defun org-insert-heading-after-current ()
7937 "Insert a new heading with same level as current, after current subtree."
7938 (interactive)
7939 (org-back-to-heading)
7940 (org-insert-heading)
7941 (org-move-subtree-down)
7942 (end-of-line 1))
7944 (defun org-insert-heading-respect-content (&optional invisible-ok)
7945 "Insert heading with `org-insert-heading-respect-content' set to t."
7946 (interactive)
7947 (org-insert-heading '(4) invisible-ok))
7949 (defun org-insert-todo-heading-respect-content (&optional force-state)
7950 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7951 (interactive)
7952 (org-insert-todo-heading force-state '(4)))
7954 (defun org-insert-todo-heading (arg &optional force-heading)
7955 "Insert a new heading with the same level and TODO state as current heading.
7956 If the heading has no TODO state, or if the state is DONE, use the first
7957 state (TODO by default). Also with one prefix arg, force first state. With
7958 two prefix args, force inserting at the end of the parent subtree."
7959 (interactive "P")
7960 (when (or force-heading (not (org-insert-item 'checkbox)))
7961 (org-insert-heading (or (and (equal arg '(16)) '(16))
7962 force-heading))
7963 (save-excursion
7964 (org-back-to-heading)
7965 (outline-previous-heading)
7966 (looking-at org-todo-line-regexp))
7967 (let*
7968 ((new-mark-x
7969 (if (or (equal arg '(4))
7970 (not (match-beginning 2))
7971 (member (match-string 2) org-done-keywords))
7972 (car org-todo-keywords-1)
7973 (match-string 2)))
7974 (new-mark
7976 (run-hook-with-args-until-success
7977 'org-todo-get-default-hook new-mark-x nil)
7978 new-mark-x)))
7979 (beginning-of-line 1)
7980 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7981 (if org-treat-insert-todo-heading-as-state-change
7982 (org-todo new-mark)
7983 (insert new-mark " "))))
7984 (when org-provide-todo-statistics
7985 (org-update-parent-todo-statistics))))
7987 (defun org-insert-subheading (arg)
7988 "Insert a new subheading and demote it.
7989 Works for outline headings and for plain lists alike."
7990 (interactive "P")
7991 (org-insert-heading arg)
7992 (cond
7993 ((org-at-heading-p) (org-do-demote))
7994 ((org-at-item-p) (org-indent-item))))
7996 (defun org-insert-todo-subheading (arg)
7997 "Insert a new subheading with TODO keyword or checkbox and demote it.
7998 Works for outline headings and for plain lists alike."
7999 (interactive "P")
8000 (org-insert-todo-heading arg)
8001 (cond
8002 ((org-at-heading-p) (org-do-demote))
8003 ((org-at-item-p) (org-indent-item))))
8005 ;;; Promotion and Demotion
8007 (defvar org-after-demote-entry-hook nil
8008 "Hook run after an entry has been demoted.
8009 The cursor will be at the beginning of the entry.
8010 When a subtree is being demoted, the hook will be called for each node.")
8012 (defvar org-after-promote-entry-hook nil
8013 "Hook run after an entry has been promoted.
8014 The cursor will be at the beginning of the entry.
8015 When a subtree is being promoted, the hook will be called for each node.")
8017 (defun org-promote-subtree ()
8018 "Promote the entire subtree.
8019 See also `org-promote'."
8020 (interactive)
8021 (save-excursion
8022 (org-with-limited-levels (org-map-tree 'org-promote)))
8023 (org-fix-position-after-promote))
8025 (defun org-demote-subtree ()
8026 "Demote the entire subtree. See `org-demote'.
8027 See also `org-promote'."
8028 (interactive)
8029 (save-excursion
8030 (org-with-limited-levels (org-map-tree 'org-demote)))
8031 (org-fix-position-after-promote))
8034 (defun org-do-promote ()
8035 "Promote the current heading higher up the tree.
8036 If the region is active in `transient-mark-mode', promote all headings
8037 in the region."
8038 (interactive)
8039 (save-excursion
8040 (if (org-region-active-p)
8041 (org-map-region 'org-promote (region-beginning) (region-end))
8042 (org-promote)))
8043 (org-fix-position-after-promote))
8045 (defun org-do-demote ()
8046 "Demote the current heading lower down the tree.
8047 If the region is active in `transient-mark-mode', demote all headings
8048 in the region."
8049 (interactive)
8050 (save-excursion
8051 (if (org-region-active-p)
8052 (org-map-region 'org-demote (region-beginning) (region-end))
8053 (org-demote)))
8054 (org-fix-position-after-promote))
8056 (defun org-fix-position-after-promote ()
8057 "Make sure that after pro/demotion cursor position is right."
8058 (let ((pos (point)))
8059 (when (save-excursion
8060 (beginning-of-line 1)
8061 (looking-at org-todo-line-regexp)
8062 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8063 (cond ((eobp) (insert " "))
8064 ((eolp) (insert " "))
8065 ((equal (char-after) ?\ ) (forward-char 1))))))
8067 (defun org-current-level ()
8068 "Return the level of the current entry, or nil if before the first headline.
8069 The level is the number of stars at the beginning of the headline."
8070 (save-excursion
8071 (org-with-limited-levels
8072 (if (ignore-errors (org-back-to-heading t))
8073 (funcall outline-level)))))
8075 (defun org-get-previous-line-level ()
8076 "Return the outline depth of the last headline before the current line.
8077 Returns 0 for the first headline in the buffer, and nil if before the
8078 first headline."
8079 (and (org-current-level)
8080 (or (and (/= (line-beginning-position) (point-min))
8081 (save-excursion (beginning-of-line 0) (org-current-level)))
8082 0)))
8084 (defun org-reduced-level (l)
8085 "Compute the effective level of a heading.
8086 This takes into account the setting of `org-odd-levels-only'."
8087 (cond
8088 ((zerop l) 0)
8089 (org-odd-levels-only (1+ (floor (/ l 2))))
8090 (t l)))
8092 (defun org-level-increment ()
8093 "Return the number of stars that will be added or removed at a
8094 time to headlines when structure editing, based on the value of
8095 `org-odd-levels-only'."
8096 (if org-odd-levels-only 2 1))
8098 (defun org-get-valid-level (level &optional change)
8099 "Rectify a level change under the influence of `org-odd-levels-only'
8100 LEVEL is a current level, CHANGE is by how much the level should be
8101 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8102 even level numbers will become the next higher odd number."
8103 (if org-odd-levels-only
8104 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8105 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8106 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8107 (max 1 (+ level (or change 0)))))
8109 (if (boundp 'define-obsolete-function-alias)
8110 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8111 (define-obsolete-function-alias 'org-get-legal-level
8112 'org-get-valid-level)
8113 (define-obsolete-function-alias 'org-get-legal-level
8114 'org-get-valid-level "23.1")))
8116 (defun org-promote ()
8117 "Promote the current heading higher up the tree.
8118 If the region is active in `transient-mark-mode', promote all headings
8119 in the region."
8120 (org-back-to-heading t)
8121 (let* ((level (save-match-data (funcall outline-level)))
8122 (after-change-functions (remove 'flyspell-after-change-function
8123 after-change-functions))
8124 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8125 (diff (abs (- level (length up-head) -1))))
8126 (cond ((and (= level 1) org-called-with-limited-levels
8127 org-allow-promoting-top-level-subtree)
8128 (replace-match "# " nil t))
8129 ((= level 1)
8130 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8131 (t (replace-match up-head nil t)))
8132 ;; Fixup tag positioning
8133 (unless (= level 1)
8134 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8135 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8136 (run-hooks 'org-after-promote-entry-hook)))
8138 (defun org-demote ()
8139 "Demote the current heading lower down the tree.
8140 If the region is active in `transient-mark-mode', demote all headings
8141 in the region."
8142 (org-back-to-heading t)
8143 (let* ((level (save-match-data (funcall outline-level)))
8144 (after-change-functions (remove 'flyspell-after-change-function
8145 after-change-functions))
8146 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8147 (diff (abs (- level (length down-head) -1))))
8148 (replace-match down-head nil t)
8149 ;; Fixup tag positioning
8150 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8151 (if org-adapt-indentation (org-fixup-indentation diff))
8152 (run-hooks 'org-after-demote-entry-hook)))
8154 (defun org-cycle-level ()
8155 "Cycle the level of an empty headline through possible states.
8156 This goes first to child, then to parent, level, then up the hierarchy.
8157 After top level, it switches back to sibling level."
8158 (interactive)
8159 (let ((org-adapt-indentation nil))
8160 (when (org-point-at-end-of-empty-headline)
8161 (setq this-command 'org-cycle-level) ; Only needed for caching
8162 (let ((cur-level (org-current-level))
8163 (prev-level (org-get-previous-line-level)))
8164 (cond
8165 ;; If first headline in file, promote to top-level.
8166 ((= prev-level 0)
8167 (loop repeat (/ (- cur-level 1) (org-level-increment))
8168 do (org-do-promote)))
8169 ;; If same level as prev, demote one.
8170 ((= prev-level cur-level)
8171 (org-do-demote))
8172 ;; If parent is top-level, promote to top level if not already.
8173 ((= prev-level 1)
8174 (loop repeat (/ (- cur-level 1) (org-level-increment))
8175 do (org-do-promote)))
8176 ;; If top-level, return to prev-level.
8177 ((= cur-level 1)
8178 (loop repeat (/ (- prev-level 1) (org-level-increment))
8179 do (org-do-demote)))
8180 ;; If less than prev-level, promote one.
8181 ((< cur-level prev-level)
8182 (org-do-promote))
8183 ;; If deeper than prev-level, promote until higher than
8184 ;; prev-level.
8185 ((> cur-level prev-level)
8186 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8187 do (org-do-promote))))
8188 t))))
8190 (defun org-map-tree (fun)
8191 "Call FUN for every heading underneath the current one."
8192 (org-back-to-heading)
8193 (let ((level (funcall outline-level)))
8194 (save-excursion
8195 (funcall fun)
8196 (while (and (progn
8197 (outline-next-heading)
8198 (> (funcall outline-level) level))
8199 (not (eobp)))
8200 (funcall fun)))))
8202 (defun org-map-region (fun beg end)
8203 "Call FUN for every heading between BEG and END."
8204 (let ((org-ignore-region t))
8205 (save-excursion
8206 (setq end (copy-marker end))
8207 (goto-char beg)
8208 (if (and (re-search-forward org-outline-regexp-bol nil t)
8209 (< (point) end))
8210 (funcall fun))
8211 (while (and (progn
8212 (outline-next-heading)
8213 (< (point) end))
8214 (not (eobp)))
8215 (funcall fun)))))
8217 (defvar org-property-end-re) ; silence byte-compiler
8218 (defun org-fixup-indentation (diff)
8219 "Change the indentation in the current entry by DIFF.
8220 However, if any line in the current entry has no indentation, or if it
8221 would end up with no indentation after the change, nothing at all is done."
8222 (save-excursion
8223 (let ((end (save-excursion (outline-next-heading)
8224 (point-marker)))
8225 (prohibit (if (> diff 0)
8226 "^\\S-"
8227 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8228 col)
8229 (unless (save-excursion (end-of-line 1)
8230 (re-search-forward prohibit end t))
8231 (while (and (< (point) end)
8232 (re-search-forward "^[ \t]+" end t))
8233 (goto-char (match-end 0))
8234 (setq col (current-column))
8235 (if (< diff 0) (replace-match ""))
8236 (org-indent-to-column (+ diff col))))
8237 (move-marker end nil))))
8239 (defun org-convert-to-odd-levels ()
8240 "Convert an org-mode file with all levels allowed to one with odd levels.
8241 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8242 level 5 etc."
8243 (interactive)
8244 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8245 (let ((outline-level 'org-outline-level)
8246 (org-odd-levels-only nil) n)
8247 (save-excursion
8248 (goto-char (point-min))
8249 (while (re-search-forward "^\\*\\*+ " nil t)
8250 (setq n (- (length (match-string 0)) 2))
8251 (while (>= (setq n (1- n)) 0)
8252 (org-demote))
8253 (end-of-line 1))))))
8255 (defun org-convert-to-oddeven-levels ()
8256 "Convert an org-mode file with only odd levels to one with odd/even levels.
8257 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8258 file contains a section with an even level, conversion would
8259 destroy the structure of the file. An error is signaled in this
8260 case."
8261 (interactive)
8262 (goto-char (point-min))
8263 ;; First check if there are no even levels
8264 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8265 (org-show-context t)
8266 (error "Not all levels are odd in this file. Conversion not possible"))
8267 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8268 (let ((outline-regexp org-outline-regexp)
8269 (outline-level 'org-outline-level)
8270 (org-odd-levels-only nil) n)
8271 (save-excursion
8272 (goto-char (point-min))
8273 (while (re-search-forward "^\\*\\*+ " nil t)
8274 (setq n (/ (1- (length (match-string 0))) 2))
8275 (while (>= (setq n (1- n)) 0)
8276 (org-promote))
8277 (end-of-line 1))))))
8279 (defun org-tr-level (n)
8280 "Make N odd if required."
8281 (if org-odd-levels-only (1+ (/ n 2)) n))
8283 ;;; Vertical tree motion, cutting and pasting of subtrees
8285 (defun org-move-subtree-up (&optional arg)
8286 "Move the current subtree up past ARG headlines of the same level."
8287 (interactive "p")
8288 (org-move-subtree-down (- (prefix-numeric-value arg))))
8290 (defun org-move-subtree-down (&optional arg)
8291 "Move the current subtree down past ARG headlines of the same level."
8292 (interactive "p")
8293 (setq arg (prefix-numeric-value arg))
8294 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8295 'org-get-last-sibling))
8296 (ins-point (make-marker))
8297 (cnt (abs arg))
8298 (col (current-column))
8299 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8300 ;; Select the tree
8301 (org-back-to-heading)
8302 (setq beg0 (point))
8303 (save-excursion
8304 (setq ne-beg (org-back-over-empty-lines))
8305 (setq beg (point)))
8306 (save-match-data
8307 (save-excursion (outline-end-of-heading)
8308 (setq folded (outline-invisible-p)))
8309 (progn (org-end-of-subtree nil t)
8310 (unless (eobp) (backward-char))))
8311 (outline-next-heading)
8312 (setq ne-end (org-back-over-empty-lines))
8313 (setq end (point))
8314 (goto-char beg0)
8315 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8316 ;; include less whitespace
8317 (save-excursion
8318 (goto-char beg)
8319 (forward-line (- ne-beg ne-end))
8320 (setq beg (point))))
8321 ;; Find insertion point, with error handling
8322 (while (> cnt 0)
8323 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8324 (progn (goto-char beg0)
8325 (user-error "Cannot move past superior level or buffer limit")))
8326 (setq cnt (1- cnt)))
8327 (if (> arg 0)
8328 ;; Moving forward - still need to move over subtree
8329 (progn (org-end-of-subtree t t)
8330 (save-excursion
8331 (org-back-over-empty-lines)
8332 (or (bolp) (newline)))))
8333 (setq ne-ins (org-back-over-empty-lines))
8334 (move-marker ins-point (point))
8335 (setq txt (buffer-substring beg end))
8336 (org-save-markers-in-region beg end)
8337 (delete-region beg end)
8338 (org-remove-empty-overlays-at beg)
8339 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8340 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8341 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8342 (let ((bbb (point)))
8343 (insert-before-markers txt)
8344 (org-reinstall-markers-in-region bbb)
8345 (move-marker ins-point bbb))
8346 (or (bolp) (insert "\n"))
8347 (setq ins-end (point))
8348 (goto-char ins-point)
8349 (org-skip-whitespace)
8350 (when (and (< arg 0)
8351 (org-first-sibling-p)
8352 (> ne-ins ne-beg))
8353 ;; Move whitespace back to beginning
8354 (save-excursion
8355 (goto-char ins-end)
8356 (let ((kill-whole-line t))
8357 (kill-line (- ne-ins ne-beg)) (point)))
8358 (insert (make-string (- ne-ins ne-beg) ?\n)))
8359 (move-marker ins-point nil)
8360 (if folded
8361 (hide-subtree)
8362 (org-show-entry)
8363 (show-children)
8364 (org-cycle-hide-drawers 'children))
8365 (org-clean-visibility-after-subtree-move)
8366 ;; move back to the initial column we were at
8367 (move-to-column col)))
8369 (defvar org-subtree-clip ""
8370 "Clipboard for cut and paste of subtrees.
8371 This is actually only a copy of the kill, because we use the normal kill
8372 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8374 (defvar org-subtree-clip-folded nil
8375 "Was the last copied subtree folded?
8376 This is used to fold the tree back after pasting.")
8378 (defun org-cut-subtree (&optional n)
8379 "Cut the current subtree into the clipboard.
8380 With prefix arg N, cut this many sequential subtrees.
8381 This is a short-hand for marking the subtree and then cutting it."
8382 (interactive "p")
8383 (org-copy-subtree n 'cut))
8385 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8386 "Copy the current subtree it in the clipboard.
8387 With prefix arg N, copy this many sequential subtrees.
8388 This is a short-hand for marking the subtree and then copying it.
8389 If CUT is non-nil, actually cut the subtree.
8390 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8391 of some markers in the region, even if CUT is non-nil. This is
8392 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8393 (interactive "p")
8394 (let (beg end folded (beg0 (point)))
8395 (if (org-called-interactively-p 'any)
8396 (org-back-to-heading nil) ; take what looks like a subtree
8397 (org-back-to-heading t)) ; take what is really there
8398 (setq beg (point))
8399 (skip-chars-forward " \t\r\n")
8400 (save-match-data
8401 (if nosubtrees
8402 (outline-next-heading)
8403 (save-excursion (outline-end-of-heading)
8404 (setq folded (outline-invisible-p)))
8405 (ignore-errors (org-forward-heading-same-level (1- n) t))
8406 (org-end-of-subtree t t)))
8407 (setq end (point))
8408 (goto-char beg0)
8409 (when (> end beg)
8410 (setq org-subtree-clip-folded folded)
8411 (when (or cut force-store-markers)
8412 (org-save-markers-in-region beg end))
8413 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8414 (setq org-subtree-clip (current-kill 0))
8415 (message "%s: Subtree(s) with %d characters"
8416 (if cut "Cut" "Copied")
8417 (length org-subtree-clip)))))
8419 (defun org-paste-subtree (&optional level tree for-yank remove)
8420 "Paste the clipboard as a subtree, with modification of headline level.
8421 The entire subtree is promoted or demoted in order to match a new headline
8422 level.
8424 If the cursor is at the beginning of a headline, the same level as
8425 that headline is used to paste the tree.
8427 If not, the new level is derived from the *visible* headings
8428 before and after the insertion point, and taken to be the inferior headline
8429 level of the two. So if the previous visible heading is level 3 and the
8430 next is level 4 (or vice versa), level 4 will be used for insertion.
8431 This makes sure that the subtree remains an independent subtree and does
8432 not swallow low level entries.
8434 You can also force a different level, either by using a numeric prefix
8435 argument, or by inserting the heading marker by hand. For example, if the
8436 cursor is after \"*****\", then the tree will be shifted to level 5.
8438 If optional TREE is given, use this text instead of the kill ring.
8440 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8441 move back over whitespace before inserting, and move point to the end of
8442 the inserted text when done.
8444 When REMOVE is non-nil, remove the subtree from the clipboard."
8445 (interactive "P")
8446 (setq tree (or tree (and kill-ring (current-kill 0))))
8447 (unless (org-kill-is-subtree-p tree)
8448 (user-error "%s"
8449 (substitute-command-keys
8450 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8451 (org-with-limited-levels
8452 (let* ((visp (not (outline-invisible-p)))
8453 (txt tree)
8454 (^re_ "\\(\\*+\\)[ \t]*")
8455 (old-level (if (string-match org-outline-regexp-bol txt)
8456 (- (match-end 0) (match-beginning 0) 1)
8457 -1))
8458 (force-level (cond (level (prefix-numeric-value level))
8459 ((and (looking-at "[ \t]*$")
8460 (string-match
8461 "^\\*+$" (buffer-substring
8462 (point-at-bol) (point))))
8463 (- (match-end 0) (match-beginning 0)))
8464 ((and (bolp)
8465 (looking-at org-outline-regexp))
8466 (- (match-end 0) (point) 1))))
8467 (previous-level (save-excursion
8468 (condition-case nil
8469 (progn
8470 (outline-previous-visible-heading 1)
8471 (if (looking-at ^re_)
8472 (- (match-end 0) (match-beginning 0) 1)
8474 (error 1))))
8475 (next-level (save-excursion
8476 (condition-case nil
8477 (progn
8478 (or (looking-at org-outline-regexp)
8479 (outline-next-visible-heading 1))
8480 (if (looking-at ^re_)
8481 (- (match-end 0) (match-beginning 0) 1)
8483 (error 1))))
8484 (new-level (or force-level (max previous-level next-level)))
8485 (shift (if (or (= old-level -1)
8486 (= new-level -1)
8487 (= old-level new-level))
8489 (- new-level old-level)))
8490 (delta (if (> shift 0) -1 1))
8491 (func (if (> shift 0) 'org-demote 'org-promote))
8492 (org-odd-levels-only nil)
8493 beg end newend)
8494 ;; Remove the forced level indicator
8495 (if force-level
8496 (delete-region (point-at-bol) (point)))
8497 ;; Paste
8498 (beginning-of-line (if (bolp) 1 2))
8499 (setq beg (point))
8500 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8501 (insert-before-markers txt)
8502 (unless (string-match "\n\\'" txt) (insert "\n"))
8503 (setq newend (point))
8504 (org-reinstall-markers-in-region beg)
8505 (setq end (point))
8506 (goto-char beg)
8507 (skip-chars-forward " \t\n\r")
8508 (setq beg (point))
8509 (if (and (outline-invisible-p) visp)
8510 (save-excursion (outline-show-heading)))
8511 ;; Shift if necessary
8512 (unless (= shift 0)
8513 (save-restriction
8514 (narrow-to-region beg end)
8515 (while (not (= shift 0))
8516 (org-map-region func (point-min) (point-max))
8517 (setq shift (+ delta shift)))
8518 (goto-char (point-min))
8519 (setq newend (point-max))))
8520 (when (or (org-called-interactively-p 'interactive) for-yank)
8521 (message "Clipboard pasted as level %d subtree" new-level))
8522 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8523 kill-ring
8524 (eq org-subtree-clip (current-kill 0))
8525 org-subtree-clip-folded)
8526 ;; The tree was folded before it was killed/copied
8527 (hide-subtree))
8528 (and for-yank (goto-char newend))
8529 (and remove (setq kill-ring (cdr kill-ring))))))
8531 (defun org-kill-is-subtree-p (&optional txt)
8532 "Check if the current kill is an outline subtree, or a set of trees.
8533 Returns nil if kill does not start with a headline, or if the first
8534 headline level is not the largest headline level in the tree.
8535 So this will actually accept several entries of equal levels as well,
8536 which is OK for `org-paste-subtree'.
8537 If optional TXT is given, check this string instead of the current kill."
8538 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8539 (re (org-get-limited-outline-regexp))
8540 (^re (concat "^" re))
8541 (start-level (and kill
8542 (string-match
8543 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8544 kill)
8545 (- (match-end 2) (match-beginning 2) 1)))
8546 (start (1+ (or (match-beginning 2) -1))))
8547 (if (not start-level)
8548 (progn
8549 nil) ;; does not even start with a heading
8550 (catch 'exit
8551 (while (setq start (string-match ^re kill (1+ start)))
8552 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8553 (throw 'exit nil)))
8554 t))))
8556 (defvar org-markers-to-move nil
8557 "Markers that should be moved with a cut-and-paste operation.
8558 Those markers are stored together with their positions relative to
8559 the start of the region.")
8561 (defun org-save-markers-in-region (beg end)
8562 "Check markers in region.
8563 If these markers are between BEG and END, record their position relative
8564 to BEG, so that after moving the block of text, we can put the markers back
8565 into place.
8566 This function gets called just before an entry or tree gets cut from the
8567 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8568 called immediately, to move the markers with the entries."
8569 (setq org-markers-to-move nil)
8570 (when (featurep 'org-clock)
8571 (org-clock-save-markers-for-cut-and-paste beg end))
8572 (when (featurep 'org-agenda)
8573 (org-agenda-save-markers-for-cut-and-paste beg end)))
8575 (defun org-check-and-save-marker (marker beg end)
8576 "Check if MARKER is between BEG and END.
8577 If yes, remember the marker and the distance to BEG."
8578 (when (and (marker-buffer marker)
8579 (equal (marker-buffer marker) (current-buffer)))
8580 (if (and (>= marker beg) (< marker end))
8581 (push (cons marker (- marker beg)) org-markers-to-move))))
8583 (defun org-reinstall-markers-in-region (beg)
8584 "Move all remembered markers to their position relative to BEG."
8585 (mapc (lambda (x)
8586 (move-marker (car x) (+ beg (cdr x))))
8587 org-markers-to-move)
8588 (setq org-markers-to-move nil))
8590 (defun org-narrow-to-subtree ()
8591 "Narrow buffer to the current subtree."
8592 (interactive)
8593 (save-excursion
8594 (save-match-data
8595 (org-with-limited-levels
8596 (narrow-to-region
8597 (progn (org-back-to-heading t) (point))
8598 (progn (org-end-of-subtree t t)
8599 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8600 (point)))))))
8602 (defun org-narrow-to-block ()
8603 "Narrow buffer to the current block."
8604 (interactive)
8605 (let* ((case-fold-search t)
8606 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8607 "^[ \t]*#\\+end_.*")))
8608 (if blockp
8609 (narrow-to-region (car blockp) (cdr blockp))
8610 (user-error "Not in a block"))))
8612 (defun org-clone-subtree-with-time-shift (n &optional shift)
8613 "Clone the task (subtree) at point N times.
8614 The clones will be inserted as siblings.
8616 In interactive use, the user will be prompted for the number of
8617 clones to be produced. If the entry has a timestamp, the user
8618 will also be prompted for a time shift, which may be a repeater
8619 as used in time stamps, for example `+3d'. To disable this,
8620 you can call the function with a universal prefix argument.
8622 When a valid repeater is given and the entry contains any time
8623 stamps, the clones will become a sequence in time, with time
8624 stamps in the subtree shifted for each clone produced. If SHIFT
8625 is nil or the empty string, time stamps will be left alone. The
8626 ID property of the original subtree is removed.
8628 If the original subtree did contain time stamps with a repeater,
8629 the following will happen:
8630 - the repeater will be removed in each clone
8631 - an additional clone will be produced, with the current, unshifted
8632 date(s) in the entry.
8633 - the original entry will be placed *after* all the clones, with
8634 repeater intact.
8635 - the start days in the repeater in the original entry will be shifted
8636 to past the last clone.
8637 In this way you can spell out a number of instances of a repeating task,
8638 and still retain the repeater to cover future instances of the task."
8639 (interactive "nNumber of clones to produce: ")
8640 (let ((shift
8641 (or shift
8642 (if (and (not (equal current-prefix-arg '(4)))
8643 (save-excursion
8644 (re-search-forward org-ts-regexp-both
8645 (save-excursion
8646 (org-end-of-subtree t)
8647 (point)) t)))
8648 (read-from-minibuffer
8649 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8650 ""))) ;; No time shift
8651 (n-no-remove -1)
8652 (drawer-re org-drawer-regexp)
8653 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8654 beg end template task idprop
8655 shift-n shift-what doshift nmin nmax)
8656 (if (not (and (integerp n) (> n 0)))
8657 (user-error "Invalid number of replications %s" n))
8658 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8659 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8660 shift)))
8661 (user-error "Invalid shift specification %s" shift))
8662 (when doshift
8663 (setq shift-n (string-to-number (match-string 1 shift))
8664 shift-what (cdr (assoc (match-string 2 shift)
8665 '(("d" . day) ("w" . week)
8666 ("m" . month) ("y" . year))))))
8667 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8668 (setq nmin 1 nmax n)
8669 (org-back-to-heading t)
8670 (setq beg (point))
8671 (setq idprop (org-entry-get nil "ID"))
8672 (org-end-of-subtree t t)
8673 (or (bolp) (insert "\n"))
8674 (setq end (point))
8675 (setq template (buffer-substring beg end))
8676 (when (and doshift
8677 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8678 (delete-region beg end)
8679 (setq end beg)
8680 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8681 (goto-char end)
8682 (loop for n from nmin to nmax do
8683 ;; prepare clone
8684 (with-temp-buffer
8685 (insert template)
8686 (org-mode)
8687 (goto-char (point-min))
8688 (org-show-subtree)
8689 (and idprop (if org-clone-delete-id
8690 (org-entry-delete nil "ID")
8691 (org-id-get-create t)))
8692 (unless (= n 0)
8693 (while (re-search-forward org-clock-re nil t)
8694 (kill-whole-line))
8695 (goto-char (point-min))
8696 (while (re-search-forward drawer-re nil t)
8697 (org-remove-empty-drawer-at (point))))
8698 (goto-char (point-min))
8699 (when doshift
8700 (while (re-search-forward org-ts-regexp-both nil t)
8701 (org-timestamp-change (* n shift-n) shift-what))
8702 (unless (= n n-no-remove)
8703 (goto-char (point-min))
8704 (while (re-search-forward org-ts-regexp nil t)
8705 (save-excursion
8706 (goto-char (match-beginning 0))
8707 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8708 (delete-region (match-beginning 1) (match-end 1)))))))
8709 (setq task (buffer-string)))
8710 (insert task))
8711 (goto-char beg)))
8713 ;;; Outline Sorting
8715 (defun org-sort (with-case)
8716 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8717 Optional argument WITH-CASE means sort case-sensitively."
8718 (interactive "P")
8719 (cond
8720 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8721 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8723 (org-call-with-arg 'org-sort-entries with-case))))
8725 (defun org-sort-remove-invisible (s)
8726 "Remove invisible links from string S."
8727 (remove-text-properties 0 (length s) org-rm-props s)
8728 (while (string-match org-bracket-link-regexp s)
8729 (setq s (replace-match (if (match-end 2)
8730 (match-string 3 s)
8731 (match-string 1 s)) t t s)))
8732 (let ((st (format " %s " s)))
8733 (while (string-match org-emph-re st)
8734 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8735 (setq s (substring st 1 -1)))
8738 (defvar org-priority-regexp) ; defined later in the file
8740 (defvar org-after-sorting-entries-or-items-hook nil
8741 "Hook that is run after a bunch of entries or items have been sorted.
8742 When children are sorted, the cursor is in the parent line when this
8743 hook gets called. When a region or a plain list is sorted, the cursor
8744 will be in the first entry of the sorted region/list.")
8746 (defun org-sort-entries
8747 (&optional with-case sorting-type getkey-func compare-func property)
8748 "Sort entries on a certain level of an outline tree.
8749 If there is an active region, the entries in the region are sorted.
8750 Else, if the cursor is before the first entry, sort the top-level items.
8751 Else, the children of the entry at point are sorted.
8753 Sorting can be alphabetically, numerically, by date/time as given by
8754 a time stamp, by a property, by priority order, or by a custom function.
8756 The command prompts for the sorting type unless it has been given to the
8757 function through the SORTING-TYPE argument, which needs to be a character,
8758 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8759 the precise meaning of each character:
8761 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8762 c By creation time, which is assumed to be the first inactive time stamp
8763 at the beginning of a line.
8764 d By deadline date/time.
8765 k By clocking time.
8766 n Numerically, by converting the beginning of the entry/item to a number.
8767 o By order of TODO keywords.
8768 p By priority according to the cookie.
8769 r By the value of a property.
8770 s By scheduled date/time.
8771 t By date/time, either the first active time stamp in the entry, or, if
8772 none exist, by the first inactive one.
8774 Capital letters will reverse the sort order.
8776 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8777 called with point at the beginning of the record. It must return either
8778 a string or a number that should serve as the sorting key for that record.
8780 Comparing entries ignores case by default. However, with an optional argument
8781 WITH-CASE, the sorting considers case as well.
8783 Sorting is done against the visible part of the headlines, it ignores hidden
8784 links.
8786 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8787 (interactive "P")
8788 (let ((case-func (if with-case 'identity 'downcase))
8789 (cmstr
8790 ;; The clock marker is lost when using `sort-subr', let's
8791 ;; store the clocking string.
8792 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8793 (save-excursion
8794 (goto-char org-clock-marker)
8795 (looking-back "^.*") (match-string-no-properties 0))))
8796 start beg end stars re re2
8797 txt what tmp)
8798 ;; Find beginning and end of region to sort
8799 (cond
8800 ((org-region-active-p)
8801 ;; we will sort the region
8802 (setq end (region-end)
8803 what "region")
8804 (goto-char (region-beginning))
8805 (if (not (org-at-heading-p)) (outline-next-heading))
8806 (setq start (point)))
8807 ((or (org-at-heading-p)
8808 (ignore-errors (progn (org-back-to-heading) t)))
8809 ;; we will sort the children of the current headline
8810 (org-back-to-heading)
8811 (setq start (point)
8812 end (progn (org-end-of-subtree t t)
8813 (or (bolp) (insert "\n"))
8814 (when (>= (org-back-over-empty-lines) 1)
8815 (forward-line 1))
8816 (point))
8817 what "children")
8818 (goto-char start)
8819 (show-subtree)
8820 (outline-next-heading))
8822 ;; we will sort the top-level entries in this file
8823 (goto-char (point-min))
8824 (or (org-at-heading-p) (outline-next-heading))
8825 (setq start (point))
8826 (goto-char (point-max))
8827 (beginning-of-line 1)
8828 (when (looking-at ".*?\\S-")
8829 ;; File ends in a non-white line
8830 (end-of-line 1)
8831 (insert "\n"))
8832 (setq end (point-max))
8833 (setq what "top-level")
8834 (goto-char start)
8835 (show-all)))
8837 (setq beg (point))
8838 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8840 (looking-at "\\(\\*+\\)")
8841 (setq stars (match-string 1)
8842 re (concat "^" (regexp-quote stars) " +")
8843 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8844 txt (buffer-substring beg end))
8845 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8846 (if (and (not (equal stars "*")) (string-match re2 txt))
8847 (user-error "Region to sort contains a level above the first entry"))
8849 (unless sorting-type
8850 (message
8851 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8852 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8853 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8854 what)
8855 (setq sorting-type (read-char-exclusive))
8857 (unless getkey-func
8858 (and (= (downcase sorting-type) ?f)
8859 (setq getkey-func
8860 (org-icompleting-read "Sort using function: "
8861 obarray 'fboundp t nil nil))
8862 (setq getkey-func (intern getkey-func))))
8864 (and (= (downcase sorting-type) ?r)
8865 (not property)
8866 (setq property
8867 (org-icompleting-read "Property: "
8868 (mapcar 'list (org-buffer-property-keys t))
8869 nil t))))
8871 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8872 (message "Sorting entries...")
8874 (save-restriction
8875 (narrow-to-region start end)
8876 (let ((dcst (downcase sorting-type))
8877 (case-fold-search nil)
8878 (now (current-time)))
8879 (sort-subr
8880 (/= dcst sorting-type)
8881 ;; This function moves to the beginning character of the "record" to
8882 ;; be sorted.
8883 (lambda nil
8884 (if (re-search-forward re nil t)
8885 (goto-char (match-beginning 0))
8886 (goto-char (point-max))))
8887 ;; This function moves to the last character of the "record" being
8888 ;; sorted.
8889 (lambda nil
8890 (save-match-data
8891 (condition-case nil
8892 (outline-forward-same-level 1)
8893 (error
8894 (goto-char (point-max))))))
8895 ;; This function returns the value that gets sorted against.
8896 (lambda nil
8897 (cond
8898 ((= dcst ?n)
8899 (if (looking-at org-complex-heading-regexp)
8900 (string-to-number (org-sort-remove-invisible (match-string 4)))
8901 nil))
8902 ((= dcst ?a)
8903 (if (looking-at org-complex-heading-regexp)
8904 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8905 nil))
8906 ((= dcst ?k)
8907 (or (get-text-property (point) :org-clock-minutes) 0))
8908 ((= dcst ?t)
8909 (let ((end (save-excursion (outline-next-heading) (point))))
8910 (if (or (re-search-forward org-ts-regexp end t)
8911 (re-search-forward org-ts-regexp-both end t))
8912 (org-time-string-to-seconds (match-string 0))
8913 (org-float-time now))))
8914 ((= dcst ?c)
8915 (let ((end (save-excursion (outline-next-heading) (point))))
8916 (if (re-search-forward
8917 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8918 end t)
8919 (org-time-string-to-seconds (match-string 0))
8920 (org-float-time now))))
8921 ((= dcst ?s)
8922 (let ((end (save-excursion (outline-next-heading) (point))))
8923 (if (re-search-forward org-scheduled-time-regexp end t)
8924 (org-time-string-to-seconds (match-string 1))
8925 (org-float-time now))))
8926 ((= dcst ?d)
8927 (let ((end (save-excursion (outline-next-heading) (point))))
8928 (if (re-search-forward org-deadline-time-regexp end t)
8929 (org-time-string-to-seconds (match-string 1))
8930 (org-float-time now))))
8931 ((= dcst ?p)
8932 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8933 (string-to-char (match-string 2))
8934 org-default-priority))
8935 ((= dcst ?r)
8936 (or (org-entry-get nil property) ""))
8937 ((= dcst ?o)
8938 (if (looking-at org-complex-heading-regexp)
8939 (let* ((m (match-string 2))
8940 (s (if (member m org-done-keywords) '- '+)))
8941 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8942 ((= dcst ?f)
8943 (if getkey-func
8944 (progn
8945 (setq tmp (funcall getkey-func))
8946 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8947 tmp)
8948 (error "Invalid key function `%s'" getkey-func)))
8949 (t (error "Invalid sorting type `%c'" sorting-type))))
8951 (cond
8952 ((= dcst ?a) 'string<)
8953 ((= dcst ?f) compare-func)
8954 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8955 (run-hooks 'org-after-sorting-entries-or-items-hook)
8956 ;; Reset the clock marker if needed
8957 (when cmstr
8958 (save-excursion
8959 (goto-char start)
8960 (search-forward cmstr nil t)
8961 (move-marker org-clock-marker (point))))
8962 (message "Sorting entries...done")))
8964 (defun org-do-sort (table what &optional with-case sorting-type)
8965 "Sort TABLE of WHAT according to SORTING-TYPE.
8966 The user will be prompted for the SORTING-TYPE if the call to this
8967 function does not specify it.
8968 WHAT is only for the prompt, to indicate what is being sorted.
8969 The sorting key will be extracted from the car of the elements of
8970 the table.
8971 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8972 (unless sorting-type
8973 (message
8974 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8975 what)
8976 (setq sorting-type (read-char-exclusive)))
8977 (let ((dcst (downcase sorting-type))
8978 extractfun comparefun)
8979 ;; Define the appropriate functions
8980 (cond
8981 ((= dcst ?n)
8982 (setq extractfun 'string-to-number
8983 comparefun (if (= dcst sorting-type) '< '>)))
8984 ((= dcst ?a)
8985 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8986 (lambda(x) (downcase (org-sort-remove-invisible x))))
8987 comparefun (if (= dcst sorting-type)
8988 'string<
8989 (lambda (a b) (and (not (string< a b))
8990 (not (string= a b)))))))
8991 ((= dcst ?t)
8992 (setq extractfun
8993 (lambda (x)
8994 (cond ((or (string-match org-ts-regexp x)
8995 (string-match org-ts-regexp-both x))
8996 (org-float-time
8997 (org-time-string-to-time (match-string 0 x))))
8998 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
8999 (org-hh:mm-string-to-minutes x))
9000 (t 0)))
9001 comparefun (if (= dcst sorting-type) '< '>)))
9002 (t (error "Invalid sorting type `%c'" sorting-type)))
9004 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
9005 table)
9006 (lambda (a b) (funcall comparefun (car a) (car b))))))
9009 ;;; The orgstruct minor mode
9011 ;; Define a minor mode which can be used in other modes in order to
9012 ;; integrate the org-mode structure editing commands.
9014 ;; This is really a hack, because the org-mode structure commands use
9015 ;; keys which normally belong to the major mode. Here is how it
9016 ;; works: The minor mode defines all the keys necessary to operate the
9017 ;; structure commands, but wraps the commands into a function which
9018 ;; tests if the cursor is currently at a headline or a plain list
9019 ;; item. If that is the case, the structure command is used,
9020 ;; temporarily setting many Org-mode variables like regular
9021 ;; expressions for filling etc. However, when any of those keys is
9022 ;; used at a different location, function uses `key-binding' to look
9023 ;; up if the key has an associated command in another currently active
9024 ;; keymap (minor modes, major mode, global), and executes that
9025 ;; command. There might be problems if any of the keys is otherwise
9026 ;; used as a prefix key.
9028 (defcustom orgstruct-heading-prefix-regexp ""
9029 "Regexp that matches the custom prefix of Org headlines in
9030 orgstruct(++)-mode."
9031 :group 'org
9032 :version "24.4"
9033 :package-version '(Org . "8.3")
9034 :type 'regexp)
9035 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9037 (defcustom orgstruct-setup-hook nil
9038 "Hook run after orgstruct-mode-map is filled."
9039 :group 'org
9040 :version "24.4"
9041 :package-version '(Org . "8.0")
9042 :type 'hook)
9044 (defvar orgstruct-initialized nil)
9046 (defvar org-local-vars nil
9047 "List of local variables, for use by `orgstruct-mode'.")
9049 ;;;###autoload
9050 (define-minor-mode orgstruct-mode
9051 "Toggle the minor mode `orgstruct-mode'.
9052 This mode is for using Org-mode structure commands in other
9053 modes. The following keys behave as if Org-mode were active, if
9054 the cursor is on a headline, or on a plain list item (both as
9055 defined by Org-mode)."
9056 nil " OrgStruct" (make-sparse-keymap)
9057 (funcall (if orgstruct-mode
9058 'add-to-invisibility-spec
9059 'remove-from-invisibility-spec)
9060 '(outline . t))
9061 (when orgstruct-mode
9062 (org-load-modules-maybe)
9063 (unless orgstruct-initialized
9064 (orgstruct-setup)
9065 (setq orgstruct-initialized t))))
9067 ;;;###autoload
9068 (defun turn-on-orgstruct ()
9069 "Unconditionally turn on `orgstruct-mode'."
9070 (orgstruct-mode 1))
9072 (defvar org-fb-vars nil)
9073 (make-variable-buffer-local 'org-fb-vars)
9074 (defun orgstruct++-mode (&optional arg)
9075 "Toggle `orgstruct-mode', the enhanced version of it.
9076 In addition to setting orgstruct-mode, this also exports all
9077 indentation and autofilling variables from org-mode into the
9078 buffer. It will also recognize item context in multiline items."
9079 (interactive "P")
9080 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9081 (if (< arg 1)
9082 (progn (orgstruct-mode -1)
9083 (mapc (lambda(v)
9084 (org-set-local (car v)
9085 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9086 org-fb-vars))
9087 (orgstruct-mode 1)
9088 (setq org-fb-vars nil)
9089 (unless org-local-vars
9090 (setq org-local-vars (org-get-local-variables)))
9091 (let (var val)
9092 (mapc
9093 (lambda (x)
9094 (when (string-match
9095 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9096 (symbol-name (car x)))
9097 (setq var (car x) val (nth 1 x))
9098 (push (list var `(quote ,(eval var))) org-fb-vars)
9099 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9100 org-local-vars)
9101 (org-set-local 'orgstruct-is-++ t))))
9103 (defvar orgstruct-is-++ nil
9104 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9105 (make-variable-buffer-local 'orgstruct-is-++)
9107 ;;;###autoload
9108 (defun turn-on-orgstruct++ ()
9109 "Unconditionally turn on `orgstruct++-mode'."
9110 (orgstruct++-mode 1))
9112 (defun orgstruct-error ()
9113 "Error when there is no default binding for a structure key."
9114 (interactive)
9115 (funcall (if (fboundp 'user-error)
9116 'user-error
9117 'error)
9118 "This key has no function outside structure elements"))
9120 (defun orgstruct-setup ()
9121 "Setup orgstruct keymap."
9122 (dolist (cell '((org-demote . t)
9123 (org-metaleft . t)
9124 (org-metaright . t)
9125 (org-promote . t)
9126 (org-shiftmetaleft . t)
9127 (org-shiftmetaright . t)
9128 org-backward-element
9129 org-backward-heading-same-level
9130 org-ctrl-c-ret
9131 org-ctrl-c-minus
9132 org-ctrl-c-star
9133 org-cycle
9134 org-forward-heading-same-level
9135 org-insert-heading
9136 org-insert-heading-respect-content
9137 org-kill-note-or-show-branches
9138 org-mark-subtree
9139 org-meta-return
9140 org-metadown
9141 org-metaup
9142 org-narrow-to-subtree
9143 org-promote-subtree
9144 org-reveal
9145 org-shiftdown
9146 org-shiftleft
9147 org-shiftmetadown
9148 org-shiftmetaup
9149 org-shiftright
9150 org-shifttab
9151 org-shifttab
9152 org-shiftup
9153 org-show-subtree
9154 org-sort
9155 org-up-element
9156 outline-demote
9157 outline-next-visible-heading
9158 outline-previous-visible-heading
9159 outline-promote
9160 outline-up-heading
9161 show-children))
9162 (let ((f (or (car-safe cell) cell))
9163 (disable-when-heading-prefix (cdr-safe cell)))
9164 (when (fboundp f)
9165 (let ((new-bindings))
9166 (dolist (binding (nconc (where-is-internal f org-mode-map)
9167 (where-is-internal f outline-mode-map)))
9168 (push binding new-bindings)
9169 ;; TODO use local-function-key-map
9170 (dolist (rep '(("<tab>" . "TAB")
9171 ("<return>" . "RET")
9172 ("<escape>" . "ESC")
9173 ("<delete>" . "DEL")))
9174 (setq binding (read-kbd-macro
9175 (let ((case-fold-search))
9176 (replace-regexp-in-string
9177 (regexp-quote (cdr rep))
9178 (car rep)
9179 (key-description binding)))))
9180 (pushnew binding new-bindings :test 'equal)))
9181 (dolist (binding new-bindings)
9182 (let ((key (lookup-key orgstruct-mode-map binding)))
9183 (when (or (not key) (numberp key))
9184 (ignore-errors
9185 (org-defkey orgstruct-mode-map
9186 binding
9187 (orgstruct-make-binding
9188 f binding disable-when-heading-prefix))))))))))
9189 (run-hooks 'orgstruct-setup-hook))
9191 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9192 "Create a function for binding in the structure minor mode.
9193 FUN is the command to call inside a table. KEY is the key that
9194 should be checked in for a command to execute outside of tables.
9195 Non-nil `disable-when-heading-prefix' means to disable the command
9196 if `orgstruct-heading-prefix-regexp' is not empty."
9197 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9198 (let ((nname name)
9199 (i 0))
9200 (while (fboundp (intern nname))
9201 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9202 (setq name (intern nname)))
9203 (eval
9204 (let ((bindings '((org-heading-regexp
9205 (concat "^"
9206 orgstruct-heading-prefix-regexp
9207 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9208 (org-outline-regexp
9209 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9210 (org-outline-regexp-bol
9211 (concat "^" org-outline-regexp))
9212 (outline-regexp org-outline-regexp)
9213 (outline-heading-end-regexp "\n")
9214 (outline-level 'org-outline-level)
9215 (outline-heading-alist))))
9216 `(defun ,name (arg)
9217 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9218 "Outside of structure, run the binding of `"
9219 (key-description key) "'."
9220 (when disable-when-heading-prefix
9221 (concat
9222 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9223 "back to the default binding due to limitations of Org's implementation of\n"
9224 "`" (symbol-name fun) "'.")))
9225 (interactive "p")
9226 (let* ((disable
9227 ,(and disable-when-heading-prefix
9228 '(not (string= orgstruct-heading-prefix-regexp ""))))
9229 (fallback
9230 (or disable
9231 (not
9232 (let* ,bindings
9233 (org-context-p 'headline 'item
9234 ,(when (memq fun
9235 '(org-insert-heading
9236 org-insert-heading-respect-content
9237 org-meta-return))
9238 '(when orgstruct-is-++
9239 'item-body))))))))
9240 (if fallback
9241 (let* ((orgstruct-mode)
9242 (binding
9243 (let ((key ,key))
9244 (catch 'exit
9245 (dolist
9246 (rep
9247 '(nil
9248 ("<\\([^>]*\\)tab>" . "\\1TAB")
9249 ("<\\([^>]*\\)return>" . "\\1RET")
9250 ("<\\([^>]*\\)escape>" . "\\1ESC")
9251 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9252 nil)
9253 (when rep
9254 (setq key (read-kbd-macro
9255 (let ((case-fold-search))
9256 (replace-regexp-in-string
9257 (car rep)
9258 (cdr rep)
9259 (key-description key))))))
9260 (when (key-binding key)
9261 (throw 'exit (key-binding key))))))))
9262 (if (keymapp binding)
9263 (org-set-transient-map binding)
9264 (let ((func (or binding
9265 (unless disable
9266 'orgstruct-error))))
9267 (when func
9268 (call-interactively func)))))
9269 (org-run-like-in-org-mode
9270 (lambda ()
9271 (interactive)
9272 (let* ,bindings
9273 (call-interactively ',fun)))))))))
9274 name))
9276 (defun org-contextualize-keys (alist contexts)
9277 "Return valid elements in ALIST depending on CONTEXTS.
9279 `org-agenda-custom-commands' or `org-capture-templates' are the
9280 values used for ALIST, and `org-agenda-custom-commands-contexts'
9281 or `org-capture-templates-contexts' are the associated contexts
9282 definitions."
9283 (let ((contexts
9284 ;; normalize contexts
9285 (mapcar
9286 (lambda(c) (cond ((listp (cadr c))
9287 (list (car c) (car c) (cadr c)))
9288 ((string= "" (cadr c))
9289 (list (car c) (car c) (caddr c)))
9290 (t c))) contexts))
9291 (a alist) c r s)
9292 ;; loop over all commands or templates
9293 (while (setq c (pop a))
9294 (let (vrules repl)
9295 (cond
9296 ((not (assoc (car c) contexts))
9297 (push c r))
9298 ((and (assoc (car c) contexts)
9299 (setq vrules (org-contextualize-validate-key
9300 (car c) contexts)))
9301 (mapc (lambda (vr)
9302 (when (not (equal (car vr) (cadr vr)))
9303 (setq repl vr))) vrules)
9304 (if (not repl) (push c r)
9305 (push (cadr repl) s)
9306 (push
9307 (cons (car c)
9308 (cdr (or (assoc (cadr repl) alist)
9309 (error "Undefined key `%s' as contextual replacement for `%s'"
9310 (cadr repl) (car c)))))
9311 r))))))
9312 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9313 (delq
9315 (delete-dups
9316 (mapcar (lambda (x)
9317 (let ((tpl (car x)))
9318 (when (not (delq
9320 (mapcar (lambda(y)
9321 (equal y tpl)) s))) x)))
9322 (reverse r))))))
9324 (defun org-contextualize-validate-key (key contexts)
9325 "Check CONTEXTS for agenda or capture KEY."
9326 (let (r rr res)
9327 (while (setq r (pop contexts))
9328 (mapc
9329 (lambda (rr)
9330 (when
9331 (and (equal key (car r))
9332 (if (functionp rr) (funcall rr)
9333 (or (and (eq (car rr) 'in-file)
9334 (buffer-file-name)
9335 (string-match (cdr rr) (buffer-file-name)))
9336 (and (eq (car rr) 'in-mode)
9337 (string-match (cdr rr) (symbol-name major-mode)))
9338 (and (eq (car rr) 'in-buffer)
9339 (string-match (cdr rr) (buffer-name)))
9340 (when (and (eq (car rr) 'not-in-file)
9341 (buffer-file-name))
9342 (not (string-match (cdr rr) (buffer-file-name))))
9343 (when (eq (car rr) 'not-in-mode)
9344 (not (string-match (cdr rr) (symbol-name major-mode))))
9345 (when (eq (car rr) 'not-in-buffer)
9346 (not (string-match (cdr rr) (buffer-name)))))))
9347 (push r res)))
9348 (car (last r))))
9349 (delete-dups (delq nil res))))
9351 (defun org-context-p (&rest contexts)
9352 "Check if local context is any of CONTEXTS.
9353 Possible values in the list of contexts are `table', `headline', and `item'."
9354 (let ((pos (point)))
9355 (goto-char (point-at-bol))
9356 (prog1 (or (and (memq 'table contexts)
9357 (looking-at "[ \t]*|"))
9358 (and (memq 'headline contexts)
9359 (looking-at org-outline-regexp))
9360 (and (memq 'item contexts)
9361 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9362 (and (memq 'item-body contexts)
9363 (org-in-item-p)))
9364 (goto-char pos))))
9366 (defun org-get-local-variables ()
9367 "Return a list of all local variables in an Org mode buffer."
9368 (let (varlist)
9369 (with-current-buffer (get-buffer-create "*Org tmp*")
9370 (erase-buffer)
9371 (org-mode)
9372 (setq varlist (buffer-local-variables)))
9373 (kill-buffer "*Org tmp*")
9374 (delq nil
9375 (mapcar
9376 (lambda (x)
9377 (setq x
9378 (if (symbolp x)
9379 (list x)
9380 (list (car x) (cdr x))))
9381 (if (and (not (get (car x) 'org-state))
9382 (string-match
9383 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9384 (symbol-name (car x))))
9385 x nil))
9386 varlist))))
9388 (defun org-clone-local-variables (from-buffer &optional regexp)
9389 "Clone local variables from FROM-BUFFER.
9390 Optional argument REGEXP selects variables to clone."
9391 (mapc
9392 (lambda (pair)
9393 (and (symbolp (car pair))
9394 (or (null regexp)
9395 (string-match regexp (symbol-name (car pair))))
9396 (set (make-local-variable (car pair))
9397 (cdr pair))))
9398 (buffer-local-variables from-buffer)))
9400 ;;;###autoload
9401 (defun org-run-like-in-org-mode (cmd)
9402 "Run a command, pretending that the current buffer is in Org-mode.
9403 This will temporarily bind local variables that are typically bound in
9404 Org-mode to the values they have in Org-mode, and then interactively
9405 call CMD."
9406 (org-load-modules-maybe)
9407 (unless org-local-vars
9408 (setq org-local-vars (org-get-local-variables)))
9409 (let (binds)
9410 (dolist (var org-local-vars)
9411 (when (or (not (boundp (car var)))
9412 (eq (symbol-value (car var))
9413 (default-value (car var))))
9414 (push (list (car var) `(quote ,(cadr var))) binds)))
9415 (eval `(let ,binds
9416 (call-interactively (quote ,cmd))))))
9418 (defun org-get-category (&optional pos force-refresh)
9419 "Get the category applying to position POS."
9420 (save-match-data
9421 (if force-refresh (org-refresh-category-properties))
9422 (let ((pos (or pos (point))))
9423 (or (get-text-property pos 'org-category)
9424 (progn (org-refresh-category-properties)
9425 (get-text-property pos 'org-category))))))
9427 ;;; Refresh properties
9429 (defun org-refresh-properties (dprop tprop)
9430 "Refresh buffer text properties.
9431 DPROP is the drawer property and TPROP is either the
9432 corresponding text property to set, or an alist with each element
9433 being a text property (as a symbol) and a function to apply to
9434 the value of the drawer property."
9435 (let ((case-fold-search t)
9436 (inhibit-read-only t))
9437 (org-with-silent-modifications
9438 (save-excursion
9439 (save-restriction
9440 (widen)
9441 (goto-char (point-min))
9442 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9443 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9445 (defun org-refresh-property (tprop p)
9446 "Refresh the buffer text property TPROP from the drawer property P.
9447 The refresh happens only for the current tree (not subtree)."
9448 (save-excursion
9449 (org-back-to-heading t)
9450 ;; tprop is a text property symbol
9451 (if (symbolp tprop)
9452 (put-text-property
9453 (point) (or (outline-next-heading) (point-max)) tprop p)
9454 ;; tprop is an alist with (properties . function) elements
9455 (mapc (lambda(al)
9456 (save-excursion
9457 (put-text-property
9458 (point-at-bol) (or (outline-next-heading) (point-max))
9459 (car al)
9460 (funcall (cdr al) p))))
9461 tprop))))
9463 (defun org-refresh-category-properties ()
9464 "Refresh category text properties in the buffer."
9465 (let ((case-fold-search t)
9466 (inhibit-read-only t)
9467 (def-cat (cond
9468 ((null org-category)
9469 (if buffer-file-name
9470 (file-name-sans-extension
9471 (file-name-nondirectory buffer-file-name))
9472 "???"))
9473 ((symbolp org-category) (symbol-name org-category))
9474 (t org-category)))
9475 beg end cat pos optionp)
9476 (org-with-silent-modifications
9477 (save-excursion
9478 (save-restriction
9479 (widen)
9480 (goto-char (point-min))
9481 (put-text-property (point) (point-max) 'org-category def-cat)
9482 (while (re-search-forward
9483 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9484 (setq pos (match-end 0)
9485 optionp (equal (char-after (match-beginning 0)) ?#)
9486 cat (org-trim (match-string 2)))
9487 (if optionp
9488 (setq beg (point-at-bol) end (point-max))
9489 (org-back-to-heading t)
9490 (setq beg (point) end (org-end-of-subtree t t)))
9491 (put-text-property beg end 'org-category cat)
9492 (goto-char pos)))))))
9494 (defun org-refresh-stats-properties ()
9495 "Refresh stats text properties in the buffer."
9496 (let (stats)
9497 (org-with-silent-modifications
9498 (save-excursion
9499 (save-restriction
9500 (widen)
9501 (goto-char (point-min))
9502 (while (re-search-forward
9503 (concat org-outline-regexp-bol ".*"
9504 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9505 nil t)
9506 (setq stats (cond ((equal (match-string 3) "0") 0)
9507 ((match-string 2)
9508 (/ (* (string-to-number (match-string 2)) 100)
9509 (string-to-number (match-string 3))))
9510 (t (string-to-number (match-string 1)))))
9511 (org-back-to-heading t)
9512 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9513 'org-stats stats)))))))
9515 (defun org-refresh-effort-properties ()
9516 "Refresh effort properties"
9517 (org-refresh-properties
9518 org-effort-property
9519 '((effort . identity)
9520 (effort-minutes . org-duration-string-to-minutes))))
9522 ;;;; Link Stuff
9524 ;;; Link abbreviations
9526 (defun org-link-expand-abbrev (link)
9527 "Apply replacements as defined in `org-link-abbrev-alist'."
9528 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9529 (let* ((key (match-string 1 link))
9530 (as (or (assoc key org-link-abbrev-alist-local)
9531 (assoc key org-link-abbrev-alist)))
9532 (tag (and (match-end 2) (match-string 3 link)))
9533 rpl)
9534 (if (not as)
9535 link
9536 (setq rpl (cdr as))
9537 (cond
9538 ((symbolp rpl) (funcall rpl tag))
9539 ((string-match "%(\\([^)]+\\))" rpl)
9540 (replace-match
9541 (save-match-data
9542 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9543 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9544 ((string-match "%h" rpl)
9545 (replace-match (url-hexify-string (or tag "")) t t rpl))
9546 (t (concat rpl tag)))))
9547 link))
9549 ;;; Storing and inserting links
9551 (defvar org-insert-link-history nil
9552 "Minibuffer history for links inserted with `org-insert-link'.")
9554 (defvar org-stored-links nil
9555 "Contains the links stored with `org-store-link'.")
9557 (defvar org-store-link-plist nil
9558 "Plist with info about the most recently link created with `org-store-link'.")
9560 (defvar org-link-protocols nil
9561 "Link protocols added to Org-mode using `org-add-link-type'.")
9563 (defvar org-store-link-functions nil
9564 "List of functions that are called to create and store a link.
9565 Each function will be called in turn until one returns a non-nil
9566 value. Each function should check if it is responsible for creating
9567 this link (for example by looking at the major mode).
9568 If not, it must exit and return nil.
9569 If yes, it should return a non-nil value after a calling
9570 `org-store-link-props' with a list of properties and values.
9571 Special properties are:
9573 :type The link prefix, like \"http\". This must be given.
9574 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9575 This is obligatory as well.
9576 :description Optional default description for the second pair
9577 of brackets in an Org-mode link. The user can still change
9578 this when inserting this link into an Org-mode buffer.
9580 In addition to these, any additional properties can be specified
9581 and then used in capture templates.")
9583 (defun org-add-link-type (type &optional follow export)
9584 "Add TYPE to the list of `org-link-types'.
9585 Re-compute all regular expressions depending on `org-link-types'
9587 FOLLOW and EXPORT are two functions.
9589 FOLLOW should take the link path as the single argument and do whatever
9590 is necessary to follow the link, for example find a file or display
9591 a mail message.
9593 EXPORT should format the link path for export to one of the export formats.
9594 It should be a function accepting three arguments:
9596 path the path of the link, the text after the prefix (like \"http:\")
9597 desc the description of the link, if any, or a description added by
9598 org-export-normalize-links if there is none
9599 format the export format, a symbol like `html' or `latex' or `ascii'..
9601 The function may use the FORMAT information to return different values
9602 depending on the format. The return value will be put literally into
9603 the exported file. If the return value is nil, this means Org should
9604 do what it normally does with links which do not have EXPORT defined.
9606 Org-mode has a built-in default for exporting links. If you are happy with
9607 this default, there is no need to define an export function for the link
9608 type. For a simple example of an export function, see `org-bbdb.el'."
9609 (add-to-list 'org-link-types type t)
9610 (org-make-link-regexps)
9611 (if (assoc type org-link-protocols)
9612 (setcdr (assoc type org-link-protocols) (list follow export))
9613 (push (list type follow export) org-link-protocols)))
9615 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9616 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9618 ;;;###autoload
9619 (defun org-store-link (arg)
9620 "\\<org-mode-map>Store an org-link to the current location.
9621 This link is added to `org-stored-links' and can later be inserted
9622 into an org-buffer with \\[org-insert-link].
9624 For some link types, a prefix arg is interpreted.
9625 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9626 For file links, arg negates `org-context-in-file-links'.
9628 A double prefix arg force skipping storing functions that are not
9629 part of Org's core.
9631 A triple prefix arg force storing a link for each line in the
9632 active region."
9633 (interactive "P")
9634 (org-load-modules-maybe)
9635 (if (and (equal arg '(64)) (org-region-active-p))
9636 (save-excursion
9637 (let ((end (region-end)))
9638 (goto-char (region-beginning))
9639 (set-mark (point))
9640 (while (< (point-at-eol) end)
9641 (move-end-of-line 1) (activate-mark)
9642 (let (current-prefix-arg)
9643 (call-interactively 'org-store-link))
9644 (move-beginning-of-line 2)
9645 (set-mark (point)))))
9646 (org-with-limited-levels
9647 (setq org-store-link-plist nil)
9648 (let (link cpltxt desc description search
9649 txt custom-id agenda-link sfuns sfunsn)
9650 (cond
9652 ;; Store a link using an external link type
9653 ((and (not (equal arg '(16)))
9654 (setq sfuns
9655 (delq
9656 nil (mapcar (lambda (f)
9657 (let (fs) (if (funcall f) (push f fs))))
9658 org-store-link-functions))
9659 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9660 (or (and (cdr sfuns)
9661 (funcall (intern
9662 (completing-read
9663 "Which function for creating the link? "
9664 sfunsn nil t (car sfunsn)))))
9665 (funcall (caar sfuns)))
9666 (setq link (plist-get org-store-link-plist :link)
9667 desc (or (plist-get org-store-link-plist
9668 :description) link))))
9670 ;; Store a link from a source code buffer
9671 ((org-src-edit-buffer-p)
9672 (let (label gc)
9673 (while (or (not label)
9674 (save-excursion
9675 (save-restriction
9676 (widen)
9677 (goto-char (point-min))
9678 (re-search-forward
9679 (regexp-quote (format org-coderef-label-format label))
9680 nil t))))
9681 (when label (message "Label exists already") (sit-for 2))
9682 (setq label (read-string "Code line label: " label)))
9683 (end-of-line 1)
9684 (setq link (format org-coderef-label-format label))
9685 (setq gc (- 79 (length link)))
9686 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9687 (insert link)
9688 (setq link (concat "(" label ")") desc nil)))
9690 ;; We are in the agenda, link to referenced location
9691 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9692 (let ((m (or (get-text-property (point) 'org-hd-marker)
9693 (get-text-property (point) 'org-marker))))
9694 (when m
9695 (org-with-point-at m
9696 (setq agenda-link
9697 (if (org-called-interactively-p 'any)
9698 (call-interactively 'org-store-link)
9699 (org-store-link nil)))))))
9701 ((eq major-mode 'calendar-mode)
9702 (let ((cd (calendar-cursor-to-date)))
9703 (setq link
9704 (format-time-string
9705 (car org-time-stamp-formats)
9706 (apply 'encode-time
9707 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9708 nil nil nil))))
9709 (org-store-link-props :type "calendar" :date cd)))
9711 ((eq major-mode 'help-mode)
9712 (setq link (concat "help:" (save-excursion
9713 (goto-char (point-min))
9714 (looking-at "^[^ ]+")
9715 (match-string 0))))
9716 (org-store-link-props :type "help"))
9718 ((eq major-mode 'w3-mode)
9719 (setq cpltxt (if (and (buffer-name)
9720 (not (string-match "Untitled" (buffer-name))))
9721 (buffer-name)
9722 (url-view-url t))
9723 link (url-view-url t))
9724 (org-store-link-props :type "w3" :url (url-view-url t)))
9726 ((eq major-mode 'image-mode)
9727 (setq cpltxt (concat "file:"
9728 (abbreviate-file-name buffer-file-name))
9729 link cpltxt)
9730 (org-store-link-props :type "image" :file buffer-file-name))
9732 ;; In dired, store a link to the file of the current line
9733 ((derived-mode-p 'dired-mode)
9734 (let ((file (dired-get-filename nil t)))
9735 (setq file (if file
9736 (abbreviate-file-name
9737 (expand-file-name (dired-get-filename nil t)))
9738 ;; otherwise, no file so use current directory.
9739 default-directory))
9740 (setq cpltxt (concat "file:" file)
9741 link cpltxt)))
9743 ((setq search (run-hook-with-args-until-success
9744 'org-create-file-search-functions))
9745 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9746 "::" search))
9747 (setq cpltxt (or description link)))
9749 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9750 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9751 (cond
9752 ;; Store a link using the target at point
9753 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9754 (setq cpltxt
9755 (concat "file:"
9756 (abbreviate-file-name
9757 (buffer-file-name (buffer-base-buffer)))
9758 "::" (match-string 1))
9759 link cpltxt))
9760 ((and (featurep 'org-id)
9761 (or (eq org-id-link-to-org-use-id t)
9762 (and (org-called-interactively-p 'any)
9763 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9764 (and (eq org-id-link-to-org-use-id
9765 'create-if-interactive-and-no-custom-id)
9766 (not custom-id))))
9767 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9768 ;; Store a link using the ID at point
9769 (setq link (condition-case nil
9770 (prog1 (org-id-store-link)
9771 (setq desc (or (plist-get org-store-link-plist
9772 :description)
9773 "")))
9774 (error
9775 ;; Probably before first headline, link only to file
9776 (concat "file:"
9777 (abbreviate-file-name
9778 (buffer-file-name (buffer-base-buffer))))))))
9780 ;; Just link to current headline
9781 (setq cpltxt (concat "file:"
9782 (abbreviate-file-name
9783 (buffer-file-name (buffer-base-buffer)))))
9784 ;; Add a context search string
9785 (when (org-xor org-context-in-file-links arg)
9786 (let* ((ee (org-element-at-point))
9787 (et (org-element-type ee))
9788 (ev (plist-get (cadr ee) :value))
9789 (ek (plist-get (cadr ee) :key))
9790 (eok (and (stringp ek) (string-match "name" ek))))
9791 (setq txt (cond
9792 ((org-at-heading-p) nil)
9793 ((and (eq et 'keyword) eok) ev)
9794 ((org-region-active-p)
9795 (buffer-substring (region-beginning) (region-end)))))
9796 (when (or (null txt) (string-match "\\S-" txt))
9797 (setq cpltxt
9798 (concat cpltxt "::"
9799 (condition-case nil
9800 (org-make-org-heading-search-string txt)
9801 (error "")))
9802 desc (or (and (eq et 'keyword) eok ev)
9803 (nth 4 (ignore-errors (org-heading-components)))
9804 "NONE")))))
9805 (if (string-match "::\\'" cpltxt)
9806 (setq cpltxt (substring cpltxt 0 -2)))
9807 (setq link cpltxt))))
9809 ((buffer-file-name (buffer-base-buffer))
9810 ;; Just link to this file here.
9811 (setq cpltxt (concat "file:"
9812 (abbreviate-file-name
9813 (buffer-file-name (buffer-base-buffer)))))
9814 ;; Add a context string.
9815 (when (org-xor org-context-in-file-links arg)
9816 (setq txt (if (org-region-active-p)
9817 (buffer-substring (region-beginning) (region-end))
9818 (buffer-substring (point-at-bol) (point-at-eol))))
9819 ;; Only use search option if there is some text.
9820 (when (string-match "\\S-" txt)
9821 (setq cpltxt
9822 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9823 desc "NONE")))
9824 (setq link cpltxt))
9826 ((org-called-interactively-p 'interactive)
9827 (user-error "No method for storing a link from this buffer"))
9829 (t (setq link nil)))
9831 ;; We're done setting link and desc, clean up
9832 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9833 (setq link (or link cpltxt)
9834 desc (or desc cpltxt))
9835 (cond ((equal desc "NONE") (setq desc nil))
9836 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9837 (let ((d0 (match-string 3 desc))
9838 (p0 (match-string 5 desc)))
9839 (setq desc
9840 (replace-regexp-in-string
9841 org-bracket-link-regexp
9842 (concat (or p0 d0)
9843 (if (equal (length (match-string 0 desc))
9844 (length desc)) "*" "")) desc)))))
9846 ;; Return the link
9847 (if (not (and (or (org-called-interactively-p 'any)
9848 executing-kbd-macro) link))
9849 (or agenda-link (and link (org-make-link-string link desc)))
9850 (push (list link desc) org-stored-links)
9851 (message "Stored: %s" (or desc link))
9852 (when custom-id
9853 (setq link (concat "file:" (abbreviate-file-name
9854 (buffer-file-name)) "::#" custom-id))
9855 (push (list link desc) org-stored-links))
9856 (car org-stored-links))))))
9858 (defun org-store-link-props (&rest plist)
9859 "Store link properties, extract names and addresses."
9860 (let (x adr)
9861 (when (setq x (plist-get plist :from))
9862 (setq adr (mail-extract-address-components x))
9863 (setq plist (plist-put plist :fromname (car adr)))
9864 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9865 (when (setq x (plist-get plist :to))
9866 (setq adr (mail-extract-address-components x))
9867 (setq plist (plist-put plist :toname (car adr)))
9868 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9869 (let ((from (plist-get plist :from))
9870 (to (plist-get plist :to)))
9871 (when (and from to org-from-is-user-regexp)
9872 (setq plist
9873 (plist-put plist :fromto
9874 (if (string-match org-from-is-user-regexp from)
9875 (concat "to %t")
9876 (concat "from %f"))))))
9877 (setq org-store-link-plist plist))
9879 (defun org-add-link-props (&rest plist)
9880 "Add these properties to the link property list."
9881 (let (key value)
9882 (while plist
9883 (setq key (pop plist) value (pop plist))
9884 (setq org-store-link-plist
9885 (plist-put org-store-link-plist key value)))))
9887 (defun org-email-link-description (&optional fmt)
9888 "Return the description part of an email link.
9889 This takes information from `org-store-link-plist' and formats it
9890 according to FMT (default from `org-email-link-description-format')."
9891 (setq fmt (or fmt org-email-link-description-format))
9892 (let* ((p org-store-link-plist)
9893 (to (plist-get p :toaddress))
9894 (from (plist-get p :fromaddress))
9895 (table
9896 (list
9897 (cons "%c" (plist-get p :fromto))
9898 (cons "%F" (plist-get p :from))
9899 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9900 (cons "%T" (plist-get p :to))
9901 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9902 (cons "%s" (plist-get p :subject))
9903 (cons "%d" (plist-get p :date))
9904 (cons "%m" (plist-get p :message-id)))))
9905 (when (string-match "%c" fmt)
9906 ;; Check if the user wrote this message
9907 (if (and org-from-is-user-regexp from to
9908 (save-match-data (string-match org-from-is-user-regexp from)))
9909 (setq fmt (replace-match "to %t" t t fmt))
9910 (setq fmt (replace-match "from %f" t t fmt))))
9911 (org-replace-escapes fmt table)))
9913 (defun org-make-org-heading-search-string (&optional string)
9914 "Make search string for the current headline or STRING."
9915 (let ((s (or string
9916 (and (derived-mode-p 'org-mode)
9917 (save-excursion
9918 (org-back-to-heading t)
9919 (org-element-property :raw-value (org-element-at-point))))))
9920 (lines org-context-in-file-links))
9921 (or string (setq s (concat "*" s))) ; Add * for headlines
9922 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9923 (when (and string (integerp lines) (> lines 0))
9924 (let ((slines (org-split-string s "\n")))
9925 (when (< lines (length slines))
9926 (setq s (mapconcat
9927 'identity
9928 (reverse (nthcdr (- (length slines) lines)
9929 (reverse slines))) "\n")))))
9930 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9932 (defun org-make-link-string (link &optional description)
9933 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9934 (unless (string-match "\\S-" link)
9935 (error "Empty link"))
9936 (when (and description
9937 (stringp description)
9938 (not (string-match "\\S-" description)))
9939 (setq description nil))
9940 (when (stringp description)
9941 ;; Remove brackets from the description, they are fatal.
9942 (while (string-match "\\[" description)
9943 (setq description (replace-match "{" t t description)))
9944 (while (string-match "\\]" description)
9945 (setq description (replace-match "}" t t description))))
9946 (when (equal link description)
9947 ;; No description needed, it is identical
9948 (setq description nil))
9949 (when (and (not description)
9950 (not (string-match (org-image-file-name-regexp) link))
9951 (not (equal link (org-link-escape link))))
9952 (setq description (org-extract-attributes link)))
9953 (setq link
9954 (cond ((string-match (org-image-file-name-regexp) link) link)
9955 ((string-match org-link-types-re link)
9956 (concat (match-string 1 link)
9957 (org-link-escape (substring link (match-end 1)))))
9958 (t (org-link-escape link))))
9959 (concat "[[" link "]"
9960 (if description (concat "[" description "]") "")
9961 "]"))
9963 (defconst org-link-escape-chars
9964 ;;%20 %5B %5D
9965 '(?\ ?\[ ?\])
9966 "List of characters that should be escaped in a link when stored to Org.
9967 This is the list that is used for internal purposes.")
9969 (defconst org-link-escape-chars-browser
9970 ;;%20 %22
9971 '(?\ ?\")
9972 "List of characters to be escaped before handing over to the browser.
9973 If you consider using this constant then you probably want to use
9974 the function `org-link-escape-browser' instead. See there why
9975 this constant is a candidate to be removed once Org drops support
9976 for Emacs 24.1 and 24.2.")
9978 (defun org-link-escape (text &optional table merge)
9979 "Return percent escaped representation of TEXT.
9980 TEXT is a string with the text to escape.
9981 Optional argument TABLE is a list with characters that should be
9982 escaped. When nil, `org-link-escape-chars' is used.
9983 If optional argument MERGE is set, merge TABLE into
9984 `org-link-escape-chars'."
9985 ;; Don't escape chars in internal links
9986 (if (string-match "^\\*[[:alnum:]]+" text)
9987 text
9988 (cond
9989 ((and table merge)
9990 (mapc (lambda (defchr)
9991 (unless (member defchr table)
9992 (setq table (cons defchr table))))
9993 org-link-escape-chars))
9994 ((null table)
9995 (setq table org-link-escape-chars)))
9996 (mapconcat
9997 (lambda (char)
9998 (if (or (member char table)
9999 (and (or (< char 32) (= char ?\%) (> char 126))
10000 org-url-hexify-p))
10001 (mapconcat (lambda (sequence-element)
10002 (format "%%%.2X" sequence-element))
10003 (or (encode-coding-char char 'utf-8)
10004 (error "Unable to percent escape character: %s"
10005 (char-to-string char))) "")
10006 (char-to-string char))) text "")))
10008 (defun org-link-escape-browser (text)
10009 "Escape some characters before handing over to the browser.
10010 This function is a candidate to be removed together with the
10011 constant `org-link-escape-chars-browser' once Org drops support
10012 for Emacs 24.1 and 24.2. All calls to this function will have to
10013 be replaced with `url-encode-url' which is available since Emacs
10014 24.3.1."
10015 ;; Example with the Org link
10016 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10017 ;; to open the browser with +subject:"Release 8.2" filled into the
10018 ;; query field: In this case the variable TEXT contains the
10019 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10020 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10021 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10022 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10023 (if (fboundp 'url-encode-url)
10024 (url-encode-url text)
10025 (if (org-string-match-p
10026 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10027 text)
10028 (org-link-escape text org-link-escape-chars-browser)
10029 text)))
10031 (defun org-link-unescape (str)
10032 "Unhex hexified Unicode strings as returned from the JavaScript function
10033 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10034 (unless (and (null str) (string= "" str))
10035 (let ((pos 0) (case-fold-search t) unhexed)
10036 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10037 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10038 (setq str (replace-match unhexed t t str))
10039 (setq pos (+ pos (length unhexed))))))
10040 str)
10042 (defun org-link-unescape-compound (hex)
10043 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10044 Note: this function also decodes single byte encodings like
10045 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10046 (save-match-data
10047 (let* ((bytes (cdr (split-string hex "%")))
10048 (ret "")
10049 (eat 0)
10050 (sum 0))
10051 (while bytes
10052 (let* ((val (string-to-number (pop bytes) 16))
10053 (shift-xor
10054 (if (= 0 eat)
10055 (cond
10056 ((>= val 252) (cons 6 252))
10057 ((>= val 248) (cons 5 248))
10058 ((>= val 240) (cons 4 240))
10059 ((>= val 224) (cons 3 224))
10060 ((>= val 192) (cons 2 192))
10061 (t (cons 0 0)))
10062 (cons 6 128))))
10063 (if (>= val 192) (setq eat (car shift-xor)))
10064 (setq val (logxor val (cdr shift-xor)))
10065 (setq sum (+ (lsh sum (car shift-xor)) val))
10066 (if (> eat 0) (setq eat (- eat 1)))
10067 (cond
10068 ((= 0 eat) ;multi byte
10069 (setq ret (concat ret (org-char-to-string sum)))
10070 (setq sum 0))
10071 ((not bytes) ; single byte(s)
10072 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10073 ret)))
10075 (defun org-link-unescape-single-byte-sequence (hex)
10076 "Unhexify hex-encoded single byte character sequences."
10077 (mapconcat (lambda (byte)
10078 (char-to-string (string-to-number byte 16)))
10079 (cdr (split-string hex "%")) ""))
10081 (defun org-xor (a b)
10082 "Exclusive or."
10083 (if a (not b) b))
10085 (defun org-fixup-message-id-for-http (s)
10086 "Replace special characters in a message id, so it can be used in an http query."
10087 (when (string-match "%" s)
10088 (setq s (mapconcat (lambda (c)
10089 (if (eq c ?%)
10090 "%25"
10091 (char-to-string c)))
10092 s "")))
10093 (while (string-match "<" s)
10094 (setq s (replace-match "%3C" t t s)))
10095 (while (string-match ">" s)
10096 (setq s (replace-match "%3E" t t s)))
10097 (while (string-match "@" s)
10098 (setq s (replace-match "%40" t t s)))
10101 (defun org-link-prettify (link)
10102 "Return a human-readable representation of LINK.
10103 The car of LINK must be a raw link.
10104 The cdr of LINK must be either a link description or nil."
10105 (let ((desc (or (cadr link) "<no description>")))
10106 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10107 "<" (car link) ">")))
10109 ;;;###autoload
10110 (defun org-insert-link-global ()
10111 "Insert a link like Org-mode does.
10112 This command can be called in any mode to insert a link in Org-mode syntax."
10113 (interactive)
10114 (org-load-modules-maybe)
10115 (org-run-like-in-org-mode 'org-insert-link))
10117 (defun org-insert-all-links (arg &optional pre post)
10118 "Insert all links in `org-stored-links'.
10119 When a universal prefix, do not delete the links from `org-stored-links'.
10120 When `ARG' is a number, insert the last N link(s).
10121 `PRE' and `POST' are optional arguments to define a string to
10122 prepend or to append."
10123 (interactive "P")
10124 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10125 (links (copy-seq org-stored-links))
10126 (pr (or pre "- "))
10127 (po (or post "\n"))
10128 (cnt 1) l)
10129 (if (null org-stored-links)
10130 (message "No link to insert")
10131 (while (and (or (listp arg) (>= arg cnt))
10132 (setq l (if (listp arg)
10133 (pop links)
10134 (pop org-stored-links))))
10135 (setq cnt (1+ cnt))
10136 (insert pr)
10137 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10138 (insert po)))))
10140 (defun org-insert-last-stored-link (arg)
10141 "Insert the last link stored in `org-stored-links'."
10142 (interactive "p")
10143 (org-insert-all-links arg "" "\n"))
10145 (defun org-link-fontify-links-to-this-file ()
10146 "Fontify links to the current file in `org-stored-links'."
10147 (let ((f (buffer-file-name)) a b)
10148 (setq a (mapcar (lambda(l)
10149 (let ((ll (car l)))
10150 (when (and (string-match "^file:\\(.+\\)::" ll)
10151 (equal f (expand-file-name (match-string 1 ll))))
10152 ll)))
10153 org-stored-links))
10154 (when (featurep 'org-id)
10155 (setq b (mapcar (lambda(l)
10156 (let ((ll (car l)))
10157 (when (and (string-match "^id:\\(.+\\)$" ll)
10158 (equal f (expand-file-name
10159 (or (org-id-find-id-file
10160 (match-string 1 ll)) ""))))
10161 ll)))
10162 org-stored-links)))
10163 (mapcar (lambda(l)
10164 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10165 (delq nil (append a b)))))
10167 (defvar org-link-links-in-this-file nil)
10168 (defun org-insert-link (&optional complete-file link-location default-description)
10169 "Insert a link. At the prompt, enter the link.
10171 Completion can be used to insert any of the link protocol prefixes like
10172 http or ftp in use.
10174 The history can be used to select a link previously stored with
10175 `org-store-link'. When the empty string is entered (i.e. if you just
10176 press RET at the prompt), the link defaults to the most recently
10177 stored link. As SPC triggers completion in the minibuffer, you need to
10178 use M-SPC or C-q SPC to force the insertion of a space character.
10180 You will also be prompted for a description, and if one is given, it will
10181 be displayed in the buffer instead of the link.
10183 If there is already a link at point, this command will allow you to edit link
10184 and description parts.
10186 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10187 be selected using completion. The path to the file will be relative to the
10188 current directory if the file is in the current directory or a subdirectory.
10189 Otherwise, the link will be the absolute path as completed in the minibuffer
10190 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10191 option `org-link-file-path-type'.
10193 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10194 the current directory or below.
10196 With three \\[universal-argument] prefixes, negate the meaning of
10197 `org-keep-stored-link-after-insertion'.
10199 If `org-make-link-description-function' is non-nil, this function will be
10200 called with the link target, and the result will be the default
10201 link description.
10203 If the LINK-LOCATION parameter is non-nil, this value will be
10204 used as the link location instead of reading one interactively.
10206 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10207 be used as the default description."
10208 (interactive "P")
10209 (let* ((wcf (current-window-configuration))
10210 (origbuf (current-buffer))
10211 (region (if (org-region-active-p)
10212 (buffer-substring (region-beginning) (region-end))))
10213 (remove (and region (list (region-beginning) (region-end))))
10214 (desc region)
10215 tmphist ; byte-compile incorrectly complains about this
10216 (link link-location)
10217 (abbrevs org-link-abbrev-alist-local)
10218 entry file all-prefixes auto-desc)
10219 (cond
10220 (link-location) ; specified by arg, just use it.
10221 ((org-in-regexp org-bracket-link-regexp 1)
10222 ;; We do have a link at point, and we are going to edit it.
10223 (setq remove (list (match-beginning 0) (match-end 0)))
10224 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10225 (setq link (read-string "Link: "
10226 (org-link-unescape
10227 (org-match-string-no-properties 1)))))
10228 ((or (org-in-regexp org-angle-link-re)
10229 (org-in-regexp org-plain-link-re))
10230 ;; Convert to bracket link
10231 (setq remove (list (match-beginning 0) (match-end 0))
10232 link (read-string "Link: "
10233 (org-remove-angle-brackets (match-string 0)))))
10234 ((member complete-file '((4) (16)))
10235 ;; Completing read for file names.
10236 (setq link (org-file-complete-link complete-file)))
10238 ;; Read link, with completion for stored links.
10239 (org-link-fontify-links-to-this-file)
10240 (org-switch-to-buffer-other-window "*Org Links*")
10241 (with-current-buffer "*Org Links*"
10242 (erase-buffer)
10243 (insert "Insert a link.
10244 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10245 (when org-stored-links
10246 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10247 (insert (mapconcat 'org-link-prettify
10248 (reverse org-stored-links) "\n")))
10249 (goto-char (point-min)))
10250 (let ((cw (selected-window)))
10251 (select-window (get-buffer-window "*Org Links*" 'visible))
10252 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10253 (unless (pos-visible-in-window-p (point-max))
10254 (org-fit-window-to-buffer))
10255 (and (window-live-p cw) (select-window cw)))
10256 ;; Fake a link history, containing the stored links.
10257 (setq tmphist (append (mapcar 'car org-stored-links)
10258 org-insert-link-history))
10259 (setq all-prefixes (append (mapcar 'car abbrevs)
10260 (mapcar 'car org-link-abbrev-alist)
10261 org-link-types))
10262 (unwind-protect
10263 (progn
10264 (setq link
10265 (org-completing-read
10266 "Link: "
10267 (append
10268 (mapcar (lambda (x) (concat x ":"))
10269 all-prefixes)
10270 (mapcar 'car org-stored-links))
10271 nil nil nil
10272 'tmphist
10273 (caar org-stored-links)))
10274 (if (not (string-match "\\S-" link))
10275 (user-error "No link selected"))
10276 (mapc (lambda(l)
10277 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10278 org-stored-links)
10279 (if (or (member link all-prefixes)
10280 (and (equal ":" (substring link -1))
10281 (member (substring link 0 -1) all-prefixes)
10282 (setq link (substring link 0 -1))))
10283 (setq link (with-current-buffer origbuf
10284 (org-link-try-special-completion link)))))
10285 (set-window-configuration wcf)
10286 (kill-buffer "*Org Links*"))
10287 (setq entry (assoc link org-stored-links))
10288 (or entry (push link org-insert-link-history))
10289 (setq desc (or desc (nth 1 entry)))))
10291 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10292 (not org-keep-stored-link-after-insertion))
10293 (setq org-stored-links (delq (assoc link org-stored-links)
10294 org-stored-links)))
10296 (if (and (string-match org-plain-link-re link)
10297 (not (string-match org-ts-regexp link)))
10298 ;; URL-like link, normalize the use of angular brackets.
10299 (setq link (org-remove-angle-brackets link)))
10301 ;; Check if we are linking to the current file with a search
10302 ;; option If yes, simplify the link by using only the search
10303 ;; option.
10304 (when (and buffer-file-name
10305 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10306 (let* ((path (match-string 1 link))
10307 (case-fold-search nil)
10308 (search (match-string 2 link)))
10309 (save-match-data
10310 (if (equal (file-truename buffer-file-name) (file-truename path))
10311 ;; We are linking to this same file, with a search option
10312 (setq link search)))))
10314 ;; Check if we can/should use a relative path. If yes, simplify the link
10315 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10316 (let* ((type (match-string 1 link))
10317 (path (match-string 2 link))
10318 (origpath path)
10319 (case-fold-search nil))
10320 (cond
10321 ((or (eq org-link-file-path-type 'absolute)
10322 (equal complete-file '(16)))
10323 (setq path (abbreviate-file-name (expand-file-name path))))
10324 ((eq org-link-file-path-type 'noabbrev)
10325 (setq path (expand-file-name path)))
10326 ((eq org-link-file-path-type 'relative)
10327 (setq path (file-relative-name path)))
10329 (save-match-data
10330 (if (string-match (concat "^" (regexp-quote
10331 (expand-file-name
10332 (file-name-as-directory
10333 default-directory))))
10334 (expand-file-name path))
10335 ;; We are linking a file with relative path name.
10336 (setq path (substring (expand-file-name path)
10337 (match-end 0)))
10338 (setq path (abbreviate-file-name (expand-file-name path)))))))
10339 (setq link (concat type path))
10340 (if (equal desc origpath)
10341 (setq desc path))))
10343 (if org-make-link-description-function
10344 (setq desc
10345 (or (condition-case nil
10346 (funcall org-make-link-description-function link desc)
10347 (error (progn (message "Can't get link description from `%s'"
10348 (symbol-name org-make-link-description-function))
10349 (sit-for 2) nil)))
10350 (read-string "Description: " default-description)))
10351 (if default-description (setq desc default-description)
10352 (setq desc (or (and auto-desc desc)
10353 (read-string "Description: " desc)))))
10355 (unless (string-match "\\S-" desc) (setq desc nil))
10356 (if remove (apply 'delete-region remove))
10357 (insert (org-make-link-string link desc))))
10359 (defun org-link-try-special-completion (type)
10360 "If there is completion support for link type TYPE, offer it."
10361 (let ((fun (intern (concat "org-" type "-complete-link"))))
10362 (if (functionp fun)
10363 (funcall fun)
10364 (read-string "Link (no completion support): " (concat type ":")))))
10366 (defun org-file-complete-link (&optional arg)
10367 "Create a file link using completion."
10368 (let (file link)
10369 (setq file (org-iread-file-name "File: "))
10370 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10371 (pwd1 (file-name-as-directory (abbreviate-file-name
10372 (expand-file-name ".")))))
10373 (cond
10374 ((equal arg '(16))
10375 (setq link (concat
10376 "file:"
10377 (abbreviate-file-name (expand-file-name file)))))
10378 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10379 (setq link (concat "file:" (match-string 1 file))))
10380 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10381 (expand-file-name file))
10382 (setq link (concat
10383 "file:" (match-string 1 (expand-file-name file)))))
10384 (t (setq link (concat "file:" file)))))
10385 link))
10387 (defun org-iread-file-name (&rest args)
10388 "Read-file-name using `ido-mode' speedup if available.
10389 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10390 See `read-file-name' for a description of parameters."
10391 (org-without-partial-completion
10392 (if (and org-completion-use-ido
10393 (fboundp 'ido-read-file-name)
10394 (boundp 'ido-mode) ido-mode
10395 (listp (second args)))
10396 (let ((ido-enter-matching-directory nil))
10397 (apply 'ido-read-file-name args))
10398 (apply 'read-file-name args))))
10400 (defun org-completing-read (&rest args)
10401 "Completing-read with SPACE being a normal character."
10402 (let ((enable-recursive-minibuffers t)
10403 (minibuffer-local-completion-map
10404 (copy-keymap minibuffer-local-completion-map)))
10405 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10406 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10407 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10408 (apply 'org-icompleting-read args)))
10410 (defun org-completing-read-no-i (&rest args)
10411 (let (org-completion-use-ido org-completion-use-iswitchb)
10412 (apply 'org-completing-read args)))
10414 (defun org-iswitchb-completing-read (prompt choices &rest args)
10415 "Use iswitch as a completing-read replacement to choose from choices.
10416 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10417 from."
10418 (let* ((iswitchb-use-virtual-buffers nil)
10419 (iswitchb-make-buflist-hook
10420 (lambda ()
10421 (setq iswitchb-temp-buflist choices))))
10422 (iswitchb-read-buffer prompt)))
10424 (defun org-icompleting-read (&rest args)
10425 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10426 (org-without-partial-completion
10427 (if (and org-completion-use-ido
10428 (fboundp 'ido-completing-read)
10429 (boundp 'ido-mode) ido-mode
10430 (listp (second args)))
10431 (let ((ido-enter-matching-directory nil))
10432 (apply 'ido-completing-read (concat (car args))
10433 (if (consp (car (nth 1 args)))
10434 (mapcar 'car (nth 1 args))
10435 (nth 1 args))
10436 (cddr args)))
10437 (if (and org-completion-use-iswitchb
10438 (boundp 'iswitchb-mode) iswitchb-mode
10439 (listp (second args)))
10440 (apply 'org-iswitchb-completing-read (concat (car args))
10441 (if (consp (car (nth 1 args)))
10442 (mapcar 'car (nth 1 args))
10443 (nth 1 args))
10444 (cddr args))
10445 (apply 'completing-read args)))))
10447 (defun org-extract-attributes (s)
10448 "Extract the attributes cookie from a string and set as text property."
10449 (let (a attr (start 0) key value)
10450 (save-match-data
10451 (when (string-match "{{\\([^}]+\\)}}$" s)
10452 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10453 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10454 (setq key (match-string 1 a) value (match-string 2 a)
10455 start (match-end 0)
10456 attr (plist-put attr (intern key) value))))
10457 (org-add-props s nil 'org-attr attr))
10460 ;;; Opening/following a link
10462 (defvar org-link-search-failed nil)
10464 (defvar org-open-link-functions nil
10465 "Hook for functions finding a plain text link.
10466 These functions must take a single argument, the link content.
10467 They will be called for links that look like [[link text][description]]
10468 when LINK TEXT does not have a protocol like \"http:\" and does not look
10469 like a filename (e.g. \"./blue.png\").
10471 These functions will be called *before* Org attempts to resolve the
10472 link by doing text searches in the current buffer - so if you want a
10473 link \"[[target]]\" to still find \"<<target>>\", your function should
10474 handle this as a special case.
10476 When the function does handle the link, it must return a non-nil value.
10477 If it decides that it is not responsible for this link, it must return
10478 nil to indicate that that Org-mode can continue with other options
10479 like exact and fuzzy text search.")
10481 (defun org-next-link (&optional search-backward)
10482 "Move forward to the next link.
10483 If the link is in hidden text, expose it."
10484 (interactive "P")
10485 (when (and org-link-search-failed (eq this-command last-command))
10486 (goto-char (point-min))
10487 (message "Link search wrapped back to beginning of buffer"))
10488 (setq org-link-search-failed nil)
10489 (let* ((pos (point))
10490 (ct (org-context))
10491 (a (assoc :link ct))
10492 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10493 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10494 ((looking-at org-any-link-re)
10495 ;; Don't stay stuck at link without an org-link face
10496 (forward-char (if search-backward -1 1))))
10497 (if (funcall srch-fun org-any-link-re nil t)
10498 (progn
10499 (goto-char (match-beginning 0))
10500 (if (outline-invisible-p) (org-show-context)))
10501 (goto-char pos)
10502 (setq org-link-search-failed t)
10503 (message "No further link found"))))
10505 (defun org-previous-link ()
10506 "Move backward to the previous link.
10507 If the link is in hidden text, expose it."
10508 (interactive)
10509 (funcall 'org-next-link t))
10511 (defun org-translate-link (s)
10512 "Translate a link string if a translation function has been defined."
10513 (if (and org-link-translation-function
10514 (fboundp org-link-translation-function)
10515 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10516 (progn
10517 (setq s (funcall org-link-translation-function
10518 (match-string 1 s) (match-string 2 s)))
10519 (concat (car s) ":" (cdr s)))
10522 (defun org-translate-link-from-planner (type path)
10523 "Translate a link from Emacs Planner syntax so that Org can follow it.
10524 This is still an experimental function, your mileage may vary."
10525 (cond
10526 ((member type '("http" "https" "news" "ftp"))
10527 ;; standard Internet links are the same.
10528 nil)
10529 ((and (equal type "irc") (string-match "^//" path))
10530 ;; Planner has two / at the beginning of an irc link, we have 1.
10531 ;; We should have zero, actually....
10532 (setq path (substring path 1)))
10533 ((and (equal type "lisp") (string-match "^/" path))
10534 ;; Planner has a slash, we do not.
10535 (setq type "elisp" path (substring path 1)))
10536 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10537 ;; A typical message link. Planner has the id after the final slash,
10538 ;; we separate it with a hash mark
10539 (setq path (concat (match-string 1 path) "#"
10540 (org-remove-angle-brackets (match-string 2 path))))))
10541 (cons type path))
10543 (defun org-find-file-at-mouse (ev)
10544 "Open file link or URL at mouse."
10545 (interactive "e")
10546 (mouse-set-point ev)
10547 (org-open-at-point 'in-emacs))
10549 (defun org-open-at-mouse (ev)
10550 "Open file link or URL at mouse.
10551 See the docstring of `org-open-file' for details."
10552 (interactive "e")
10553 (mouse-set-point ev)
10554 (if (eq major-mode 'org-agenda-mode)
10555 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10556 (org-open-at-point))
10558 (defvar org-window-config-before-follow-link nil
10559 "The window configuration before following a link.
10560 This is saved in case the need arises to restore it.")
10562 (defvar org-open-link-marker (make-marker)
10563 "Marker pointing to the location where `org-open-at-point' was called.")
10565 ;;;###autoload
10566 (defun org-open-at-point-global ()
10567 "Follow a link like Org-mode does.
10568 This command can be called in any mode to follow a link that has
10569 Org-mode syntax."
10570 (interactive)
10571 (org-run-like-in-org-mode 'org-open-at-point))
10573 ;;;###autoload
10574 (defun org-open-link-from-string (s &optional arg reference-buffer)
10575 "Open a link in the string S, as if it was in Org-mode."
10576 (interactive "sLink: \nP")
10577 (let ((reference-buffer (or reference-buffer (current-buffer))))
10578 (with-temp-buffer
10579 (let ((org-inhibit-startup (not reference-buffer)))
10580 (org-mode)
10581 (insert s)
10582 (goto-char (point-min))
10583 (when reference-buffer
10584 (setq org-link-abbrev-alist-local
10585 (with-current-buffer reference-buffer
10586 org-link-abbrev-alist-local)))
10587 (org-open-at-point arg reference-buffer)))))
10589 (defvar org-open-at-point-functions nil
10590 "Hook that is run when following a link at point.
10592 Functions in this hook must return t if they identify and follow
10593 a link at point. If they don't find anything interesting at point,
10594 they must return nil.")
10596 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10597 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10598 (defun org-open-at-point (&optional arg reference-buffer)
10599 "Open link, timestamp, footnote or tags at point.
10601 When point is on a link, follow it. Normally, files will be
10602 opened by an appropriate application. If the optional prefix
10603 argument ARG is non-nil, Emacs will visit the file. With
10604 a double prefix argument, try to open outside of Emacs, in the
10605 application the system uses for this file type.
10607 When point is on a timestamp, open the agenda at the day
10608 specified.
10610 When point is a footnote definition, move to the first reference
10611 found. If it is on a reference, move to the associated
10612 definition.
10614 When point is on a headline, display a list of every link in the
10615 entry, so it is possible to pick one, or all, of them. If point
10616 is on a tag, call `org-tags-view' instead.
10618 When optional argument REFERENCE-BUFFER is non-nil, it should
10619 specify a buffer from where the link search should happen. This
10620 is used internally by `org-open-link-from-string'.
10622 On top of syntactically correct links, this function will open
10623 the link at point in comments or comment blocks and the first
10624 link in a property drawer line."
10625 (interactive "P")
10626 ;; On a code block, open block's results.
10627 (unless (call-interactively 'org-babel-open-src-block-result)
10628 (org-load-modules-maybe)
10629 (move-marker org-open-link-marker (point))
10630 (setq org-window-config-before-follow-link (current-window-configuration))
10631 (org-remove-occur-highlights nil nil t)
10632 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10633 (let* ((context (org-element-context)) type value)
10634 ;; On an unsupported type, check if point is contained within
10635 ;; a support one.
10636 (while (and (not (memq (setq type (org-element-type context))
10637 '(comment comment-block
10638 headline inlinetask link
10639 footnote-definition footnote-reference
10640 node-property timestamp)))
10641 (setq context (org-element-property :parent context))))
10642 (setq value (org-element-property :value context))
10643 (cond
10644 ;; Blank lines at the beginning of buffer: bail out.
10645 ((not context) (user-error "No link found"))
10646 ;; Exception n°1: links in property drawers
10647 ((eq type 'node-property)
10648 (org-open-link-from-string
10649 (and (string-match org-any-link-re value)
10650 (match-string-no-properties 0 value))))
10651 ;; Exception n°2: links in comments.
10652 ((memq type '(comment comment-block))
10653 (save-excursion
10654 (skip-chars-forward "\\S-" (point-at-eol))
10655 (let ((string-rear (replace-regexp-in-string
10656 "^[ \t]*# [ \t]*" ""
10657 (buffer-substring (point) (line-beginning-position))))
10658 (string-front (buffer-substring (point) (line-end-position))))
10659 (with-temp-buffer
10660 (let ((org-inhibit-startup t)) (org-mode))
10661 (insert value)
10662 (goto-char (point-min))
10663 (when (and (search-forward string-rear nil t)
10664 (search-forward string-front (line-end-position) t))
10665 (goto-char (match-beginning 0))
10666 (org-open-at-point)
10667 (when (string= string-rear "") (forward-char)))))))
10668 ;; On a headline or an inlinetask, but not on a timestamp,
10669 ;; a link, a footnote reference or on tags.
10670 ((and (memq type '(headline inlinetask))
10671 ;; Not on tags.
10672 (progn (save-excursion (beginning-of-line)
10673 (looking-at org-complex-heading-regexp))
10674 (or (not (match-beginning 5))
10675 (< (point) (match-beginning 5)))))
10676 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10677 (links (car data))
10678 (links-end (cdr data)))
10679 (if links
10680 (dolist (link (if (stringp links) (list links) links))
10681 (search-forward link nil links-end)
10682 (goto-char (match-beginning 0))
10683 (org-open-at-point))
10684 (require 'org-attach)
10685 (org-attach-reveal 'if-exists))))
10686 ;; Do nothing on white spaces after an object, unless point
10687 ;; is right after it.
10688 ((> (point)
10689 (save-excursion
10690 (goto-char (org-element-property :end context))
10691 (skip-chars-backward " \t")
10692 (point)))
10693 (user-error "No link found"))
10694 ((eq type 'timestamp) (org-follow-timestamp-link))
10695 ;; On tags within a headline or an inlinetask.
10696 ((and (memq type '(headline inlinetask))
10697 (progn (save-excursion (beginning-of-line)
10698 (looking-at org-complex-heading-regexp))
10699 (and (match-beginning 5)
10700 (>= (point) (match-beginning 5)))))
10701 (org-tags-view arg (substring (match-string 5) 0 -1)))
10702 ((eq type 'link)
10703 (let ((type (org-element-property :type context))
10704 (path (org-link-unescape (org-element-property :path context))))
10705 ;; Switch back to REFERENCE-BUFFER needed when called in
10706 ;; a temporary buffer through `org-open-link-from-string'.
10707 (with-current-buffer (or reference-buffer (current-buffer))
10708 (cond
10709 ((equal type "file")
10710 (if (string-match "[*?{]" (file-name-nondirectory path))
10711 (dired path)
10712 ;; Look into `org-link-protocols' in order to find
10713 ;; a DEDICATED-FUNCTION to open file. The function
10714 ;; will be applied on raw link instead of parsed
10715 ;; link due to the limitation in `org-add-link-type'
10716 ;; ("open" function called with a single argument).
10717 ;; If no such function is found, fallback to
10718 ;; `org-open-file'.
10720 ;; Note : "file+emacs" and "file+sys" types are
10721 ;; hard-coded in order to escape the previous
10722 ;; limitation.
10723 (let* ((option (org-element-property :search-option context))
10724 (app (org-element-property :application context))
10725 (dedicated-function
10726 (nth 1 (assoc app org-link-protocols))))
10727 (if dedicated-function
10728 (funcall dedicated-function
10729 (concat path
10730 (and option (concat "::" option))))
10731 (apply 'org-open-file
10732 path
10733 (cond (arg)
10734 ((equal app "emacs") 'emacs)
10735 ((equal app "sys") 'system))
10736 (cond ((not option) nil)
10737 ((org-string-match-p "\\`[0-9]+\\'" option)
10738 (list (string-to-number option)))
10739 (t (list nil
10740 (org-link-unescape option)))))))))
10741 ((assoc type org-link-protocols)
10742 (funcall (nth 1 (assoc type org-link-protocols)) path))
10743 ((equal type "help")
10744 (let ((f-or-v (intern path)))
10745 (cond ((fboundp f-or-v) (describe-function f-or-v))
10746 ((boundp f-or-v) (describe-variable f-or-v))
10747 (t (error "Not a known function or variable")))))
10748 ((member type '("http" "https" "ftp" "mailto" "news"))
10749 (browse-url (org-link-escape-browser (concat type ":" path))))
10750 ((equal type "doi")
10751 (browse-url
10752 (org-link-escape-browser (concat org-doi-server-url path))))
10753 ((equal type "message") (browse-url (concat type ":" path)))
10754 ((equal type "shell")
10755 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10756 (cmd path))
10757 (if (or (and (org-string-nw-p
10758 org-confirm-shell-link-not-regexp)
10759 (string-match
10760 org-confirm-shell-link-not-regexp cmd))
10761 (not org-confirm-shell-link-function)
10762 (funcall org-confirm-shell-link-function
10763 (format "Execute \"%s\" in shell? "
10764 (org-add-props cmd nil
10765 'face 'org-warning))))
10766 (progn
10767 (message "Executing %s" cmd)
10768 (shell-command cmd buf)
10769 (when (featurep 'midnight)
10770 (setq clean-buffer-list-kill-buffer-names
10771 (cons buf
10772 clean-buffer-list-kill-buffer-names))))
10773 (user-error "Abort"))))
10774 ((equal type "elisp")
10775 (let ((cmd path))
10776 (if (or (and (org-string-nw-p
10777 org-confirm-elisp-link-not-regexp)
10778 (org-string-match-p
10779 org-confirm-elisp-link-not-regexp cmd))
10780 (not org-confirm-elisp-link-function)
10781 (funcall org-confirm-elisp-link-function
10782 (format "Execute \"%s\" as elisp? "
10783 (org-add-props cmd nil
10784 'face 'org-warning))))
10785 (message "%s => %s" cmd
10786 (if (eq (string-to-char cmd) ?\()
10787 (eval (read cmd))
10788 (call-interactively (read cmd))))
10789 (user-error "Abort"))))
10790 ((equal type "id")
10791 (require 'ord-id)
10792 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10793 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10794 (unless (run-hook-with-args-until-success
10795 'org-open-link-functions path)
10796 (if (not arg) (org-mark-ring-push)
10797 (switch-to-buffer-other-window
10798 (org-get-buffer-for-internal-link (current-buffer))))
10799 (let ((cmd `(org-link-search
10800 ,(if (member type '("custom-id" "coderef"))
10801 (org-element-property :raw-link context)
10802 path)
10803 ,(cond ((equal arg '(4)) 'occur)
10804 ((equal arg '(16)) 'org-occur))
10805 ,(org-element-property :begin context))))
10806 (condition-case nil
10807 (let ((org-link-search-inhibit-query t))
10808 (eval cmd))
10809 (error (progn (widen) (eval cmd)))))))
10810 (t (browse-url-at-point))))))
10811 ;; On a footnote reference or at a footnote definition's label.
10812 ((or (eq type 'footnote-reference)
10813 (and (eq type 'footnote-definition)
10814 (save-excursion
10815 ;; Do not validate action when point is on the
10816 ;; spaces right after the footnote label, in
10817 ;; order to be on par with behaviour on links.
10818 (skip-chars-forward " \t")
10819 (let ((begin
10820 (org-element-property :contents-begin context)))
10821 (if begin (< (point) begin)
10822 (= (org-element-property :post-affiliated context)
10823 (line-beginning-position)))))))
10824 (org-footnote-action))
10825 (t (user-error "No link found")))))
10826 (move-marker org-open-link-marker nil)
10827 (run-hook-with-args 'org-follow-link-hook)))
10829 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10830 "Offer links in the current entry and return the selected link.
10831 If there is only one link, return it.
10832 If NTH is an integer, return the NTH link found.
10833 If ZERO is a string, check also this string for a link, and if
10834 there is one, return it."
10835 (with-current-buffer buffer
10836 (save-excursion
10837 (save-restriction
10838 (widen)
10839 (goto-char marker)
10840 (let ((cnt ?0)
10841 (in-emacs (if (integerp nth) nil nth))
10842 have-zero end links link c)
10843 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10844 (push (match-string 0 zero) links)
10845 (setq cnt (1- cnt) have-zero t))
10846 (save-excursion
10847 (org-back-to-heading t)
10848 (setq end (save-excursion (outline-next-heading) (point)))
10849 (while (re-search-forward org-any-link-re end t)
10850 (push (match-string 0) links))
10851 (setq links (org-uniquify (reverse links))))
10852 (cond
10853 ((null links)
10854 (message "No links"))
10855 ((equal (length links) 1)
10856 (setq link (car links)))
10857 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10858 (setq link (nth (if have-zero nth (1- nth)) links)))
10859 (t ; we have to select a link
10860 (save-excursion
10861 (save-window-excursion
10862 (delete-other-windows)
10863 (with-output-to-temp-buffer "*Select Link*"
10864 (mapc (lambda (l)
10865 (if (not (string-match org-bracket-link-regexp l))
10866 (princ (format "[%c] %s\n" (incf cnt)
10867 (org-remove-angle-brackets l)))
10868 (if (match-end 3)
10869 (princ (format "[%c] %s (%s)\n" (incf cnt)
10870 (match-string 3 l) (match-string 1 l)))
10871 (princ (format "[%c] %s\n" (incf cnt)
10872 (match-string 1 l))))))
10873 links))
10874 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10875 (message "Select link to open, RET to open all:")
10876 (setq c (read-char-exclusive))
10877 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10878 (when (equal c ?q) (user-error "Abort"))
10879 (if (equal c ?\C-m)
10880 (setq link links)
10881 (setq nth (- c ?0))
10882 (if have-zero (setq nth (1+ nth)))
10883 (unless (and (integerp nth) (>= (length links) nth))
10884 (user-error "Invalid link selection"))
10885 (setq link (nth (1- nth) links)))))
10886 (cons link end))))))
10888 ;; TODO: These functions are deprecated since `org-open-at-point'
10889 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10890 (defun org-open-file-with-system (path)
10891 "Open file at PATH using the system way of opening it."
10892 (org-open-file path 'system))
10893 (defun org-open-file-with-emacs (path)
10894 "Open file at PATH in Emacs."
10895 (org-open-file path 'emacs))
10898 ;;; File search
10900 (defvar org-create-file-search-functions nil
10901 "List of functions to construct the right search string for a file link.
10902 These functions are called in turn with point at the location to
10903 which the link should point.
10905 A function in the hook should first test if it would like to
10906 handle this file type, for example by checking the `major-mode'
10907 or the file extension. If it decides not to handle this file, it
10908 should just return nil to give other functions a chance. If it
10909 does handle the file, it must return the search string to be used
10910 when following the link. The search string will be part of the
10911 file link, given after a double colon, and `org-open-at-point'
10912 will automatically search for it. If special measures must be
10913 taken to make the search successful, another function should be
10914 added to the companion hook `org-execute-file-search-functions',
10915 which see.
10917 A function in this hook may also use `setq' to set the variable
10918 `description' to provide a suggestion for the descriptive text to
10919 be used for this link when it gets inserted into an Org-mode
10920 buffer with \\[org-insert-link].")
10922 (defvar org-execute-file-search-functions nil
10923 "List of functions to execute a file search triggered by a link.
10925 Functions added to this hook must accept a single argument, the
10926 search string that was part of the file link, the part after the
10927 double colon. The function must first check if it would like to
10928 handle this search, for example by checking the `major-mode' or
10929 the file extension. If it decides not to handle this search, it
10930 should just return nil to give other functions a chance. If it
10931 does handle the search, it must return a non-nil value to keep
10932 other functions from trying.
10934 Each function can access the current prefix argument through the
10935 variable `current-prefix-arg'. Note that a single prefix is used
10936 to force opening a link in Emacs, so it may be good to only use a
10937 numeric or double prefix to guide the search function.
10939 In case this is needed, a function in this hook can also restore
10940 the window configuration before `org-open-at-point' was called using:
10942 (set-window-configuration org-window-config-before-follow-link)")
10944 (defun org-link-search (s &optional type avoid-pos stealth)
10945 "Search for a link search option.
10946 If S is surrounded by forward slashes, it is interpreted as a
10947 regular expression. In org-mode files, this will create an `org-occur'
10948 sparse tree. In ordinary files, `occur' will be used to list matches.
10949 If the current buffer is in `dired-mode', grep will be used to search
10950 in all files. If AVOID-POS is given, ignore matches near that position.
10952 When optional argument STEALTH is non-nil, do not modify
10953 visibility around point, thus ignoring
10954 `org-show-hierarchy-above', `org-show-following-heading' and
10955 `org-show-siblings' variables."
10956 (let ((case-fold-search t)
10957 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10958 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10959 (append '(("") (" ") ("\t") ("\n"))
10960 org-emphasis-alist)
10961 "\\|") "\\)"))
10962 (pos (point))
10963 (pre nil) (post nil)
10964 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10965 (cond
10966 ;; First check if there are any special search functions
10967 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10968 ;; Now try the builtin stuff
10969 ((and (equal (string-to-char s0) ?#)
10970 (> (length s0) 1)
10971 (save-excursion
10972 (goto-char (point-min))
10973 (and
10974 (re-search-forward
10975 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10976 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10977 (setq type 'dedicated
10978 pos (match-beginning 0))))
10979 ;; There is an exact target for this
10980 (goto-char pos)
10981 (org-back-to-heading t)))
10982 ((save-excursion
10983 (goto-char (point-min))
10984 (and
10985 (re-search-forward
10986 (concat "<<" (regexp-quote s0) ">>") nil t)
10987 (setq type 'dedicated
10988 pos (match-beginning 0))))
10989 ;; There is an exact target for this
10990 (goto-char pos))
10991 ((save-excursion
10992 (goto-char (point-min))
10993 (and
10994 (re-search-forward
10995 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10996 (setq type 'dedicated pos (match-beginning 0))))
10997 ;; Found an element with a matching #+name affiliated keyword.
10998 (goto-char pos))
10999 ((and (string-match "^(\\(.*\\))$" s0)
11000 (save-excursion
11001 (goto-char (point-min))
11002 (and
11003 (re-search-forward
11004 (concat "[^[]" (regexp-quote
11005 (format org-coderef-label-format
11006 (match-string 1 s0))))
11007 nil t)
11008 (setq type 'dedicated
11009 pos (1+ (match-beginning 0))))))
11010 ;; There is a coderef target for this
11011 (goto-char pos))
11012 ((string-match "^/\\(.*\\)/$" s)
11013 ;; A regular expression
11014 (cond
11015 ((derived-mode-p 'org-mode)
11016 (org-occur (match-string 1 s)))
11017 (t (org-do-occur (match-string 1 s)))))
11018 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11019 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11020 (goto-char (point-min))
11021 (cond
11022 ((let (case-fold-search)
11023 (re-search-forward (format org-complex-heading-regexp-format
11024 (regexp-quote s))
11025 nil t))
11026 ;; OK, found a match
11027 (setq type 'dedicated)
11028 (goto-char (match-beginning 0)))
11029 ((and (not org-link-search-inhibit-query)
11030 (eq org-link-search-must-match-exact-headline 'query-to-create)
11031 (y-or-n-p "No match - create this as a new heading? "))
11032 (goto-char (point-max))
11033 (or (bolp) (newline))
11034 (insert "* " s "\n")
11035 (beginning-of-line 0))
11037 (goto-char pos)
11038 (error "No match"))))
11040 ;; A normal search string
11041 (when (equal (string-to-char s) ?*)
11042 ;; Anchor on headlines, post may include tags.
11043 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11044 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11045 s (substring s 1)))
11046 (remove-text-properties
11047 0 (length s)
11048 '(face nil mouse-face nil keymap nil fontified nil) s)
11049 ;; Make a series of regular expressions to find a match
11050 (setq words (org-split-string s "[ \n\r\t]+")
11052 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11053 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11054 "\\)" markers)
11055 re2a_ (concat "\\(" (mapconcat 'downcase words
11056 "[ \t\r\n]+") "\\)[ \t\r\n]")
11057 re2a (concat "[ \t\r\n]" re2a_)
11058 re4_ (concat "\\(" (mapconcat 'downcase words
11059 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11060 re4 (concat "[^a-zA-Z_]" re4_)
11062 re1 (concat pre re2 post)
11063 re3 (concat pre (if pre re4_ re4) post)
11064 re5 (concat pre ".*" re4)
11065 re2 (concat pre re2)
11066 re2a (concat pre (if pre re2a_ re2a))
11067 re4 (concat pre (if pre re4_ re4))
11068 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11069 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11070 re5 "\\)"))
11071 (cond
11072 ((eq type 'org-occur) (org-occur reall))
11073 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11074 (t (goto-char (point-min))
11075 (setq type 'fuzzy)
11076 (if (or (and (org-search-not-self 1 re0 nil t)
11077 (setq type 'dedicated))
11078 (org-search-not-self 1 re1 nil t)
11079 (org-search-not-self 1 re2 nil t)
11080 (org-search-not-self 1 re2a nil t)
11081 (org-search-not-self 1 re3 nil t)
11082 (org-search-not-self 1 re4 nil t)
11083 (org-search-not-self 1 re5 nil t))
11084 (goto-char (match-beginning 1))
11085 (goto-char pos)
11086 (error "No match"))))))
11087 (and (derived-mode-p 'org-mode)
11088 (not stealth)
11089 (org-show-context 'link-search))
11090 type))
11092 (defun org-search-not-self (group &rest args)
11093 "Execute `re-search-forward', but only accept matches that do not
11094 enclose the position of `org-open-link-marker'."
11095 (let ((m org-open-link-marker))
11096 (catch 'exit
11097 (while (apply 're-search-forward args)
11098 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11099 (goto-char (match-end group))
11100 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11101 (> (match-beginning 0) (marker-position m))
11102 (< (match-end 0) (marker-position m)))
11103 (save-match-data
11104 (or (not (org-in-regexp
11105 org-bracket-link-analytic-regexp 1))
11106 (not (match-end 4)) ; no description
11107 (and (<= (match-beginning 4) (point))
11108 (>= (match-end 4) (point))))))
11109 (throw 'exit (point))))))))
11111 (defun org-get-buffer-for-internal-link (buffer)
11112 "Return a buffer to be used for displaying the link target of internal links."
11113 (cond
11114 ((not org-display-internal-link-with-indirect-buffer)
11115 buffer)
11116 ((string-match "(Clone)$" (buffer-name buffer))
11117 (message "Buffer is already a clone, not making another one")
11118 ;; we also do not modify visibility in this case
11119 buffer)
11120 (t ; make a new indirect buffer for displaying the link
11121 (let* ((bn (buffer-name buffer))
11122 (ibn (concat bn "(Clone)"))
11123 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11124 (with-current-buffer ib (org-overview))
11125 ib))))
11127 (defun org-do-occur (regexp &optional cleanup)
11128 "Call the Emacs command `occur'.
11129 If CLEANUP is non-nil, remove the printout of the regular expression
11130 in the *Occur* buffer. This is useful if the regex is long and not useful
11131 to read."
11132 (occur regexp)
11133 (when cleanup
11134 (let ((cwin (selected-window)) win beg end)
11135 (when (setq win (get-buffer-window "*Occur*"))
11136 (select-window win))
11137 (goto-char (point-min))
11138 (when (re-search-forward "match[a-z]+" nil t)
11139 (setq beg (match-end 0))
11140 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11141 (setq end (1- (match-beginning 0)))))
11142 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11143 (goto-char (point-min))
11144 (select-window cwin))))
11146 ;;; The mark ring for links jumps
11148 (defvar org-mark-ring nil
11149 "Mark ring for positions before jumps in Org-mode.")
11150 (defvar org-mark-ring-last-goto nil
11151 "Last position in the mark ring used to go back.")
11152 ;; Fill and close the ring
11153 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11154 (loop for i from 1 to org-mark-ring-length do
11155 (push (make-marker) org-mark-ring))
11156 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11157 org-mark-ring)
11159 (defun org-mark-ring-push (&optional pos buffer)
11160 "Put the current position or POS into the mark ring and rotate it."
11161 (interactive)
11162 (setq pos (or pos (point)))
11163 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11164 (move-marker (car org-mark-ring)
11165 (or pos (point))
11166 (or buffer (current-buffer)))
11167 (message "%s"
11168 (substitute-command-keys
11169 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11171 (defun org-mark-ring-goto (&optional n)
11172 "Jump to the previous position in the mark ring.
11173 With prefix arg N, jump back that many stored positions. When
11174 called several times in succession, walk through the entire ring.
11175 Org-mode commands jumping to a different position in the current file,
11176 or to another Org-mode file, automatically push the old position
11177 onto the ring."
11178 (interactive "p")
11179 (let (p m)
11180 (if (eq last-command this-command)
11181 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11182 (setq p org-mark-ring))
11183 (setq org-mark-ring-last-goto p)
11184 (setq m (car p))
11185 (org-pop-to-buffer-same-window (marker-buffer m))
11186 (goto-char m)
11187 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11189 (defun org-remove-angle-brackets (s)
11190 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11191 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11193 (defun org-add-angle-brackets (s)
11194 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11195 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11197 (defun org-remove-double-quotes (s)
11198 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11199 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11202 ;;; Following specific links
11204 (defun org-follow-timestamp-link ()
11205 "Open an agenda view for the time-stamp date/range at point."
11206 (cond
11207 ((org-at-date-range-p t)
11208 (let ((org-agenda-start-on-weekday)
11209 (t1 (match-string 1))
11210 (t2 (match-string 2)) tt1 tt2)
11211 (setq tt1 (time-to-days (org-time-string-to-time t1))
11212 tt2 (time-to-days (org-time-string-to-time t2)))
11213 (let ((org-agenda-buffer-tmp-name
11214 (format "*Org Agenda(a:%s)"
11215 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11216 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11217 ((org-at-timestamp-p t)
11218 (let ((org-agenda-buffer-tmp-name
11219 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11220 (org-agenda-list nil (time-to-days (org-time-string-to-time
11221 (substring (match-string 1) 0 10)))
11222 1)))
11223 (t (error "This should not happen"))))
11226 ;;; Following file links
11227 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11228 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11229 (declare-function mailcap-mime-info
11230 "mailcap" (string &optional request no-decode))
11231 (defvar org-wait nil)
11232 (defun org-open-file (path &optional in-emacs line search)
11233 "Open the file at PATH.
11234 First, this expands any special file name abbreviations. Then the
11235 configuration variable `org-file-apps' is checked if it contains an
11236 entry for this file type, and if yes, the corresponding command is launched.
11238 If no application is found, Emacs simply visits the file.
11240 With optional prefix argument IN-EMACS, Emacs will visit the file.
11241 With a double \\[universal-argument] \\[universal-argument] \
11242 prefix arg, Org tries to avoid opening in Emacs
11243 and to use an external application to visit the file.
11245 Optional LINE specifies a line to go to, optional SEARCH a string
11246 to search for. If LINE or SEARCH is given, the file will be
11247 opened in Emacs, unless an entry from org-file-apps that makes
11248 use of groups in a regexp matches.
11250 If you want to change the way frames are used when following a
11251 link, please customize `org-link-frame-setup'.
11253 If the file does not exist, an error is thrown."
11254 (let* ((file (if (equal path "")
11255 buffer-file-name
11256 (substitute-in-file-name (expand-file-name path))))
11257 (file-apps (append org-file-apps (org-default-apps)))
11258 (apps (org-remove-if
11259 'org-file-apps-entry-match-against-dlink-p file-apps))
11260 (apps-dlink (org-remove-if-not
11261 'org-file-apps-entry-match-against-dlink-p file-apps))
11262 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11263 (dirp (if remp nil (file-directory-p file)))
11264 (file (if (and dirp org-open-directory-means-index-dot-org)
11265 (concat (file-name-as-directory file) "index.org")
11266 file))
11267 (a-m-a-p (assq 'auto-mode apps))
11268 (dfile (downcase file))
11269 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11270 (link (cond ((and (eq line nil)
11271 (eq search nil))
11272 file)
11273 (line
11274 (concat file "::" (number-to-string line)))
11275 (search
11276 (concat file "::" search))))
11277 (dlink (downcase link))
11278 (old-buffer (current-buffer))
11279 (old-pos (point))
11280 (old-mode major-mode)
11281 ext cmd link-match-data)
11282 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11283 (setq ext (match-string 1 dfile))
11284 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11285 (setq ext (match-string 1 dfile))))
11286 (cond
11287 ((member in-emacs '((16) system))
11288 (setq cmd (cdr (assoc 'system apps))))
11289 (in-emacs (setq cmd 'emacs))
11291 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11292 (and dirp (cdr (assoc 'directory apps)))
11293 ; first, try matching against apps-dlink
11294 ; if we get a match here, store the match data for later
11295 (let ((match (assoc-default dlink apps-dlink
11296 'string-match)))
11297 (if match
11298 (progn (setq link-match-data (match-data))
11299 match)
11300 (progn (setq in-emacs (or in-emacs line search))
11301 nil))) ; if we have no match in apps-dlink,
11302 ; always open the file in emacs if line or search
11303 ; is given (for backwards compatibility)
11304 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11305 'string-match)
11306 (cdr (assoc ext apps))
11307 (cdr (assoc t apps))))))
11308 (when (eq cmd 'system)
11309 (setq cmd (cdr (assoc 'system apps))))
11310 (when (eq cmd 'default)
11311 (setq cmd (cdr (assoc t apps))))
11312 (when (eq cmd 'mailcap)
11313 (require 'mailcap)
11314 (mailcap-parse-mailcaps)
11315 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11316 (command (mailcap-mime-info mime-type)))
11317 (if (stringp command)
11318 (setq cmd command)
11319 (setq cmd 'emacs))))
11320 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11321 (not (file-exists-p file))
11322 (not org-open-non-existing-files))
11323 (user-error "No such file: %s" file))
11324 (cond
11325 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11326 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11327 (while (string-match "['\"]%s['\"]" cmd)
11328 (setq cmd (replace-match "%s" t t cmd)))
11329 (while (string-match "%s" cmd)
11330 (setq cmd (replace-match
11331 (save-match-data
11332 (shell-quote-argument
11333 (convert-standard-filename file)))
11334 t t cmd)))
11336 ;; Replace "%1", "%2" etc. in command with group matches from regex
11337 (save-match-data
11338 (let ((match-index 1)
11339 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11340 (set-match-data link-match-data)
11341 (while (<= match-index number-of-groups)
11342 (let ((regex (concat "%" (number-to-string match-index)))
11343 (replace-with (match-string match-index dlink)))
11344 (while (string-match regex cmd)
11345 (setq cmd (replace-match replace-with t t cmd))))
11346 (setq match-index (+ match-index 1)))))
11348 (save-window-excursion
11349 (message "Running %s...done" cmd)
11350 (start-process-shell-command cmd nil cmd)
11351 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11352 ((or (stringp cmd)
11353 (eq cmd 'emacs))
11354 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11355 (widen)
11356 (if line (progn (org-goto-line line)
11357 (if (derived-mode-p 'org-mode)
11358 (org-reveal)))
11359 (if search (org-link-search search))))
11360 ((consp cmd)
11361 (let ((file (convert-standard-filename file)))
11362 (save-match-data
11363 (set-match-data link-match-data)
11364 (eval cmd))))
11365 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11366 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11367 (or (not (equal old-buffer (current-buffer)))
11368 (not (equal old-pos (point))))
11369 (org-mark-ring-push old-pos old-buffer))))
11371 (defun org-file-apps-entry-match-against-dlink-p (entry)
11372 "This function returns non-nil if `entry' uses a regular
11373 expression which should be matched against the whole link by
11374 org-open-file.
11376 It assumes that is the case when the entry uses a regular
11377 expression which has at least one grouping construct and the
11378 action is either a lisp form or a command string containing
11379 '%1', i.e. using at least one subexpression match as a
11380 parameter."
11381 (let ((selector (car entry))
11382 (action (cdr entry)))
11383 (if (stringp selector)
11384 (and (> (regexp-opt-depth selector) 0)
11385 (or (and (stringp action)
11386 (string-match "%[0-9]" action))
11387 (consp action)))
11388 nil)))
11390 (defun org-default-apps ()
11391 "Return the default applications for this operating system."
11392 (cond
11393 ((eq system-type 'darwin)
11394 org-file-apps-defaults-macosx)
11395 ((eq system-type 'windows-nt)
11396 org-file-apps-defaults-windowsnt)
11397 (t org-file-apps-defaults-gnu)))
11399 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11400 "Convert extensions to regular expressions in the cars of LIST.
11401 Also, weed out any non-string entries, because the return value is used
11402 only for regexp matching.
11403 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11404 point to the symbol `emacs', indicating that the file should
11405 be opened in Emacs."
11406 (append
11407 (delq nil
11408 (mapcar (lambda (x)
11409 (if (not (stringp (car x)))
11411 (if (string-match "\\W" (car x))
11413 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11414 list))
11415 (if add-auto-mode
11416 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11418 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11419 (defun org-file-remote-p (file)
11420 "Test whether FILE specifies a location on a remote system.
11421 Return non-nil if the location is indeed remote.
11423 For example, the filename \"/user@host:/foo\" specifies a location
11424 on the system \"/user@host:\"."
11425 (cond ((fboundp 'file-remote-p)
11426 (file-remote-p file))
11427 ((fboundp 'tramp-handle-file-remote-p)
11428 (tramp-handle-file-remote-p file))
11429 ((and (boundp 'ange-ftp-name-format)
11430 (string-match (car ange-ftp-name-format) file))
11431 t)))
11434 ;;;; Refiling
11436 (defun org-get-org-file ()
11437 "Read a filename, with default directory `org-directory'."
11438 (let ((default (or org-default-notes-file remember-data-file)))
11439 (read-file-name (format "File name [%s]: " default)
11440 (file-name-as-directory org-directory)
11441 default)))
11443 (defun org-notes-order-reversed-p ()
11444 "Check if the current file should receive notes in reversed order."
11445 (cond
11446 ((not org-reverse-note-order) nil)
11447 ((eq t org-reverse-note-order) t)
11448 ((not (listp org-reverse-note-order)) nil)
11449 (t (catch 'exit
11450 (let ((all org-reverse-note-order)
11451 entry)
11452 (while (setq entry (pop all))
11453 (if (string-match (car entry) buffer-file-name)
11454 (throw 'exit (cdr entry))))
11455 nil)))))
11457 (defvar org-refile-target-table nil
11458 "The list of refile targets, created by `org-refile'.")
11460 (defvar org-agenda-new-buffers nil
11461 "Buffers created to visit agenda files.")
11463 (defvar org-refile-cache nil
11464 "Cache for refile targets.")
11466 (defvar org-refile-markers nil
11467 "All the markers used for caching refile locations.")
11469 (defun org-refile-marker (pos)
11470 "Get a new refile marker, but only if caching is in use."
11471 (if (not org-refile-use-cache)
11473 (let ((m (make-marker)))
11474 (move-marker m pos)
11475 (push m org-refile-markers)
11476 m)))
11478 (defun org-refile-cache-clear ()
11479 "Clear the refile cache and disable all the markers."
11480 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11481 (setq org-refile-markers nil)
11482 (setq org-refile-cache nil)
11483 (message "Refile cache has been cleared"))
11485 (defun org-refile-cache-check-set (set)
11486 "Check if all the markers in the cache still have live buffers."
11487 (let (marker)
11488 (catch 'exit
11489 (while (and set (setq marker (nth 3 (pop set))))
11490 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11491 (when (and marker (null (marker-buffer marker)))
11492 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11493 (sit-for 3)
11494 (throw 'exit nil)))
11495 t)))
11497 (defun org-refile-cache-put (set &rest identifiers)
11498 "Push the refile targets SET into the cache, under IDENTIFIERS."
11499 (let* ((key (sha1 (prin1-to-string identifiers)))
11500 (entry (assoc key org-refile-cache)))
11501 (if entry
11502 (setcdr entry set)
11503 (push (cons key set) org-refile-cache))))
11505 (defun org-refile-cache-get (&rest identifiers)
11506 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11507 (cond
11508 ((not org-refile-cache) nil)
11509 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11511 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11512 org-refile-cache))))
11513 (and set (org-refile-cache-check-set set) set)))))
11515 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11516 "Produce a table with refile targets."
11517 (let ((case-fold-search nil)
11518 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11519 (entries (or org-refile-targets '((nil . (:level . 1)))))
11520 targets tgs txt re files f desc descre fast-path-p level pos0)
11521 (message "Getting targets...")
11522 (with-current-buffer (or default-buffer (current-buffer))
11523 (while (setq entry (pop entries))
11524 (setq files (car entry) desc (cdr entry))
11525 (setq fast-path-p nil)
11526 (cond
11527 ((null files) (setq files (list (current-buffer))))
11528 ((eq files 'org-agenda-files)
11529 (setq files (org-agenda-files 'unrestricted)))
11530 ((and (symbolp files) (fboundp files))
11531 (setq files (funcall files)))
11532 ((and (symbolp files) (boundp files))
11533 (setq files (symbol-value files))))
11534 (if (stringp files) (setq files (list files)))
11535 (cond
11536 ((eq (car desc) :tag)
11537 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11538 ((eq (car desc) :todo)
11539 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11540 ((eq (car desc) :regexp)
11541 (setq descre (cdr desc)))
11542 ((eq (car desc) :level)
11543 (setq descre (concat "^\\*\\{" (number-to-string
11544 (if org-odd-levels-only
11545 (1- (* 2 (cdr desc)))
11546 (cdr desc)))
11547 "\\}[ \t]")))
11548 ((eq (car desc) :maxlevel)
11549 (setq fast-path-p t)
11550 (setq descre (concat "^\\*\\{1," (number-to-string
11551 (if org-odd-levels-only
11552 (1- (* 2 (cdr desc)))
11553 (cdr desc)))
11554 "\\}[ \t]")))
11555 (t (error "Bad refiling target description %s" desc)))
11556 (while (setq f (pop files))
11557 (with-current-buffer
11558 (if (bufferp f) f (org-get-agenda-file-buffer f))
11560 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11561 (progn
11562 (if (bufferp f) (setq f (buffer-file-name
11563 (buffer-base-buffer f))))
11564 (setq f (and f (expand-file-name f)))
11565 (if (eq org-refile-use-outline-path 'file)
11566 (push (list (file-name-nondirectory f) f nil nil) tgs))
11567 (save-excursion
11568 (save-restriction
11569 (widen)
11570 (goto-char (point-min))
11571 (while (re-search-forward descre nil t)
11572 (goto-char (setq pos0 (point-at-bol)))
11573 (catch 'next
11574 (when org-refile-target-verify-function
11575 (save-match-data
11576 (or (funcall org-refile-target-verify-function)
11577 (throw 'next t))))
11578 (when (and (looking-at org-complex-heading-regexp)
11579 (not (member (match-string 4) excluded-entries))
11580 (match-string 4))
11581 (setq level (org-reduced-level
11582 (- (match-end 1) (match-beginning 1)))
11583 txt (org-link-display-format (match-string 4))
11584 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11585 re (format org-complex-heading-regexp-format
11586 (regexp-quote (match-string 4))))
11587 (when org-refile-use-outline-path
11588 (setq txt (mapconcat
11589 'org-protect-slash
11590 (append
11591 (if (eq org-refile-use-outline-path
11592 'file)
11593 (list (file-name-nondirectory
11594 (buffer-file-name
11595 (buffer-base-buffer))))
11596 (if (eq org-refile-use-outline-path
11597 'full-file-path)
11598 (list (buffer-file-name
11599 (buffer-base-buffer)))))
11600 (org-get-outline-path fast-path-p
11601 level txt)
11602 (list txt))
11603 "/")))
11604 (push (list txt f re (org-refile-marker (point)))
11605 tgs)))
11606 (when (= (point) pos0)
11607 ;; verification function has not moved point
11608 (goto-char (point-at-eol))))))))
11609 (when org-refile-use-cache
11610 (org-refile-cache-put tgs (buffer-file-name) descre))
11611 (setq targets (append tgs targets))))))
11612 (message "Getting targets...done")
11613 (nreverse targets)))
11615 (defun org-protect-slash (s)
11616 (while (string-match "/" s)
11617 (setq s (replace-match "\\" t t s)))
11620 (defvar org-olpa (make-vector 20 nil))
11622 (defun org-get-outline-path (&optional fastp level heading)
11623 "Return the outline path to the current entry, as a list.
11625 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11626 routine which makes outline path derivations for an entire file,
11627 avoiding backtracing. Refile target collection makes use of that."
11628 (if fastp
11629 (progn
11630 (if (> level 19)
11631 (error "Outline path failure, more than 19 levels"))
11632 (loop for i from level upto 19 do
11633 (aset org-olpa i nil))
11634 (prog1
11635 (delq nil (append org-olpa nil))
11636 (aset org-olpa level heading)))
11637 (let (rtn case-fold-search)
11638 (save-excursion
11639 (save-restriction
11640 (widen)
11641 (while (org-up-heading-safe)
11642 (when (looking-at org-complex-heading-regexp)
11643 (push (org-trim
11644 (replace-regexp-in-string
11645 ;; Remove statistical/checkboxes cookies
11646 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11647 (org-match-string-no-properties 4)))
11648 rtn)))
11649 rtn)))))
11651 (defun org-format-outline-path (path &optional width prefix separator)
11652 "Format the outline path PATH for display.
11653 WIDTH is the maximum number of characters that is available.
11654 PREFIX is a prefix to be included in the returned string,
11655 such as the file name.
11656 SEPARATOR is inserted between the different parts of the path,
11657 the default is \"/\"."
11658 (setq width (or width 79))
11659 (if prefix (setq width (- width (length prefix))))
11660 (if (not path)
11661 (or prefix "")
11662 (let* ((nsteps (length path))
11663 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11664 (maxwidth (if (<= total-width width)
11665 10000 ;; everything fits
11666 ;; we need to shorten the level headings
11667 (/ (- width nsteps) nsteps)))
11668 (org-odd-levels-only nil)
11669 (n 0)
11670 (total (1+ (length prefix))))
11671 (setq maxwidth (max maxwidth 10))
11672 (concat prefix
11673 (if prefix (or separator "/"))
11674 (mapconcat
11675 (lambda (h)
11676 (setq n (1+ n))
11677 (if (and (= n nsteps) (< maxwidth 10000))
11678 (setq maxwidth (- total-width total)))
11679 (if (< (length h) maxwidth)
11680 (progn (setq total (+ total (length h) 1)) h)
11681 (setq h (substring h 0 (- maxwidth 2))
11682 total (+ total maxwidth 1))
11683 (if (string-match "[ \t]+\\'" h)
11684 (setq h (substring h 0 (match-beginning 0))))
11685 (setq h (concat h "..")))
11686 (org-add-props h nil 'face
11687 (nth (% (1- n) org-n-level-faces)
11688 org-level-faces))
11690 path (or separator "/"))))))
11692 (defun org-display-outline-path (&optional file current separator just-return-string)
11693 "Display the current outline path in the echo area.
11695 If FILE is non-nil, prepend the output with the file name.
11696 If CURRENT is non-nil, append the current heading to the output.
11697 SEPARATOR is passed through to `org-format-outline-path'. It separates
11698 the different parts of the path and defaults to \"/\".
11699 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11700 (interactive "P")
11701 (let* (case-fold-search
11702 (bfn (buffer-file-name (buffer-base-buffer)))
11703 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11704 res)
11705 (if current (setq path (append path
11706 (save-excursion
11707 (org-back-to-heading t)
11708 (if (looking-at org-complex-heading-regexp)
11709 (list (match-string 4)))))))
11710 (setq res
11711 (org-format-outline-path
11712 path
11713 (1- (frame-width))
11714 (and file bfn (concat (file-name-nondirectory bfn) separator))
11715 separator))
11716 (if just-return-string
11717 (org-no-properties res)
11718 (org-unlogged-message "%s" res))))
11720 (defvar org-refile-history nil
11721 "History for refiling operations.")
11723 (defvar org-after-refile-insert-hook nil
11724 "Hook run after `org-refile' has inserted its stuff at the new location.
11725 Note that this is still *before* the stuff will be removed from
11726 the *old* location.")
11728 (defvar org-capture-last-stored-marker)
11729 (defvar org-refile-keep nil
11730 "Non-nil means `org-refile' will copy instead of refile.")
11732 (defun org-copy ()
11733 "Like `org-refile', but copy."
11734 (interactive)
11735 (let ((org-refile-keep t))
11736 (funcall 'org-refile nil nil nil "Copy")))
11738 (defun org-refile (&optional arg default-buffer rfloc msg)
11739 "Move the entry or entries at point to another heading.
11740 The list of target headings is compiled using the information in
11741 `org-refile-targets', which see.
11743 At the target location, the entry is filed as a subitem of the
11744 target heading. Depending on `org-reverse-note-order', the new
11745 subitem will either be the first or the last subitem.
11747 If there is an active region, all entries in that region will be
11748 refiled. However, the region must fulfill the requirement that
11749 the first heading sets the top-level of the moved text.
11751 With prefix arg ARG, the command will only visit the target
11752 location and not actually move anything.
11754 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11755 refiling operation has put the subtree.
11757 With a numeric prefix argument of `2', refile to the running clock.
11759 With a numeric prefix argument of `3', emulate `org-refile-keep'
11760 being set to `t' and copy to the target location, don't move it.
11761 Beware that keeping refiled entries may result in duplicated ID
11762 properties.
11764 RFLOC can be a refile location obtained in a different way.
11766 MSG is a string to replace \"Refile\" in the default prompt with
11767 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11769 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11771 If you are using target caching (see `org-refile-use-cache'), you
11772 have to clear the target cache in order to find new targets.
11773 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11774 prefix argument (`C-u C-u C-u C-c C-w')."
11775 (interactive "P")
11776 (if (member arg '(0 (64)))
11777 (org-refile-cache-clear)
11778 (let* ((actionmsg (cond (msg msg)
11779 ((equal arg 3) "Refile (and keep)")
11780 (t "Refile")))
11781 (cbuf (current-buffer))
11782 (regionp (org-region-active-p))
11783 (region-start (and regionp (region-beginning)))
11784 (region-end (and regionp (region-end)))
11785 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11786 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11787 pos it nbuf file re level reversed)
11788 (setq last-command nil)
11789 (when regionp
11790 (goto-char region-start)
11791 (or (bolp) (goto-char (point-at-bol)))
11792 (setq region-start (point))
11793 (unless (or (org-kill-is-subtree-p
11794 (buffer-substring region-start region-end))
11795 (prog1 org-refile-active-region-within-subtree
11796 (let ((s (point-at-eol)))
11797 (org-toggle-heading)
11798 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11799 (user-error "The region is not a (sequence of) subtree(s)")))
11800 (if (equal arg '(16))
11801 (org-refile-goto-last-stored)
11802 (when (or
11803 (and (equal arg 2)
11804 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11805 (prog1
11806 (setq it (list (or org-clock-heading "running clock")
11807 (buffer-file-name
11808 (marker-buffer org-clock-hd-marker))
11810 (marker-position org-clock-hd-marker)))
11811 (setq arg nil)))
11812 (setq it (or rfloc
11813 (let (heading-text)
11814 (save-excursion
11815 (unless (and arg (listp arg))
11816 (org-back-to-heading t)
11817 (setq heading-text
11818 (replace-regexp-in-string
11819 org-bracket-link-regexp
11820 "\\3"
11821 (nth 4 (org-heading-components)))))
11822 (org-refile-get-location
11823 (cond ((and arg (listp arg)) "Goto")
11824 (regionp (concat actionmsg " region to"))
11825 (t (concat actionmsg " subtree \""
11826 heading-text "\" to")))
11827 default-buffer
11828 (and (not (equal '(4) arg))
11829 org-refile-allow-creating-parent-nodes)
11830 arg))))))
11831 (setq file (nth 1 it)
11832 re (nth 2 it)
11833 pos (nth 3 it))
11834 (if (and (not arg)
11836 (equal (buffer-file-name) file)
11837 (if regionp
11838 (and (>= pos region-start)
11839 (<= pos region-end))
11840 (and (>= pos (point))
11841 (< pos (save-excursion
11842 (org-end-of-subtree t t))))))
11843 (error "Cannot refile to position inside the tree or region"))
11844 (setq nbuf (or (find-buffer-visiting file)
11845 (find-file-noselect file)))
11846 (if (and arg (not (equal arg 3)))
11847 (progn
11848 (org-pop-to-buffer-same-window nbuf)
11849 (goto-char pos)
11850 (org-show-context 'org-goto))
11851 (if regionp
11852 (progn
11853 (org-kill-new (buffer-substring region-start region-end))
11854 (org-save-markers-in-region region-start region-end))
11855 (org-copy-subtree 1 nil t))
11856 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11857 (find-file-noselect file)))
11858 (setq reversed (org-notes-order-reversed-p))
11859 (save-excursion
11860 (save-restriction
11861 (widen)
11862 (if pos
11863 (progn
11864 (goto-char pos)
11865 (looking-at org-outline-regexp)
11866 (setq level (org-get-valid-level (funcall outline-level) 1))
11867 (goto-char
11868 (if reversed
11869 (or (outline-next-heading) (point-max))
11870 (or (save-excursion (org-get-next-sibling))
11871 (org-end-of-subtree t t)
11872 (point-max)))))
11873 (setq level 1)
11874 (if (not reversed)
11875 (goto-char (point-max))
11876 (goto-char (point-min))
11877 (or (outline-next-heading) (goto-char (point-max)))))
11878 (if (not (bolp)) (newline))
11879 (org-paste-subtree level nil nil t)
11880 (when org-log-refile
11881 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11882 (unless (eq org-log-refile 'note)
11883 (save-excursion (org-add-log-note))))
11884 (and org-auto-align-tags
11885 (let ((org-loop-over-headlines-in-active-region nil))
11886 (org-set-tags nil t)))
11887 (let ((bookmark-name (plist-get org-bookmark-names-plist
11888 :last-refile)))
11889 (when bookmark-name
11890 (with-demoted-errors
11891 (bookmark-set bookmark-name))))
11892 ;; If we are refiling for capture, make sure that the
11893 ;; last-capture pointers point here
11894 (when (org-bound-and-true-p org-refile-for-capture)
11895 (let ((bookmark-name (plist-get org-bookmark-names-plist
11896 :last-capture-marker)))
11897 (when bookmark-name
11898 (with-demoted-errors
11899 (bookmark-set bookmark-name))))
11900 (move-marker org-capture-last-stored-marker (point)))
11901 (if (fboundp 'deactivate-mark) (deactivate-mark))
11902 (run-hooks 'org-after-refile-insert-hook))))
11903 (unless org-refile-keep
11904 (if regionp
11905 (delete-region (point) (+ (point) (- region-end region-start)))
11906 (delete-region
11907 (and (org-back-to-heading t) (point))
11908 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11909 (when (featurep 'org-inlinetask)
11910 (org-inlinetask-remove-END-maybe))
11911 (setq org-markers-to-move nil)
11912 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11914 (defun org-refile-goto-last-stored ()
11915 "Go to the location where the last refile was stored."
11916 (interactive)
11917 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11918 (message "This is the location of the last refile"))
11920 (defun org-refile--get-location (refloc tbl)
11921 "When user refile to REFLOC, find the associated target in TBL.
11922 Also check `org-refile-target-table'."
11923 (car (delq
11925 (mapcar
11926 (lambda (r) (or (assoc r tbl)
11927 (assoc r org-refile-target-table)))
11928 (list (replace-regexp-in-string "/$" "" refloc)
11929 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11931 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11932 no-exclude)
11933 "Prompt the user for a refile location, using PROMPT.
11934 PROMPT should not be suffixed with a colon and a space, because
11935 this function appends the default value from
11936 `org-refile-history' automatically, if that is not empty.
11937 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11938 this is used for the GOTO interface."
11939 (let ((org-refile-targets org-refile-targets)
11940 (org-refile-use-outline-path org-refile-use-outline-path)
11941 excluded-entries)
11942 (when (and (derived-mode-p 'org-mode)
11943 (not org-refile-use-cache)
11944 (not no-exclude))
11945 (org-map-tree
11946 (lambda()
11947 (setq excluded-entries
11948 (append excluded-entries (list (org-get-heading t t)))))))
11949 (setq org-refile-target-table
11950 (org-refile-get-targets default-buffer excluded-entries)))
11951 (unless org-refile-target-table
11952 (user-error "No refile targets"))
11953 (let* ((cbuf (current-buffer))
11954 (partial-completion-mode nil)
11955 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11956 (cfunc (if (and org-refile-use-outline-path
11957 org-outline-path-complete-in-steps)
11958 'org-olpath-completing-read
11959 'org-icompleting-read))
11960 (extra (if org-refile-use-outline-path "/" ""))
11961 (cbnex (concat (buffer-name) extra))
11962 (filename (and cfn (expand-file-name cfn)))
11963 (tbl (mapcar
11964 (lambda (x)
11965 (if (and (not (member org-refile-use-outline-path
11966 '(file full-file-path)))
11967 (not (equal filename (nth 1 x))))
11968 (cons (concat (car x) extra " ("
11969 (file-name-nondirectory (nth 1 x)) ")")
11970 (cdr x))
11971 (cons (concat (car x) extra) (cdr x))))
11972 org-refile-target-table))
11973 (completion-ignore-case t)
11974 cdef
11975 (prompt (concat prompt
11976 (or (and (car org-refile-history)
11977 (concat " (default " (car org-refile-history) ")"))
11978 (and (assoc cbnex tbl) (setq cdef cbnex)
11979 (concat " (default " cbnex ")"))) ": "))
11980 pa answ parent-target child parent old-hist)
11981 (setq old-hist org-refile-history)
11982 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11983 nil 'org-refile-history (or cdef (car org-refile-history))))
11984 (if (setq pa (org-refile--get-location answ tbl))
11985 (progn
11986 (org-refile-check-position pa)
11987 (when (or (not org-refile-history)
11988 (not (eq old-hist org-refile-history))
11989 (not (equal (car pa) (car org-refile-history))))
11990 (setq org-refile-history
11991 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11992 org-refile-history
11993 (cdr org-refile-history))))
11994 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11995 (pop org-refile-history)))
11997 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11998 (progn
11999 (setq parent (match-string 1 answ)
12000 child (match-string 2 answ))
12001 (setq parent-target (org-refile--get-location parent tbl))
12002 (when (and parent-target
12003 (or (eq new-nodes t)
12004 (and (eq new-nodes 'confirm)
12005 (y-or-n-p (format "Create new node \"%s\"? "
12006 child)))))
12007 (org-refile-new-child parent-target child)))
12008 (user-error "Invalid target location")))))
12010 (declare-function org-string-nw-p "org-macs" (s))
12011 (defun org-refile-check-position (refile-pointer)
12012 "Check if the refile pointer matches the headline to which it points."
12013 (let* ((file (nth 1 refile-pointer))
12014 (re (nth 2 refile-pointer))
12015 (pos (nth 3 refile-pointer))
12016 buffer)
12017 (if (and (not (markerp pos)) (not file))
12018 (user-error "Please indicate a target file in the refile path")
12019 (when (org-string-nw-p re)
12020 (setq buffer (if (markerp pos)
12021 (marker-buffer pos)
12022 (or (find-buffer-visiting file)
12023 (find-file-noselect file))))
12024 (with-current-buffer buffer
12025 (save-excursion
12026 (save-restriction
12027 (widen)
12028 (goto-char pos)
12029 (beginning-of-line 1)
12030 (unless (org-looking-at-p re)
12031 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12033 (defun org-refile-new-child (parent-target child)
12034 "Use refile target PARENT-TARGET to add new CHILD below it."
12035 (unless parent-target
12036 (error "Cannot find parent for new node"))
12037 (let ((file (nth 1 parent-target))
12038 (pos (nth 3 parent-target))
12039 level)
12040 (with-current-buffer (or (find-buffer-visiting file)
12041 (find-file-noselect file))
12042 (save-excursion
12043 (save-restriction
12044 (widen)
12045 (if pos
12046 (goto-char pos)
12047 (goto-char (point-max))
12048 (if (not (bolp)) (newline)))
12049 (when (looking-at org-outline-regexp)
12050 (setq level (funcall outline-level))
12051 (org-end-of-subtree t t))
12052 (org-back-over-empty-lines)
12053 (insert "\n" (make-string
12054 (if pos (org-get-valid-level level 1) 1) ?*)
12055 " " child "\n")
12056 (beginning-of-line 0)
12057 (list (concat (car parent-target) "/" child) file "" (point)))))))
12059 (defun org-olpath-completing-read (prompt collection &rest args)
12060 "Read an outline path like a file name."
12061 (let ((thetable collection)
12062 (org-completion-use-ido nil) ; does not work with ido.
12063 (org-completion-use-iswitchb nil)) ; or iswitchb
12064 (apply
12065 'org-icompleting-read prompt
12066 (lambda (string predicate &optional flag)
12067 (let (rtn r f (l (length string)))
12068 (cond
12069 ((eq flag nil)
12070 ;; try completion
12071 (try-completion string thetable))
12072 ((eq flag t)
12073 ;; all-completions
12074 (setq rtn (all-completions string thetable predicate))
12075 (mapcar
12076 (lambda (x)
12077 (setq r (substring x l))
12078 (if (string-match " ([^)]*)$" x)
12079 (setq f (match-string 0 x))
12080 (setq f ""))
12081 (if (string-match "/" r)
12082 (concat string (substring r 0 (match-end 0)) f)
12084 rtn))
12085 ((eq flag 'lambda)
12086 ;; exact match?
12087 (assoc string thetable)))))
12088 args)))
12090 ;;;; Dynamic blocks
12092 (defun org-find-dblock (name)
12093 "Find the first dynamic block with name NAME in the buffer.
12094 If not found, stay at current position and return nil."
12095 (let ((case-fold-search t) pos)
12096 (save-excursion
12097 (goto-char (point-min))
12098 (setq pos (and (re-search-forward
12099 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12100 (match-beginning 0))))
12101 (if pos (goto-char pos))
12102 pos))
12104 (defun org-create-dblock (plist)
12105 "Create a dynamic block section, with parameters taken from PLIST.
12106 PLIST must contain a :name entry which is used as the name of the block."
12107 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12108 (end-of-line 1)
12109 (newline))
12110 (let ((col (current-column))
12111 (name (plist-get plist :name)))
12112 (insert "#+BEGIN: " name)
12113 (while plist
12114 (if (eq (car plist) :name)
12115 (setq plist (cddr plist))
12116 (insert " " (prin1-to-string (pop plist)))))
12117 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12118 (beginning-of-line -2)))
12120 (defun org-prepare-dblock ()
12121 "Prepare dynamic block for refresh.
12122 This empties the block, puts the cursor at the insert position and returns
12123 the property list including an extra property :name with the block name."
12124 (unless (looking-at org-dblock-start-re)
12125 (user-error "Not at a dynamic block"))
12126 (let* ((begdel (1+ (match-end 0)))
12127 (name (org-no-properties (match-string 1)))
12128 (params (append (list :name name)
12129 (read (concat "(" (match-string 3) ")")))))
12130 (save-excursion
12131 (beginning-of-line 1)
12132 (skip-chars-forward " \t")
12133 (setq params (plist-put params :indentation-column (current-column))))
12134 (unless (re-search-forward org-dblock-end-re nil t)
12135 (error "Dynamic block not terminated"))
12136 (setq params
12137 (append params
12138 (list :content (buffer-substring
12139 begdel (match-beginning 0)))))
12140 (delete-region begdel (match-beginning 0))
12141 (goto-char begdel)
12142 (open-line 1)
12143 params))
12145 (defun org-map-dblocks (&optional command)
12146 "Apply COMMAND to all dynamic blocks in the current buffer.
12147 If COMMAND is not given, use `org-update-dblock'."
12148 (let ((cmd (or command 'org-update-dblock)))
12149 (save-excursion
12150 (goto-char (point-min))
12151 (while (re-search-forward org-dblock-start-re nil t)
12152 (goto-char (match-beginning 0))
12153 (save-excursion
12154 (condition-case nil
12155 (funcall cmd)
12156 (error (message "Error during update of dynamic block"))))
12157 (unless (re-search-forward org-dblock-end-re nil t)
12158 (error "Dynamic block not terminated"))))))
12160 (defun org-dblock-update (&optional arg)
12161 "User command for updating dynamic blocks.
12162 Update the dynamic block at point. With prefix ARG, update all dynamic
12163 blocks in the buffer."
12164 (interactive "P")
12165 (if arg
12166 (org-update-all-dblocks)
12167 (or (looking-at org-dblock-start-re)
12168 (org-beginning-of-dblock))
12169 (org-update-dblock)))
12171 (defun org-update-dblock ()
12172 "Update the dynamic block at point.
12173 This means to empty the block, parse for parameters and then call
12174 the correct writing function."
12175 (interactive)
12176 (save-excursion
12177 (let* ((win (selected-window))
12178 (pos (point))
12179 (line (org-current-line))
12180 (params (org-prepare-dblock))
12181 (name (plist-get params :name))
12182 (indent (plist-get params :indentation-column))
12183 (cmd (intern (concat "org-dblock-write:" name))))
12184 (message "Updating dynamic block `%s' at line %d..." name line)
12185 (funcall cmd params)
12186 (message "Updating dynamic block `%s' at line %d...done" name line)
12187 (goto-char pos)
12188 (when (and indent (> indent 0))
12189 (setq indent (make-string indent ?\ ))
12190 (save-excursion
12191 (select-window win)
12192 (org-beginning-of-dblock)
12193 (forward-line 1)
12194 (while (not (looking-at org-dblock-end-re))
12195 (insert indent)
12196 (beginning-of-line 2))
12197 (when (looking-at org-dblock-end-re)
12198 (and (looking-at "[ \t]+")
12199 (replace-match ""))
12200 (insert indent)))))))
12202 (defun org-beginning-of-dblock ()
12203 "Find the beginning of the dynamic block at point.
12204 Error if there is no such block at point."
12205 (let ((pos (point))
12206 beg)
12207 (end-of-line 1)
12208 (if (and (re-search-backward org-dblock-start-re nil t)
12209 (setq beg (match-beginning 0))
12210 (re-search-forward org-dblock-end-re nil t)
12211 (> (match-end 0) pos))
12212 (goto-char beg)
12213 (goto-char pos)
12214 (error "Not in a dynamic block"))))
12216 (defun org-update-all-dblocks ()
12217 "Update all dynamic blocks in the buffer.
12218 This function can be used in a hook."
12219 (interactive)
12220 (when (derived-mode-p 'org-mode)
12221 (org-map-dblocks 'org-update-dblock)))
12224 ;;;; Completion
12226 (declare-function org-export-backend-name "org-export" (cl-x))
12227 (declare-function org-export-backend-options "org-export" (cl-x))
12228 (defun org-get-export-keywords ()
12229 "Return a list of all currently understood export keywords.
12230 Export keywords include options, block names, attributes and
12231 keywords relative to each registered export back-end."
12232 (let (keywords)
12233 (dolist (backend
12234 (org-bound-and-true-p org-export--registered-backends)
12235 (delq nil keywords))
12236 ;; Back-end name (for keywords, like #+LATEX:)
12237 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12238 (dolist (option-entry (org-export-backend-options backend))
12239 ;; Back-end options.
12240 (push (nth 1 option-entry) keywords)))))
12242 (defconst org-options-keywords
12243 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12244 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12245 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12246 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12247 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12249 (defcustom org-structure-template-alist
12250 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12251 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12252 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12253 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12254 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12255 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12256 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12257 ("L" "#+LaTeX: ")
12258 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12259 ("H" "#+HTML: ")
12260 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12261 ("A" "#+ASCII: ")
12262 ("i" "#+INDEX: ?")
12263 ("I" "#+INCLUDE: %file ?"))
12264 "Structure completion elements.
12265 This is a list of abbreviation keys and values. The value gets inserted
12266 if you type `<' followed by the key and then press the completion key,
12267 usually `TAB'. %file will be replaced by a file name after prompting
12268 for the file using completion. The cursor will be placed at the position
12269 of the `?` in the template.
12270 There are two templates for each key, the first uses the original Org syntax,
12271 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12272 the default when the /org-mtags.el/ module has been loaded. See also the
12273 variable `org-mtags-prefer-muse-templates'."
12274 :group 'org-completion
12275 :type '(repeat
12276 (list
12277 (string :tag "Key")
12278 (string :tag "Template")))
12279 :version 24.4
12280 :package-version '(Org . "8.3"))
12282 (defun org-try-structure-completion ()
12283 "Try to complete a structure template before point.
12284 This looks for strings like \"<e\" on an otherwise empty line and
12285 expands them."
12286 (let ((l (buffer-substring (point-at-bol) (point)))
12288 (when (and (looking-at "[ \t]*$")
12289 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12290 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12291 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12292 (match-beginning 1)) a)
12293 t)))
12295 (defun org-complete-expand-structure-template (start cell)
12296 "Expand a structure template."
12297 (let ((rpl (nth 1 cell))
12298 (ind ""))
12299 (delete-region start (point))
12300 (when (string-match "\\`[ \t]*#\\+" rpl)
12301 (cond
12302 ((bolp))
12303 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12304 (setq ind (buffer-substring (point-at-bol) (point))))
12305 (t (newline))))
12306 (setq start (point))
12307 (if (string-match "%file" rpl)
12308 (setq rpl (replace-match
12309 (concat
12310 "\""
12311 (save-match-data
12312 (abbreviate-file-name (read-file-name "Include file: ")))
12313 "\"")
12314 t t rpl)))
12315 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12316 (concat "\n" ind)))
12317 (insert rpl)
12318 (if (re-search-backward "\\?" start t) (delete-char 1))))
12320 ;;;; TODO, DEADLINE, Comments
12322 (defun org-toggle-comment ()
12323 "Change the COMMENT state of an entry."
12324 (interactive)
12325 (save-excursion
12326 (org-back-to-heading)
12327 (looking-at org-complex-heading-regexp)
12328 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12329 (skip-chars-forward " \t")
12330 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12331 (if (org-in-commented-heading-p t)
12332 (delete-region (point)
12333 (progn (search-forward " " (line-end-position) 'move)
12334 (skip-chars-forward " \t")
12335 (point)))
12336 (insert org-comment-string)
12337 (unless (eolp) (insert " ")))))
12339 (defvar org-last-todo-state-is-todo nil
12340 "This is non-nil when the last TODO state change led to a TODO state.
12341 If the last change removed the TODO tag or switched to DONE, then
12342 this is nil.")
12344 (defvar org-setting-tags nil) ; dynamically skipped
12346 (defvar org-todo-setup-filter-hook nil
12347 "Hook for functions that pre-filter todo specs.
12348 Each function takes a todo spec and returns either nil or the spec
12349 transformed into canonical form." )
12351 (defvar org-todo-get-default-hook nil
12352 "Hook for functions that get a default item for todo.
12353 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12354 nil or a string to be used for the todo mark." )
12356 (defvar org-agenda-headline-snapshot-before-repeat)
12358 (defun org-current-effective-time ()
12359 "Return current time adjusted for `org-extend-today-until' variable."
12360 (let* ((ct (org-current-time))
12361 (dct (decode-time ct))
12362 (ct1
12363 (cond
12364 (org-use-last-clock-out-time-as-effective-time
12365 (or (org-clock-get-last-clock-out-time) ct))
12366 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12367 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12368 (t ct))))
12369 ct1))
12371 (defun org-todo-yesterday (&optional arg)
12372 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12373 (interactive "P")
12374 (if (eq major-mode 'org-agenda-mode)
12375 (apply 'org-agenda-todo-yesterday arg)
12376 (let* ((hour (third (decode-time
12377 (org-current-time))))
12378 (org-extend-today-until (1+ hour)))
12379 (org-todo arg))))
12381 (defvar org-block-entry-blocking ""
12382 "First entry preventing the TODO state change.")
12384 (defun org-cancel-repeater ()
12385 "Cancel a repeater by setting its numeric value to zero."
12386 (interactive)
12387 (save-excursion
12388 (org-back-to-heading t)
12389 (let ((bound1 (point))
12390 (bound0 (save-excursion (outline-next-heading) (point))))
12391 (when (re-search-forward
12392 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12393 org-deadline-time-regexp "\\)\\|\\("
12394 org-ts-regexp "\\)")
12395 bound0 t)
12396 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12397 (replace-match "0" t nil nil 1))))))
12399 (defun org-todo (&optional arg)
12400 "Change the TODO state of an item.
12401 The state of an item is given by a keyword at the start of the heading,
12402 like
12403 *** TODO Write paper
12404 *** DONE Call mom
12406 The different keywords are specified in the variable `org-todo-keywords'.
12407 By default the available states are \"TODO\" and \"DONE\".
12408 So for this example: when the item starts with TODO, it is changed to DONE.
12409 When it starts with DONE, the DONE is removed. And when neither TODO nor
12410 DONE are present, add TODO at the beginning of the heading.
12412 With \\[universal-argument] prefix arg, use completion to determine the new \
12413 state.
12414 With numeric prefix arg, switch to that state.
12415 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12416 keywords (nextset).
12417 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12418 With a numeric prefix arg of 0, inhibit note taking for the change.
12419 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12421 When called through ELisp, arg is also interpreted in the following way:
12422 'none -> empty state
12423 \"\"(empty string) -> switch to empty state
12424 'done -> switch to DONE
12425 'nextset -> switch to the next set of keywords
12426 'previousset -> switch to the previous set of keywords
12427 \"WAITING\" -> switch to the specified keyword, but only if it
12428 really is a member of `org-todo-keywords'."
12429 (interactive "P")
12430 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12431 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12432 'region-start-level 'region))
12433 org-loop-over-headlines-in-active-region)
12434 (org-map-entries
12435 `(org-todo ,arg)
12436 org-loop-over-headlines-in-active-region
12437 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12438 (if (equal arg '(16)) (setq arg 'nextset))
12439 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12440 (let ((org-blocker-hook org-blocker-hook)
12441 commentp
12442 case-fold-search)
12443 (when (equal arg '(64))
12444 (setq arg nil org-blocker-hook nil))
12445 (when (and org-blocker-hook
12446 (or org-inhibit-blocking
12447 (org-entry-get nil "NOBLOCKING")))
12448 (setq org-blocker-hook nil))
12449 (save-excursion
12450 (catch 'exit
12451 (org-back-to-heading t)
12452 (when (org-in-commented-heading-p t)
12453 (org-toggle-comment)
12454 (setq commentp t))
12455 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12456 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12457 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12458 (let* ((match-data (match-data))
12459 (startpos (point-at-bol))
12460 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12461 (org-log-done org-log-done)
12462 (org-log-repeat org-log-repeat)
12463 (org-todo-log-states org-todo-log-states)
12464 (org-inhibit-logging
12465 (if (equal arg 0)
12466 (progn (setq arg nil) 'note) org-inhibit-logging))
12467 (this (match-string 1))
12468 (hl-pos (match-beginning 0))
12469 (head (org-get-todo-sequence-head this))
12470 (ass (assoc head org-todo-kwd-alist))
12471 (interpret (nth 1 ass))
12472 (done-word (nth 3 ass))
12473 (final-done-word (nth 4 ass))
12474 (org-last-state (or this ""))
12475 (completion-ignore-case t)
12476 (member (member this org-todo-keywords-1))
12477 (tail (cdr member))
12478 (org-state (cond
12479 ((and org-todo-key-trigger
12480 (or (and (equal arg '(4))
12481 (eq org-use-fast-todo-selection 'prefix))
12482 (and (not arg) org-use-fast-todo-selection
12483 (not (eq org-use-fast-todo-selection
12484 'prefix)))))
12485 ;; Use fast selection
12486 (org-fast-todo-selection))
12487 ((and (equal arg '(4))
12488 (or (not org-use-fast-todo-selection)
12489 (not org-todo-key-trigger)))
12490 ;; Read a state with completion
12491 (org-icompleting-read
12492 "State: " (mapcar 'list org-todo-keywords-1)
12493 nil t))
12494 ((eq arg 'right)
12495 (if this
12496 (if tail (car tail) nil)
12497 (car org-todo-keywords-1)))
12498 ((eq arg 'left)
12499 (if (equal member org-todo-keywords-1)
12501 (if this
12502 (nth (- (length org-todo-keywords-1)
12503 (length tail) 2)
12504 org-todo-keywords-1)
12505 (org-last org-todo-keywords-1))))
12506 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12507 (setq arg nil))) ; hack to fall back to cycling
12508 (arg
12509 ;; user or caller requests a specific state
12510 (cond
12511 ((equal arg "") nil)
12512 ((eq arg 'none) nil)
12513 ((eq arg 'done) (or done-word (car org-done-keywords)))
12514 ((eq arg 'nextset)
12515 (or (car (cdr (member head org-todo-heads)))
12516 (car org-todo-heads)))
12517 ((eq arg 'previousset)
12518 (let ((org-todo-heads (reverse org-todo-heads)))
12519 (or (car (cdr (member head org-todo-heads)))
12520 (car org-todo-heads))))
12521 ((car (member arg org-todo-keywords-1)))
12522 ((stringp arg)
12523 (user-error "State `%s' not valid in this file" arg))
12524 ((nth (1- (prefix-numeric-value arg))
12525 org-todo-keywords-1))))
12526 ((null member) (or head (car org-todo-keywords-1)))
12527 ((equal this final-done-word) nil) ;; -> make empty
12528 ((null tail) nil) ;; -> first entry
12529 ((memq interpret '(type priority))
12530 (if (eq this-command last-command)
12531 (car tail)
12532 (if (> (length tail) 0)
12533 (or done-word (car org-done-keywords))
12534 nil)))
12536 (car tail))))
12537 (org-state (or
12538 (run-hook-with-args-until-success
12539 'org-todo-get-default-hook org-state org-last-state)
12540 org-state))
12541 (next (if org-state (concat " " org-state " ") " "))
12542 (change-plist (list :type 'todo-state-change :from this :to org-state
12543 :position startpos))
12544 dolog now-done-p)
12545 (when org-blocker-hook
12546 (setq org-last-todo-state-is-todo
12547 (not (member this org-done-keywords)))
12548 (unless (save-excursion
12549 (save-match-data
12550 (org-with-wide-buffer
12551 (run-hook-with-args-until-failure
12552 'org-blocker-hook change-plist))))
12553 (if (org-called-interactively-p 'interactive)
12554 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12555 this org-state org-block-entry-blocking)
12556 ;; fail silently
12557 (message "TODO state change from %s to %s blocked (by \"%s\")"
12558 this org-state org-block-entry-blocking)
12559 (throw 'exit nil))))
12560 (store-match-data match-data)
12561 (replace-match next t t)
12562 (cond ((equal this org-state)
12563 (message "TODO state was already %s" (org-trim next)))
12564 ((pos-visible-in-window-p hl-pos)
12565 (message "TODO state changed to %s" (org-trim next))))
12566 (unless head
12567 (setq head (org-get-todo-sequence-head org-state)
12568 ass (assoc head org-todo-kwd-alist)
12569 interpret (nth 1 ass)
12570 done-word (nth 3 ass)
12571 final-done-word (nth 4 ass)))
12572 (when (memq arg '(nextset previousset))
12573 (message "Keyword-Set %d/%d: %s"
12574 (- (length org-todo-sets) -1
12575 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12576 (length org-todo-sets)
12577 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12578 (setq org-last-todo-state-is-todo
12579 (not (member org-state org-done-keywords)))
12580 (setq now-done-p (and (member org-state org-done-keywords)
12581 (not (member this org-done-keywords))))
12582 (and logging (org-local-logging logging))
12583 (when (and (or org-todo-log-states org-log-done)
12584 (not (eq org-inhibit-logging t))
12585 (not (memq arg '(nextset previousset))))
12586 ;; we need to look at recording a time and note
12587 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12588 (nth 2 (assoc this org-todo-log-states))))
12589 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12590 (setq dolog 'time))
12591 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12592 (and org-state
12593 (member org-state org-not-done-keywords)
12594 (not (member this org-not-done-keywords))))
12595 ;; This is now a todo state and was not one before
12596 ;; If there was a CLOSED time stamp, get rid of it.
12597 (org-add-planning-info nil nil 'closed))
12598 (when (and now-done-p org-log-done)
12599 ;; It is now done, and it was not done before
12600 (org-add-planning-info 'closed (org-current-effective-time))
12601 (if (and (not dolog) (eq 'note org-log-done))
12602 (org-add-log-setup 'done org-state this 'findpos 'note)))
12603 (when (and org-state dolog)
12604 ;; This is a non-nil state, and we need to log it
12605 (org-add-log-setup 'state org-state this 'findpos dolog)))
12606 ;; Fixup tag positioning
12607 (org-todo-trigger-tag-changes org-state)
12608 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12609 (when org-provide-todo-statistics
12610 (org-update-parent-todo-statistics))
12611 (run-hooks 'org-after-todo-state-change-hook)
12612 (if (and arg (not (member org-state org-done-keywords)))
12613 (setq head (org-get-todo-sequence-head org-state)))
12614 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12615 ;; Do we need to trigger a repeat?
12616 (when now-done-p
12617 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12618 ;; This is for the agenda, take a snapshot of the headline.
12619 (save-match-data
12620 (setq org-agenda-headline-snapshot-before-repeat
12621 (org-get-heading))))
12622 (org-auto-repeat-maybe org-state))
12623 ;; Fixup cursor location if close to the keyword
12624 (if (and (outline-on-heading-p)
12625 (not (bolp))
12626 (save-excursion (beginning-of-line 1)
12627 (looking-at org-todo-line-regexp))
12628 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12629 (progn
12630 (goto-char (or (match-end 2) (match-end 1)))
12631 (and (looking-at " ") (just-one-space))))
12632 (when org-trigger-hook
12633 (save-excursion
12634 (run-hook-with-args 'org-trigger-hook change-plist)))
12635 (when commentp (org-toggle-comment))))))))
12637 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12638 "Block turning an entry into a TODO, using the hierarchy.
12639 This checks whether the current task should be blocked from state
12640 changes. Such blocking occurs when:
12642 1. The task has children which are not all in a completed state.
12644 2. A task has a parent with the property :ORDERED:, and there
12645 are siblings prior to the current task with incomplete
12646 status.
12648 3. The parent of the task is blocked because it has siblings that should
12649 be done first, or is child of a block grandparent TODO entry."
12651 (if (not org-enforce-todo-dependencies)
12652 t ; if locally turned off don't block
12653 (catch 'dont-block
12654 ;; If this is not a todo state change, or if this entry is already DONE,
12655 ;; do not block
12656 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12657 (member (plist-get change-plist :from)
12658 (cons 'done org-done-keywords))
12659 (member (plist-get change-plist :to)
12660 (cons 'todo org-not-done-keywords))
12661 (not (plist-get change-plist :to)))
12662 (throw 'dont-block t))
12663 ;; If this task has children, and any are undone, it's blocked
12664 (save-excursion
12665 (org-back-to-heading t)
12666 (let ((this-level (funcall outline-level)))
12667 (outline-next-heading)
12668 (let ((child-level (funcall outline-level)))
12669 (while (and (not (eobp))
12670 (> child-level this-level))
12671 ;; this todo has children, check whether they are all
12672 ;; completed
12673 (if (and (not (org-entry-is-done-p))
12674 (org-entry-is-todo-p))
12675 (progn (setq org-block-entry-blocking (org-get-heading))
12676 (throw 'dont-block nil)))
12677 (outline-next-heading)
12678 (setq child-level (funcall outline-level))))))
12679 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12680 ;; any previous siblings are undone, it's blocked
12681 (save-excursion
12682 (org-back-to-heading t)
12683 (let* ((pos (point))
12684 (parent-pos (and (org-up-heading-safe) (point))))
12685 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12686 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12687 (forward-line 1)
12688 (re-search-forward org-not-done-heading-regexp pos t))
12689 (setq org-block-entry-blocking (match-string 0))
12690 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12691 ;; Search further up the hierarchy, to see if an ancestor is blocked
12692 (while t
12693 (goto-char parent-pos)
12694 (if (not (looking-at org-not-done-heading-regexp))
12695 (throw 'dont-block t)) ; do not block, parent is not a TODO
12696 (setq pos (point))
12697 (setq parent-pos (and (org-up-heading-safe) (point)))
12698 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12699 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12700 (forward-line 1)
12701 (re-search-forward org-not-done-heading-regexp pos t)
12702 (setq org-block-entry-blocking (org-get-heading)))
12703 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12705 (defcustom org-track-ordered-property-with-tag nil
12706 "Should the ORDERED property also be shown as a tag?
12707 The ORDERED property decides if an entry should require subtasks to be
12708 completed in sequence. Since a property is not very visible, setting
12709 this option means that toggling the ORDERED property with the command
12710 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12711 not relevant for the behavior, but it makes things more visible.
12713 Note that toggling the tag with tags commands will not change the property
12714 and therefore not influence behavior!
12716 This can be t, meaning the tag ORDERED should be used, It can also be a
12717 string to select a different tag for this task."
12718 :group 'org-todo
12719 :type '(choice
12720 (const :tag "No tracking" nil)
12721 (const :tag "Track with ORDERED tag" t)
12722 (string :tag "Use other tag")))
12724 (defun org-toggle-ordered-property ()
12725 "Toggle the ORDERED property of the current entry.
12726 For better visibility, you can track the value of this property with a tag.
12727 See variable `org-track-ordered-property-with-tag'."
12728 (interactive)
12729 (let* ((t1 org-track-ordered-property-with-tag)
12730 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12731 (save-excursion
12732 (org-back-to-heading)
12733 (if (org-entry-get nil "ORDERED")
12734 (progn
12735 (org-delete-property "ORDERED")
12736 (and tag (org-toggle-tag tag 'off))
12737 (message "Subtasks can be completed in arbitrary order"))
12738 (org-entry-put nil "ORDERED" "t")
12739 (and tag (org-toggle-tag tag 'on))
12740 (message "Subtasks must be completed in sequence")))))
12742 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12743 (defun org-block-todo-from-checkboxes (change-plist)
12744 "Block turning an entry into a TODO, using checkboxes.
12745 This checks whether the current task should be blocked from state
12746 changes because there are unchecked boxes in this entry."
12747 (if (not org-enforce-todo-checkbox-dependencies)
12748 t ; if locally turned off don't block
12749 (catch 'dont-block
12750 ;; If this is not a todo state change, or if this entry is already DONE,
12751 ;; do not block
12752 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12753 (member (plist-get change-plist :from)
12754 (cons 'done org-done-keywords))
12755 (member (plist-get change-plist :to)
12756 (cons 'todo org-not-done-keywords))
12757 (not (plist-get change-plist :to)))
12758 (throw 'dont-block t))
12759 ;; If this task has checkboxes that are not checked, it's blocked
12760 (save-excursion
12761 (org-back-to-heading t)
12762 (let ((beg (point)) end)
12763 (outline-next-heading)
12764 (setq end (point))
12765 (goto-char beg)
12766 (if (org-list-search-forward
12767 (concat (org-item-beginning-re)
12768 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12769 "\\[[- ]\\]")
12770 end t)
12771 (progn
12772 (if (boundp 'org-blocked-by-checkboxes)
12773 (setq org-blocked-by-checkboxes t))
12774 (throw 'dont-block nil)))))
12775 t))) ; do not block
12777 (defun org-entry-blocked-p ()
12778 "Is the current entry blocked?"
12779 (org-with-silent-modifications
12780 (if (org-entry-get nil "NOBLOCKING")
12781 nil ;; Never block this entry
12782 (not (run-hook-with-args-until-failure
12783 'org-blocker-hook
12784 (list :type 'todo-state-change
12785 :position (point)
12786 :from 'todo
12787 :to 'done))))))
12789 (defun org-update-statistics-cookies (all)
12790 "Update the statistics cookie, either from TODO or from checkboxes.
12791 This should be called with the cursor in a line with a statistics cookie."
12792 (interactive "P")
12793 (if all
12794 (progn
12795 (org-update-checkbox-count 'all)
12796 (org-map-entries 'org-update-parent-todo-statistics))
12797 (if (not (org-at-heading-p))
12798 (org-update-checkbox-count)
12799 (let ((pos (point-marker))
12800 end l1 l2)
12801 (ignore-errors (org-back-to-heading t))
12802 (if (not (org-at-heading-p))
12803 (org-update-checkbox-count)
12804 (setq l1 (org-outline-level))
12805 (setq end (save-excursion
12806 (outline-next-heading)
12807 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12808 (point)))
12809 (if (and (save-excursion
12810 (re-search-forward
12811 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12812 (not (save-excursion (re-search-forward
12813 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12814 (org-update-checkbox-count)
12815 (if (and l2 (> l2 l1))
12816 (progn
12817 (goto-char end)
12818 (org-update-parent-todo-statistics))
12819 (goto-char pos)
12820 (beginning-of-line 1)
12821 (while (re-search-forward
12822 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12823 (point-at-eol) t)
12824 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12825 (goto-char pos)
12826 (move-marker pos nil)))))
12828 (defvar org-entry-property-inherited-from) ;; defined below
12829 (defun org-update-parent-todo-statistics ()
12830 "Update any statistics cookie in the parent of the current headline.
12831 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12832 the entire subtree and this will travel up the hierarchy and update
12833 statistics everywhere."
12834 (let* ((prop (save-excursion (org-up-heading-safe)
12835 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12836 (recursive (or (not org-hierarchical-todo-statistics)
12837 (and prop (string-match "\\<recursive\\>" prop))))
12838 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12840 (first t)
12841 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12842 level ltoggle l1 new ndel
12843 (cnt-all 0) (cnt-done 0) is-percent kwd
12844 checkbox-beg ov ovs ove cookie-present)
12845 (catch 'exit
12846 (save-excursion
12847 (beginning-of-line 1)
12848 (setq ltoggle (funcall outline-level))
12849 ;; Three situations are to consider:
12851 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12852 ;; to the top-level ancestor on the headline;
12854 ;; 2. If parent has "recursive" property, repeat up to the
12855 ;; headline setting that property, taking inheritance into
12856 ;; account;
12858 ;; 3. Else, move up to direct parent and proceed only once.
12859 (while (and (setq level (org-up-heading-safe))
12860 (or recursive first)
12861 (>= (point) lim))
12862 (setq first nil cookie-present nil)
12863 (unless (and level
12864 (not (string-match
12865 "\\<checkbox\\>"
12866 (downcase (or (org-entry-get nil "COOKIE_DATA")
12867 "")))))
12868 (throw 'exit nil))
12869 (while (re-search-forward box-re (point-at-eol) t)
12870 (setq cnt-all 0 cnt-done 0 cookie-present t)
12871 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12872 (save-match-data
12873 (unless (outline-next-heading) (throw 'exit nil))
12874 (while (and (looking-at org-complex-heading-regexp)
12875 (> (setq l1 (length (match-string 1))) level))
12876 (setq kwd (and (or recursive (= l1 ltoggle))
12877 (match-string 2)))
12878 (if (or (eq org-provide-todo-statistics 'all-headlines)
12879 (and (eq org-provide-todo-statistics t)
12880 (or (member kwd org-done-keywords)))
12881 (and (listp org-provide-todo-statistics)
12882 (stringp (car org-provide-todo-statistics))
12883 (or (member kwd org-provide-todo-statistics)
12884 (member kwd org-done-keywords)))
12885 (and (listp org-provide-todo-statistics)
12886 (listp (car org-provide-todo-statistics))
12887 (or (member kwd (car org-provide-todo-statistics))
12888 (and (member kwd org-done-keywords)
12889 (member kwd (cadr org-provide-todo-statistics))))))
12890 (setq cnt-all (1+ cnt-all))
12891 (if (eq org-provide-todo-statistics t)
12892 (and kwd (setq cnt-all (1+ cnt-all)))))
12893 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12894 (member kwd org-done-keywords))
12895 (and (listp org-provide-todo-statistics)
12896 (listp (car org-provide-todo-statistics))
12897 (member kwd org-done-keywords)
12898 (member kwd (cadr org-provide-todo-statistics)))
12899 (and (listp org-provide-todo-statistics)
12900 (stringp (car org-provide-todo-statistics))
12901 (member kwd org-done-keywords)))
12902 (setq cnt-done (1+ cnt-done)))
12903 (outline-next-heading)))
12904 (setq new
12905 (if is-percent
12906 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12907 (format "[%d/%d]" cnt-done cnt-all))
12908 ndel (- (match-end 0) checkbox-beg))
12909 ;; handle overlays when updating cookie from column view
12910 (when (setq ov (car (overlays-at checkbox-beg)))
12911 (setq ovs (overlay-start ov) ove (overlay-end ov))
12912 (delete-overlay ov))
12913 (goto-char checkbox-beg)
12914 (insert new)
12915 (delete-region (point) (+ (point) ndel))
12916 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12917 (when ov (move-overlay ov ovs ove)))
12918 (when cookie-present
12919 (run-hook-with-args 'org-after-todo-statistics-hook
12920 cnt-done (- cnt-all cnt-done))))))
12921 (run-hooks 'org-todo-statistics-hook)))
12923 (defvar org-after-todo-statistics-hook nil
12924 "Hook that is called after a TODO statistics cookie has been updated.
12925 Each function is called with two arguments: the number of not-done entries
12926 and the number of done entries.
12928 For example, the following function, when added to this hook, will switch
12929 an entry to DONE when all children are done, and back to TODO when new
12930 entries are set to a TODO status. Note that this hook is only called
12931 when there is a statistics cookie in the headline!
12933 (defun org-summary-todo (n-done n-not-done)
12934 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12935 (let (org-log-done org-log-states) ; turn off logging
12936 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12939 (defvar org-todo-statistics-hook nil
12940 "Hook that is run whenever Org thinks TODO statistics should be updated.
12941 This hook runs even if there is no statistics cookie present, in which case
12942 `org-after-todo-statistics-hook' would not run.")
12944 (defun org-todo-trigger-tag-changes (state)
12945 "Apply the changes defined in `org-todo-state-tags-triggers'."
12946 (let ((l org-todo-state-tags-triggers)
12947 changes)
12948 (when (or (not state) (equal state ""))
12949 (setq changes (append changes (cdr (assoc "" l)))))
12950 (when (and (stringp state) (> (length state) 0))
12951 (setq changes (append changes (cdr (assoc state l)))))
12952 (when (member state org-not-done-keywords)
12953 (setq changes (append changes (cdr (assoc 'todo l)))))
12954 (when (member state org-done-keywords)
12955 (setq changes (append changes (cdr (assoc 'done l)))))
12956 (dolist (c changes)
12957 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12959 (defun org-local-logging (value)
12960 "Get logging settings from a property VALUE."
12961 (let* (words w a)
12962 ;; directly set the variables, they are already local.
12963 (setq org-log-done nil
12964 org-log-repeat nil
12965 org-todo-log-states nil)
12966 (setq words (org-split-string value))
12967 (while (setq w (pop words))
12968 (cond
12969 ((setq a (assoc w org-startup-options))
12970 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12971 (set (nth 1 a) (nth 2 a))))
12972 ((setq a (org-extract-log-state-settings w))
12973 (and (member (car a) org-todo-keywords-1)
12974 (push a org-todo-log-states)))))))
12976 (defun org-get-todo-sequence-head (kwd)
12977 "Return the head of the TODO sequence to which KWD belongs.
12978 If KWD is not set, check if there is a text property remembering the
12979 right sequence."
12980 (let (p)
12981 (cond
12982 ((not kwd)
12983 (or (get-text-property (point-at-bol) 'org-todo-head)
12984 (progn
12985 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12986 nil (point-at-eol)))
12987 (get-text-property p 'org-todo-head))))
12988 ((not (member kwd org-todo-keywords-1))
12989 (car org-todo-keywords-1))
12990 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12992 (defun org-fast-todo-selection ()
12993 "Fast TODO keyword selection with single keys.
12994 Returns the new TODO keyword, or nil if no state change should occur."
12995 (let* ((fulltable org-todo-key-alist)
12996 (done-keywords org-done-keywords) ;; needed for the faces.
12997 (maxlen (apply 'max (mapcar
12998 (lambda (x)
12999 (if (stringp (car x)) (string-width (car x)) 0))
13000 fulltable)))
13001 (expert nil)
13002 (fwidth (+ maxlen 3 1 3))
13003 (ncol (/ (- (window-width) 4) fwidth))
13004 tg cnt e c tbl
13005 groups ingroup)
13006 (save-excursion
13007 (save-window-excursion
13008 (if expert
13009 (set-buffer (get-buffer-create " *Org todo*"))
13010 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13011 (erase-buffer)
13012 (org-set-local 'org-done-keywords done-keywords)
13013 (setq tbl fulltable cnt 0)
13014 (while (setq e (pop tbl))
13015 (cond
13016 ((equal e '(:startgroup))
13017 (push '() groups) (setq ingroup t)
13018 (when (not (= cnt 0))
13019 (setq cnt 0)
13020 (insert "\n"))
13021 (insert "{ "))
13022 ((equal e '(:endgroup))
13023 (setq ingroup nil cnt 0)
13024 (insert "}\n"))
13025 ((equal e '(:newline))
13026 (when (not (= cnt 0))
13027 (setq cnt 0)
13028 (insert "\n")
13029 (setq e (car tbl))
13030 (while (equal (car tbl) '(:newline))
13031 (insert "\n")
13032 (setq tbl (cdr tbl)))))
13034 (setq tg (car e) c (cdr e))
13035 (if ingroup (push tg (car groups)))
13036 (setq tg (org-add-props tg nil 'face
13037 (org-get-todo-face tg)))
13038 (if (and (= cnt 0) (not ingroup)) (insert " "))
13039 (insert "[" c "] " tg (make-string
13040 (- fwidth 4 (length tg)) ?\ ))
13041 (when (= (setq cnt (1+ cnt)) ncol)
13042 (insert "\n")
13043 (if ingroup (insert " "))
13044 (setq cnt 0)))))
13045 (insert "\n")
13046 (goto-char (point-min))
13047 (if (not expert) (org-fit-window-to-buffer))
13048 (message "[a-z..]:Set [SPC]:clear")
13049 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13050 (cond
13051 ((or (= c ?\C-g)
13052 (and (= c ?q) (not (rassoc c fulltable))))
13053 (setq quit-flag t))
13054 ((= c ?\ ) nil)
13055 ((setq e (rassoc c fulltable) tg (car e))
13057 (t (setq quit-flag t)))))))
13059 (defun org-entry-is-todo-p ()
13060 (member (org-get-todo-state) org-not-done-keywords))
13062 (defun org-entry-is-done-p ()
13063 (member (org-get-todo-state) org-done-keywords))
13065 (defun org-get-todo-state ()
13066 "Return the TODO keyword of the current subtree."
13067 (save-excursion
13068 (org-back-to-heading t)
13069 (and (looking-at org-todo-line-regexp)
13070 (match-end 2)
13071 (match-string 2))))
13073 (defun org-at-date-range-p (&optional inactive-ok)
13074 "Is the cursor inside a date range?"
13075 (interactive)
13076 (save-excursion
13077 (catch 'exit
13078 (let ((pos (point)))
13079 (skip-chars-backward "^[<\r\n")
13080 (skip-chars-backward "<[")
13081 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13082 (>= (match-end 0) pos)
13083 (throw 'exit t))
13084 (skip-chars-backward "^<[\r\n")
13085 (skip-chars-backward "<[")
13086 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13087 (>= (match-end 0) pos)
13088 (throw 'exit t)))
13089 nil)))
13091 (defun org-get-repeat (&optional tagline)
13092 "Check if there is a deadline/schedule with repeater in this entry."
13093 (save-match-data
13094 (save-excursion
13095 (org-back-to-heading t)
13096 (and (re-search-forward (if tagline
13097 (concat tagline "\\s-*" org-repeat-re)
13098 org-repeat-re)
13099 (org-entry-end-position) t)
13100 (match-string-no-properties 1)))))
13102 (defvar org-last-changed-timestamp)
13103 (defvar org-last-inserted-timestamp)
13104 (defvar org-log-post-message)
13105 (defvar org-log-note-purpose)
13106 (defvar org-log-note-how nil)
13107 (defvar org-log-note-extra)
13108 (defun org-auto-repeat-maybe (done-word)
13109 "Check if the current headline contains a repeated deadline/schedule.
13110 If yes, set TODO state back to what it was and change the base date
13111 of repeating deadline/scheduled time stamps to new date.
13112 This function is run automatically after each state change to a DONE state."
13113 ;; last-state is dynamically scoped into this function
13114 (let* ((repeat (org-get-repeat))
13115 (aa (assoc org-last-state org-todo-kwd-alist))
13116 (interpret (nth 1 aa))
13117 (head (nth 2 aa))
13118 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13119 (msg "Entry repeats: ")
13120 (org-log-done nil)
13121 (org-todo-log-states nil)
13122 re type n what ts time to-state)
13123 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13124 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13125 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13126 org-todo-repeat-to-state))
13127 (unless (and to-state (member to-state org-todo-keywords-1))
13128 (setq to-state (if (eq interpret 'type) org-last-state head)))
13129 (org-todo to-state)
13130 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13131 (org-entry-put nil "LAST_REPEAT" (format-time-string
13132 (org-time-stamp-format t t))))
13133 (when org-log-repeat
13134 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13135 (memq 'org-add-log-note post-command-hook))
13136 ;; OK, we are already setup for some record
13137 (if (eq org-log-repeat 'note)
13138 ;; make sure we take a note, not only a time stamp
13139 (setq org-log-note-how 'note))
13140 ;; Set up for taking a record
13141 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13142 org-last-state
13143 'findpos org-log-repeat)))
13144 (org-back-to-heading t)
13145 (org-add-planning-info nil nil 'closed)
13146 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13147 org-deadline-time-regexp "\\)\\|\\("
13148 org-ts-regexp "\\)"))
13149 (while (re-search-forward
13150 re (save-excursion (outline-next-heading) (point)) t)
13151 (setq type (if (match-end 1) org-scheduled-string
13152 (if (match-end 3) org-deadline-string "Plain:"))
13153 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13154 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13155 (setq n (string-to-number (match-string 2 ts))
13156 what (match-string 3 ts))
13157 (if (equal what "w") (setq n (* n 7) what "d"))
13158 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13159 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13160 ;; Preparation, see if we need to modify the start date for the change
13161 (when (match-end 1)
13162 (setq time (save-match-data (org-time-string-to-time ts)))
13163 (cond
13164 ((equal (match-string 1 ts) ".")
13165 ;; Shift starting date to today
13166 (org-timestamp-change
13167 (- (org-today) (time-to-days time))
13168 'day))
13169 ((equal (match-string 1 ts) "+")
13170 (let ((nshiftmax 10) (nshift 0))
13171 (while (or (= nshift 0)
13172 (<= (time-to-days time)
13173 (time-to-days (current-time))))
13174 (when (= (incf nshift) nshiftmax)
13175 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13176 (user-error "Abort")))
13177 (org-timestamp-change n (cdr (assoc what whata)))
13178 (org-at-timestamp-p t)
13179 (setq ts (match-string 1))
13180 (setq time (save-match-data (org-time-string-to-time ts)))))
13181 (org-timestamp-change (- n) (cdr (assoc what whata)))
13182 ;; rematch, so that we have everything in place for the real shift
13183 (org-at-timestamp-p t)
13184 (setq ts (match-string 1))
13185 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13186 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13187 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13188 (setq org-log-post-message msg)
13189 (message "%s" msg))))
13191 (defun org-show-todo-tree (arg)
13192 "Make a compact tree which shows all headlines marked with TODO.
13193 The tree will show the lines where the regexp matches, and all higher
13194 headlines above the match.
13195 With a \\[universal-argument] prefix, prompt for a regexp to match.
13196 With a numeric prefix N, construct a sparse tree for the Nth element
13197 of `org-todo-keywords-1'."
13198 (interactive "P")
13199 (let ((case-fold-search nil)
13200 (kwd-re
13201 (cond ((null arg) org-not-done-regexp)
13202 ((equal arg '(4))
13203 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13204 (mapcar 'list org-todo-keywords-1))))
13205 (concat "\\("
13206 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13207 "\\)\\>")))
13208 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13209 (regexp-quote (nth (1- (prefix-numeric-value arg))
13210 org-todo-keywords-1)))
13211 (t (user-error "Invalid prefix argument: %s" arg)))))
13212 (message "%d TODO entries found"
13213 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13215 (defun org-deadline (arg &optional time)
13216 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13217 With one universal prefix argument, remove any deadline from the item.
13218 With two universal prefix arguments, prompt for a warning delay.
13219 With argument TIME, set the deadline at the corresponding date. TIME
13220 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13221 (interactive "P")
13222 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13223 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13224 'region-start-level 'region))
13225 org-loop-over-headlines-in-active-region)
13226 (org-map-entries
13227 `(org-deadline ',arg ,time)
13228 org-loop-over-headlines-in-active-region
13229 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13230 (let* ((old-date (org-entry-get nil "DEADLINE"))
13231 (old-date-time (if old-date (org-time-string-to-time old-date)))
13232 (repeater (and old-date
13233 (string-match
13234 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13235 old-date)
13236 (match-string 1 old-date))))
13237 (cond
13238 ((equal arg '(4))
13239 (when (and old-date org-log-redeadline)
13240 (org-add-log-setup 'deldeadline nil old-date 'findpos
13241 org-log-redeadline))
13242 (org-remove-timestamp-with-keyword org-deadline-string)
13243 (message "Item no longer has a deadline."))
13244 ((equal arg '(16))
13245 (save-excursion
13246 (org-back-to-heading t)
13247 (if (re-search-forward
13248 org-deadline-time-regexp
13249 (save-excursion (outline-next-heading) (point)) t)
13250 (let* ((rpl0 (match-string 1))
13251 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13252 (replace-match
13253 (concat org-deadline-string
13254 " <" rpl
13255 (format " -%dd"
13256 (abs
13257 (- (time-to-days
13258 (save-match-data
13259 (org-read-date nil t nil "Warn starting from" old-date-time)))
13260 (time-to-days old-date-time))))
13261 ">") t t))
13262 (user-error "No deadline information to update"))))
13264 (org-add-planning-info 'deadline time 'closed)
13265 (when (and old-date org-log-redeadline
13266 (not (equal old-date
13267 (substring org-last-inserted-timestamp 1 -1))))
13268 (org-add-log-setup 'redeadline nil old-date 'findpos
13269 org-log-redeadline))
13270 (when repeater
13271 (save-excursion
13272 (org-back-to-heading t)
13273 (when (re-search-forward (concat org-deadline-string " "
13274 org-last-inserted-timestamp)
13275 (save-excursion
13276 (outline-next-heading) (point)) t)
13277 (goto-char (1- (match-end 0)))
13278 (insert " " repeater)
13279 (setq org-last-inserted-timestamp
13280 (concat (substring org-last-inserted-timestamp 0 -1)
13281 " " repeater
13282 (substring org-last-inserted-timestamp -1))))))
13283 (message "Deadline on %s" org-last-inserted-timestamp))))))
13285 (defun org-schedule (arg &optional time)
13286 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13287 With one universal prefix argument, remove any scheduling date from the item.
13288 With two universal prefix arguments, prompt for a delay cookie.
13289 With argument TIME, scheduled at the corresponding date. TIME can
13290 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13291 (interactive "P")
13292 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13293 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13294 'region-start-level 'region))
13295 org-loop-over-headlines-in-active-region)
13296 (org-map-entries
13297 `(org-schedule ',arg ,time)
13298 org-loop-over-headlines-in-active-region
13299 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13300 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13301 (old-date-time (if old-date (org-time-string-to-time old-date)))
13302 (repeater (and old-date
13303 (string-match
13304 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13305 old-date)
13306 (match-string 1 old-date))))
13307 (cond
13308 ((equal arg '(4))
13309 (progn
13310 (when (and old-date org-log-reschedule)
13311 (org-add-log-setup 'delschedule nil old-date 'findpos
13312 org-log-reschedule))
13313 (org-remove-timestamp-with-keyword org-scheduled-string)
13314 (message "Item is no longer scheduled.")))
13315 ((equal arg '(16))
13316 (save-excursion
13317 (org-back-to-heading t)
13318 (if (re-search-forward
13319 org-scheduled-time-regexp
13320 (save-excursion (outline-next-heading) (point)) t)
13321 (let* ((rpl0 (match-string 1))
13322 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13323 (replace-match
13324 (concat org-scheduled-string
13325 " <" rpl
13326 (format " -%dd"
13327 (abs
13328 (- (time-to-days
13329 (save-match-data
13330 (org-read-date nil t nil "Delay until" old-date-time)))
13331 (time-to-days old-date-time))))
13332 ">") t t))
13333 (user-error "No scheduled information to update"))))
13335 (org-add-planning-info 'scheduled time 'closed)
13336 (when (and old-date org-log-reschedule
13337 (not (equal old-date
13338 (substring org-last-inserted-timestamp 1 -1))))
13339 (org-add-log-setup 'reschedule nil old-date 'findpos
13340 org-log-reschedule))
13341 (when repeater
13342 (save-excursion
13343 (org-back-to-heading t)
13344 (when (re-search-forward (concat org-scheduled-string " "
13345 org-last-inserted-timestamp)
13346 (save-excursion
13347 (outline-next-heading) (point)) t)
13348 (goto-char (1- (match-end 0)))
13349 (insert " " repeater)
13350 (setq org-last-inserted-timestamp
13351 (concat (substring org-last-inserted-timestamp 0 -1)
13352 " " repeater
13353 (substring org-last-inserted-timestamp -1))))))
13354 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13356 (defun org-get-scheduled-time (pom &optional inherit)
13357 "Get the scheduled time as a time tuple, of a format suitable
13358 for calling org-schedule with, or if there is no scheduling,
13359 returns nil."
13360 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13361 (when time
13362 (apply 'encode-time (org-parse-time-string time)))))
13364 (defun org-get-deadline-time (pom &optional inherit)
13365 "Get the deadline as a time tuple, of a format suitable for
13366 calling org-deadline with, or if there is no scheduling, returns
13367 nil."
13368 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13369 (when time
13370 (apply 'encode-time (org-parse-time-string time)))))
13372 (defun org-remove-timestamp-with-keyword (keyword)
13373 "Remove all time stamps with KEYWORD in the current entry."
13374 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13375 beg)
13376 (save-excursion
13377 (org-back-to-heading t)
13378 (setq beg (point))
13379 (outline-next-heading)
13380 (while (re-search-backward re beg t)
13381 (replace-match "")
13382 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13383 (equal (char-before) ?\ ))
13384 (backward-delete-char 1)
13385 (if (string-match "^[ \t]*$" (buffer-substring
13386 (point-at-bol) (point-at-eol)))
13387 (delete-region (point-at-bol)
13388 (min (point-max) (1+ (point-at-eol))))))))))
13390 (defvar org-time-was-given) ; dynamically scoped parameter
13391 (defvar org-end-time-was-given) ; dynamically scoped parameter
13393 (defun org-add-planning-info (what &optional time &rest remove)
13394 "Insert new timestamp with keyword in the line directly after the headline.
13395 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13396 If non is given, the user is prompted for a date.
13397 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13398 be removed."
13399 (interactive)
13400 (let (org-time-was-given org-end-time-was-given ts
13401 end default-time default-input)
13403 (catch 'exit
13404 (when (and (memq what '(scheduled deadline))
13405 (or (not time)
13406 (and (stringp time)
13407 (string-match "^[-+]+[0-9]" time))))
13408 ;; Try to get a default date/time from existing timestamp
13409 (save-excursion
13410 (org-back-to-heading t)
13411 (setq end (save-excursion (outline-next-heading) (point)))
13412 (when (re-search-forward (if (eq what 'scheduled)
13413 org-scheduled-time-regexp
13414 org-deadline-time-regexp)
13415 end t)
13416 (setq ts (match-string 1)
13417 default-time
13418 (apply 'encode-time (org-parse-time-string ts))
13419 default-input (and ts (org-get-compact-tod ts))))))
13420 (when what
13421 (setq time
13422 (if (stringp time)
13423 ;; This is a string (relative or absolute), set proper date
13424 (apply 'encode-time
13425 (org-read-date-analyze
13426 time default-time (decode-time default-time)))
13427 ;; If necessary, get the time from the user
13428 (or time (org-read-date nil 'to-time nil nil
13429 default-time default-input)))))
13431 (when (and org-insert-labeled-timestamps-at-point
13432 (member what '(scheduled deadline)))
13433 (insert
13434 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13435 (org-insert-time-stamp time org-time-was-given
13436 nil nil nil (list org-end-time-was-given))
13437 (setq what nil))
13438 (save-excursion
13439 (save-restriction
13440 (let (col list elt ts buffer-invisibility-spec)
13441 (org-back-to-heading t)
13442 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13443 (goto-char (match-end 1))
13444 (setq col (current-column))
13445 (goto-char (match-end 0))
13446 (if (eobp) (insert "\n") (forward-char 1))
13447 (when (and (not what)
13448 (not (looking-at
13449 (concat "[ \t]*"
13450 org-keyword-time-not-clock-regexp))))
13451 ;; Nothing to add, nothing to remove...... :-)
13452 (throw 'exit nil))
13453 (if (and (not (looking-at org-outline-regexp))
13454 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13455 "[^\r\n]*"))
13456 (not (equal (match-string 1) org-clock-string)))
13457 (narrow-to-region (match-beginning 0) (match-end 0))
13458 (insert-before-markers "\n")
13459 (backward-char 1)
13460 (narrow-to-region (point) (point))
13461 (and org-adapt-indentation (org-indent-to-column col)))
13462 ;; Check if we have to remove something.
13463 (setq list (cons what remove))
13464 (while list
13465 (setq elt (pop list))
13466 (when (or (and (eq elt 'scheduled)
13467 (re-search-forward org-scheduled-time-regexp nil t))
13468 (and (eq elt 'deadline)
13469 (re-search-forward org-deadline-time-regexp nil t))
13470 (and (eq elt 'closed)
13471 (re-search-forward org-closed-time-regexp nil t)))
13472 (replace-match "")
13473 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13474 (and (looking-at "[ \t]+") (replace-match ""))
13475 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13476 (when what
13477 (insert
13478 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13479 (cond ((eq what 'scheduled) org-scheduled-string)
13480 ((eq what 'deadline) org-deadline-string)
13481 ((eq what 'closed) org-closed-string))
13482 " ")
13483 (setq ts (org-insert-time-stamp
13484 time
13485 (or org-time-was-given
13486 (and (eq what 'closed) org-log-done-with-time))
13487 (eq what 'closed)
13488 nil nil (list org-end-time-was-given)))
13489 (insert
13490 (if (not (or (bolp) (eq (char-before) ?\ )
13491 (memq (char-after) '(32 10))
13492 (eobp))) " " ""))
13493 (end-of-line 1))
13494 (goto-char (point-min))
13495 (widen)
13496 (if (and (looking-at "[ \t]*\n")
13497 (equal (char-before) ?\n))
13498 (delete-region (1- (point)) (point-at-eol)))
13499 ts))))))
13501 (defvar org-log-note-marker (make-marker))
13502 (defvar org-log-note-purpose nil)
13503 (defvar org-log-note-state nil)
13504 (defvar org-log-note-previous-state nil)
13505 (defvar org-log-note-extra nil)
13506 (defvar org-log-note-window-configuration nil)
13507 (defvar org-log-note-return-to (make-marker))
13508 (defvar org-log-note-effective-time nil
13509 "Remembered current time so that dynamically scoped
13510 `org-extend-today-until' affects tha timestamps in state change
13511 log")
13513 (defvar org-log-post-message nil
13514 "Message to be displayed after a log note has been stored.
13515 The auto-repeater uses this.")
13517 (defun org-add-note ()
13518 "Add a note to the current entry.
13519 This is done in the same way as adding a state change note."
13520 (interactive)
13521 (org-add-log-setup 'note nil nil 'findpos nil))
13523 (defvar org-property-end-re)
13524 (defun org-add-log-setup (&optional purpose state prev-state
13525 findpos how extra)
13526 "Set up the post command hook to take a note.
13527 If this is about to TODO state change, the new state is expected in STATE.
13528 When FINDPOS is non-nil, find the correct position for the note in
13529 the current entry. If not, assume that it can be inserted at point.
13530 HOW is an indicator what kind of note should be created.
13531 EXTRA is additional text that will be inserted into the notes buffer."
13532 (let* ((org-log-into-drawer (org-log-into-drawer))
13533 (drawer (cond ((stringp org-log-into-drawer)
13534 org-log-into-drawer)
13535 (org-log-into-drawer "LOGBOOK"))))
13536 (save-restriction
13537 (save-excursion
13538 (when findpos
13539 (org-back-to-heading t)
13540 (narrow-to-region (point) (save-excursion
13541 (outline-next-heading) (point)))
13542 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13543 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13544 "[^\r\n]*\\)?"))
13545 (goto-char (match-end 0))
13546 (cond
13547 (drawer
13548 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13549 nil t)
13550 (progn
13551 (goto-char (match-end 0))
13552 (or org-log-states-order-reversed
13553 (and (re-search-forward org-property-end-re nil t)
13554 (goto-char (1- (match-beginning 0))))))
13555 (insert "\n:" drawer ":\n:END:")
13556 (beginning-of-line 0)
13557 (org-indent-line)
13558 (beginning-of-line 2)
13559 (org-indent-line)
13560 (end-of-line 0)))
13561 ((and org-log-state-notes-insert-after-drawers
13562 (save-excursion
13563 (forward-line) (looking-at org-drawer-regexp)))
13564 (forward-line)
13565 (while (looking-at org-drawer-regexp)
13566 (goto-char (match-end 0))
13567 (re-search-forward org-property-end-re (point-max) t)
13568 (forward-line))
13569 (forward-line -1)))
13570 (unless org-log-states-order-reversed
13571 (and (= (char-after) ?\n) (forward-char 1))
13572 (org-skip-over-state-notes)
13573 (skip-chars-backward " \t\n\r")))
13574 (move-marker org-log-note-marker (point))
13575 (setq org-log-note-purpose purpose
13576 org-log-note-state state
13577 org-log-note-previous-state prev-state
13578 org-log-note-how how
13579 org-log-note-extra extra
13580 org-log-note-effective-time (org-current-effective-time))
13581 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13583 (defun org-skip-over-state-notes ()
13584 "Skip past the list of State notes in an entry."
13585 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13586 (when (ignore-errors (goto-char (org-in-item-p)))
13587 (let* ((struct (org-list-struct))
13588 (prevs (org-list-prevs-alist struct)))
13589 (while (looking-at "[ \t]*- State")
13590 (goto-char (or (org-list-get-next-item (point) struct prevs)
13591 (org-list-get-item-end (point) struct)))))))
13593 (defun org-add-log-note (&optional purpose)
13594 "Pop up a window for taking a note, and add this note later at point."
13595 (remove-hook 'post-command-hook 'org-add-log-note)
13596 (setq org-log-note-window-configuration (current-window-configuration))
13597 (delete-other-windows)
13598 (move-marker org-log-note-return-to (point))
13599 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13600 (goto-char org-log-note-marker)
13601 (org-switch-to-buffer-other-window "*Org Note*")
13602 (erase-buffer)
13603 (if (memq org-log-note-how '(time state))
13604 (let (current-prefix-arg) (org-store-log-note))
13605 (let ((org-inhibit-startup t)) (org-mode))
13606 (insert (format "# Insert note for %s.
13607 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13608 (cond
13609 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13610 ((eq org-log-note-purpose 'done) "closed todo item")
13611 ((eq org-log-note-purpose 'state)
13612 (format "state change from \"%s\" to \"%s\""
13613 (or org-log-note-previous-state "")
13614 (or org-log-note-state "")))
13615 ((eq org-log-note-purpose 'reschedule)
13616 "rescheduling")
13617 ((eq org-log-note-purpose 'delschedule)
13618 "no longer scheduled")
13619 ((eq org-log-note-purpose 'redeadline)
13620 "changing deadline")
13621 ((eq org-log-note-purpose 'deldeadline)
13622 "removing deadline")
13623 ((eq org-log-note-purpose 'refile)
13624 "refiling")
13625 ((eq org-log-note-purpose 'note)
13626 "this entry")
13627 (t (error "This should not happen")))))
13628 (if org-log-note-extra (insert org-log-note-extra))
13629 (org-set-local 'org-finish-function 'org-store-log-note)
13630 (run-hooks 'org-log-buffer-setup-hook)))
13632 (defvar org-note-abort nil) ; dynamically scoped
13633 (defun org-store-log-note ()
13634 "Finish taking a log note, and insert it to where it belongs."
13635 (let ((txt (buffer-string)))
13636 (kill-buffer (current-buffer))
13637 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13638 lines ind bul)
13639 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13640 (setq txt (replace-match "" t t txt)))
13641 (if (string-match "\\s-+\\'" txt)
13642 (setq txt (replace-match "" t t txt)))
13643 (setq lines (org-split-string txt "\n"))
13644 (when (and note (string-match "\\S-" note))
13645 (setq note
13646 (org-replace-escapes
13647 note
13648 (list (cons "%u" (user-login-name))
13649 (cons "%U" user-full-name)
13650 (cons "%t" (format-time-string
13651 (org-time-stamp-format 'long 'inactive)
13652 org-log-note-effective-time))
13653 (cons "%T" (format-time-string
13654 (org-time-stamp-format 'long nil)
13655 org-log-note-effective-time))
13656 (cons "%d" (format-time-string
13657 (org-time-stamp-format nil 'inactive)
13658 org-log-note-effective-time))
13659 (cons "%D" (format-time-string
13660 (org-time-stamp-format nil nil)
13661 org-log-note-effective-time))
13662 (cons "%s" (if org-log-note-state
13663 (concat "\"" org-log-note-state "\"")
13664 ""))
13665 (cons "%S" (if org-log-note-previous-state
13666 (concat "\"" org-log-note-previous-state "\"")
13667 "\"\"")))))
13668 (if lines (setq note (concat note " \\\\")))
13669 (push note lines))
13670 (when (or current-prefix-arg org-note-abort)
13671 (when org-log-into-drawer
13672 (org-remove-empty-drawer-at org-log-note-marker))
13673 (setq lines nil))
13674 (when lines
13675 (with-current-buffer (marker-buffer org-log-note-marker)
13676 (save-excursion
13677 (goto-char org-log-note-marker)
13678 (move-marker org-log-note-marker nil)
13679 (end-of-line 1)
13680 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13681 (setq ind (save-excursion
13682 (if (ignore-errors (goto-char (org-in-item-p)))
13683 (let ((struct (org-list-struct)))
13684 (org-list-get-ind
13685 (org-list-get-top-point struct) struct))
13686 (skip-chars-backward " \r\t\n")
13687 (cond
13688 ((and (org-at-heading-p)
13689 org-adapt-indentation)
13690 (1+ (org-current-level)))
13691 ((org-at-heading-p) 0)
13692 (t (org-get-indentation))))))
13693 (setq bul (org-list-bullet-string "-"))
13694 (org-indent-line-to ind)
13695 (insert bul (pop lines))
13696 (let ((ind-body (+ (length bul) ind)))
13697 (while lines
13698 (insert "\n")
13699 (org-indent-line-to ind-body)
13700 (insert (pop lines))))
13701 (message "Note stored")
13702 (org-back-to-heading t)
13703 (org-cycle-hide-drawers 'children))
13704 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13705 ;; from within `org-add-log-note' because `buffer-undo-list'
13706 ;; is then modified outside of `org-with-remote-undo'.
13707 (when (eq this-command 'org-agenda-todo)
13708 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13709 ;; Don't add undo information when called from `org-agenda-todo'
13710 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13711 (set-window-configuration org-log-note-window-configuration)
13712 (with-current-buffer (marker-buffer org-log-note-return-to)
13713 (goto-char org-log-note-return-to))
13714 (move-marker org-log-note-return-to nil)
13715 (and org-log-post-message (message "%s" org-log-post-message))))
13717 (defun org-remove-empty-drawer-at (pos)
13718 "Remove an empty drawer at position POS.
13719 POS may also be a marker."
13720 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13721 (org-with-wide-buffer
13722 (goto-char pos)
13723 (let ((drawer (org-element-at-point)))
13724 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13725 (not (org-element-property :contents-begin drawer)))
13726 (delete-region (org-element-property :begin drawer)
13727 (progn (goto-char (org-element-property :end drawer))
13728 (skip-chars-backward " \r\t\n")
13729 (forward-line)
13730 (point))))))))
13732 (defvar org-ts-type nil)
13733 (defun org-sparse-tree (&optional arg type)
13734 "Create a sparse tree, prompt for the details.
13735 This command can create sparse trees. You first need to select the type
13736 of match used to create the tree:
13738 t Show all TODO entries.
13739 T Show entries with a specific TODO keyword.
13740 m Show entries selected by a tags/property match.
13741 p Enter a property name and its value (both with completion on existing
13742 names/values) and show entries with that property.
13743 r Show entries matching a regular expression (`/' can be used as well).
13744 b Show deadlines and scheduled items before a date.
13745 a Show deadlines and scheduled items after a date.
13746 d Show deadlines due within `org-deadline-warning-days'.
13747 D Show deadlines and scheduled items between a date range."
13748 (interactive "P")
13749 (setq type (or type org-sparse-tree-default-date-type))
13750 (setq org-ts-type type)
13751 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13752 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13753 [c]ycle through date types: %s"
13754 (case type
13755 (all "all timestamps")
13756 (scheduled "only scheduled")
13757 (deadline "only deadline")
13758 (active "only active timestamps")
13759 (inactive "only inactive timestamps")
13760 (scheduled-or-deadline "scheduled/deadline")
13761 (closed "with a closed time-stamp")
13762 (otherwise "scheduled/deadline")))
13763 (let ((answer (read-char-exclusive)))
13764 (case answer
13766 (org-sparse-tree
13768 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13769 inactive closed)))))
13770 (?d (call-interactively 'org-check-deadlines))
13771 (?b (call-interactively 'org-check-before-date))
13772 (?a (call-interactively 'org-check-after-date))
13773 (?D (call-interactively 'org-check-dates-range))
13774 (?t (call-interactively 'org-show-todo-tree))
13775 (?T (org-show-todo-tree '(4)))
13776 (?m (call-interactively 'org-match-sparse-tree))
13777 ((?p ?P)
13778 (let* ((kwd (org-icompleting-read
13779 "Property: " (mapcar 'list (org-buffer-property-keys))))
13780 (value (org-icompleting-read
13781 "Value: " (mapcar 'list (org-property-values kwd)))))
13782 (unless (string-match "\\`{.*}\\'" value)
13783 (setq value (concat "\"" value "\"")))
13784 (org-match-sparse-tree arg (concat kwd "=" value))))
13785 ((?r ?R ?/) (call-interactively 'org-occur))
13786 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13788 (defvar org-occur-highlights nil
13789 "List of overlays used for occur matches.")
13790 (make-variable-buffer-local 'org-occur-highlights)
13791 (defvar org-occur-parameters nil
13792 "Parameters of the active org-occur calls.
13793 This is a list, each call to org-occur pushes as cons cell,
13794 containing the regular expression and the callback, onto the list.
13795 The list can contain several entries if `org-occur' has been called
13796 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13797 will only contain one set of parameters. When the highlights are
13798 removed (for example with `C-c C-c', or with the next edit (depending
13799 on `org-remove-highlights-with-change'), this variable is emptied
13800 as well.")
13801 (make-variable-buffer-local 'org-occur-parameters)
13803 (defun org-occur (regexp &optional keep-previous callback)
13804 "Make a compact tree which shows all matches of REGEXP.
13805 The tree will show the lines where the regexp matches, and all higher
13806 headlines above the match. It will also show the heading after the match,
13807 to make sure editing the matching entry is easy.
13808 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13809 call to `org-occur' will be kept, to allow stacking of calls to this
13810 command.
13811 If CALLBACK is non-nil, it is a function which is called to confirm
13812 that the match should indeed be shown."
13813 (interactive "sRegexp: \nP")
13814 (when (equal regexp "")
13815 (user-error "Regexp cannot be empty"))
13816 (unless keep-previous
13817 (org-remove-occur-highlights nil nil t))
13818 (push (cons regexp callback) org-occur-parameters)
13819 (let ((cnt 0))
13820 (save-excursion
13821 (goto-char (point-min))
13822 (if (or (not keep-previous) ; do not want to keep
13823 (not org-occur-highlights)) ; no previous matches
13824 ;; hide everything
13825 (org-overview))
13826 (while (re-search-forward regexp nil t)
13827 (when (or (not callback)
13828 (save-match-data (funcall callback)))
13829 (setq cnt (1+ cnt))
13830 (when org-highlight-sparse-tree-matches
13831 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13832 (org-show-context 'occur-tree))))
13833 (when org-remove-highlights-with-change
13834 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13835 nil 'local))
13836 (unless org-sparse-tree-open-archived-trees
13837 (org-hide-archived-subtrees (point-min) (point-max)))
13838 (run-hooks 'org-occur-hook)
13839 (if (org-called-interactively-p 'interactive)
13840 (message "%d match(es) for regexp %s" cnt regexp))
13841 cnt))
13843 (defun org-occur-next-match (&optional n reset)
13844 "Function for `next-error-function' to find sparse tree matches.
13845 N is the number of matches to move, when negative move backwards.
13846 RESET is entirely ignored - this function always goes back to the
13847 starting point when no match is found."
13848 (let* ((limit (if (< n 0) (point-min) (point-max)))
13849 (search-func (if (< n 0)
13850 'previous-single-char-property-change
13851 'next-single-char-property-change))
13852 (n (abs n))
13853 (pos (point))
13855 (catch 'exit
13856 (while (setq p1 (funcall search-func (point) 'org-type))
13857 (when (equal p1 limit)
13858 (goto-char pos)
13859 (user-error "No more matches"))
13860 (when (equal (get-char-property p1 'org-type) 'org-occur)
13861 (setq n (1- n))
13862 (when (= n 0)
13863 (goto-char p1)
13864 (throw 'exit (point))))
13865 (goto-char p1))
13866 (goto-char p1)
13867 (user-error "No more matches"))))
13869 (defun org-show-context (&optional key)
13870 "Make sure point and context are visible.
13871 How much context is shown depends upon the variables
13872 `org-show-hierarchy-above', `org-show-following-heading',
13873 `org-show-entry-below' and `org-show-siblings'."
13874 (let ((heading-p (org-at-heading-p t))
13875 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13876 (following-p (org-get-alist-option org-show-following-heading key))
13877 (entry-p (org-get-alist-option org-show-entry-below key))
13878 (siblings-p (org-get-alist-option org-show-siblings key)))
13879 ;; Show heading or entry text
13880 (if (and heading-p (not entry-p))
13881 (org-flag-heading nil) ; only show the heading
13882 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13883 (org-show-hidden-entry))) ; show entire entry
13884 (when following-p
13885 ;; Show next sibling, or heading below text
13886 (save-excursion
13887 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13888 (org-flag-heading nil))))
13889 (when siblings-p (org-show-siblings))
13890 (when hierarchy-p
13891 ;; show all higher headings, possibly with siblings
13892 (save-excursion
13893 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13894 (not (bobp)))
13895 (org-flag-heading nil)
13896 (when siblings-p (org-show-siblings)))))))
13898 (defvar org-reveal-start-hook nil
13899 "Hook run before revealing a location.")
13901 (defun org-reveal (&optional siblings)
13902 "Show current entry, hierarchy above it, and the following headline.
13903 This can be used to show a consistent set of context around locations
13904 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13905 not t for the search context.
13907 With optional argument SIBLINGS, on each level of the hierarchy all
13908 siblings are shown. This repairs the tree structure to what it would
13909 look like when opened with hierarchical calls to `org-cycle'.
13910 With double optional argument \\[universal-argument] \\[universal-argument], \
13911 go to the parent and show the
13912 entire tree."
13913 (interactive "P")
13914 (run-hooks 'org-reveal-start-hook)
13915 (let ((org-show-hierarchy-above t)
13916 (org-show-following-heading t)
13917 (org-show-siblings (if siblings t org-show-siblings)))
13918 (org-show-context nil))
13919 (when (equal siblings '(16))
13920 (save-excursion
13921 (when (org-up-heading-safe)
13922 (org-show-subtree)
13923 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13925 (defun org-highlight-new-match (beg end)
13926 "Highlight from BEG to END and mark the highlight is an occur headline."
13927 (let ((ov (make-overlay beg end)))
13928 (overlay-put ov 'face 'secondary-selection)
13929 (overlay-put ov 'org-type 'org-occur)
13930 (push ov org-occur-highlights)))
13932 (defun org-remove-occur-highlights (&optional beg end noremove)
13933 "Remove the occur highlights from the buffer.
13934 BEG and END are ignored. If NOREMOVE is nil, remove this function
13935 from the `before-change-functions' in the current buffer."
13936 (interactive)
13937 (unless org-inhibit-highlight-removal
13938 (mapc 'delete-overlay org-occur-highlights)
13939 (setq org-occur-highlights nil)
13940 (setq org-occur-parameters nil)
13941 (unless noremove
13942 (remove-hook 'before-change-functions
13943 'org-remove-occur-highlights 'local))))
13945 ;;;; Priorities
13947 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13948 "Regular expression matching the priority indicator.")
13950 (defvar org-remove-priority-next-time nil)
13952 (defun org-priority-up ()
13953 "Increase the priority of the current item."
13954 (interactive)
13955 (org-priority 'up))
13957 (defun org-priority-down ()
13958 "Decrease the priority of the current item."
13959 (interactive)
13960 (org-priority 'down))
13962 (defun org-priority (&optional action show)
13963 "Change the priority of an item.
13964 ACTION can be `set', `up', `down', or a character."
13965 (interactive "P")
13966 (if (equal action '(4))
13967 (org-show-priority)
13968 (unless org-enable-priority-commands
13969 (user-error "Priority commands are disabled"))
13970 (setq action (or action 'set))
13971 (let (current new news have remove)
13972 (save-excursion
13973 (org-back-to-heading t)
13974 (if (looking-at org-priority-regexp)
13975 (setq current (string-to-char (match-string 2))
13976 have t))
13977 (cond
13978 ((eq action 'remove)
13979 (setq remove t new ?\ ))
13980 ((or (eq action 'set)
13981 (if (featurep 'xemacs) (characterp action) (integerp action)))
13982 (if (not (eq action 'set))
13983 (setq new action)
13984 (message "Priority %c-%c, SPC to remove: "
13985 org-highest-priority org-lowest-priority)
13986 (save-match-data
13987 (setq new (read-char-exclusive))))
13988 (if (and (= (upcase org-highest-priority) org-highest-priority)
13989 (= (upcase org-lowest-priority) org-lowest-priority))
13990 (setq new (upcase new)))
13991 (cond ((equal new ?\ ) (setq remove t))
13992 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13993 (user-error "Priority must be between `%c' and `%c'"
13994 org-highest-priority org-lowest-priority))))
13995 ((eq action 'up)
13996 (setq new (if have
13997 (1- current) ; normal cycling
13998 ;; last priority was empty
13999 (if (eq last-command this-command)
14000 org-lowest-priority ; wrap around empty to lowest
14001 ;; default
14002 (if org-priority-start-cycle-with-default
14003 org-default-priority
14004 (1- org-default-priority))))))
14005 ((eq action 'down)
14006 (setq new (if have
14007 (1+ current) ; normal cycling
14008 ;; last priority was empty
14009 (if (eq last-command this-command)
14010 org-highest-priority ; wrap around empty to highest
14011 ;; default
14012 (if org-priority-start-cycle-with-default
14013 org-default-priority
14014 (1+ org-default-priority))))))
14015 (t (user-error "Invalid action")))
14016 (if (or (< (upcase new) org-highest-priority)
14017 (> (upcase new) org-lowest-priority))
14018 (if (and (memq action '(up down))
14019 (not have) (not (eq last-command this-command)))
14020 ;; `new' is from default priority
14021 (error
14022 "The default can not be set, see `org-default-priority' why")
14023 ;; normal cycling: `new' is beyond highest/lowest priority
14024 ;; and is wrapped around to the empty priority
14025 (setq remove t)))
14026 (setq news (format "%c" new))
14027 (if have
14028 (if remove
14029 (replace-match "" t t nil 1)
14030 (replace-match news t t nil 2))
14031 (if remove
14032 (user-error "No priority cookie found in line")
14033 (let ((case-fold-search nil))
14034 (looking-at org-todo-line-regexp))
14035 (if (match-end 2)
14036 (progn
14037 (goto-char (match-end 2))
14038 (insert " [#" news "]"))
14039 (goto-char (match-beginning 3))
14040 (insert "[#" news "] "))))
14041 (org-set-tags nil 'align))
14042 (if remove
14043 (message "Priority removed")
14044 (message "Priority of current item set to %s" news)))))
14046 (defun org-show-priority ()
14047 "Show the priority of the current item.
14048 This priority is composed of the main priority given with the [#A] cookies,
14049 and by additional input from the age of a schedules or deadline entry."
14050 (interactive)
14051 (let ((pri (if (eq major-mode 'org-agenda-mode)
14052 (org-get-at-bol 'priority)
14053 (save-excursion
14054 (save-match-data
14055 (beginning-of-line)
14056 (and (looking-at org-heading-regexp)
14057 (org-get-priority (match-string 0))))))))
14058 (message "Priority is %d" (if pri pri -1000))))
14060 (defun org-get-priority (s)
14061 "Find priority cookie and return priority."
14062 (save-match-data
14063 (if (functionp org-get-priority-function)
14064 (funcall org-get-priority-function)
14065 (if (not (string-match org-priority-regexp s))
14066 (* 1000 (- org-lowest-priority org-default-priority))
14067 (* 1000 (- org-lowest-priority
14068 (string-to-char (match-string 2 s))))))))
14070 ;;;; Tags
14072 (defvar org-agenda-archives-mode)
14073 (defvar org-map-continue-from nil
14074 "Position from where mapping should continue.
14075 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14077 (defvar org-scanner-tags nil
14078 "The current tag list while the tags scanner is running.")
14079 (defvar org-trust-scanner-tags nil
14080 "Should `org-get-tags-at' use the tags for the scanner.
14081 This is for internal dynamical scoping only.
14082 When this is non-nil, the function `org-get-tags-at' will return the value
14083 of `org-scanner-tags' instead of building the list by itself. This
14084 can lead to large speed-ups when the tags scanner is used in a file with
14085 many entries, and when the list of tags is retrieved, for example to
14086 obtain a list of properties. Building the tags list for each entry in such
14087 a file becomes an N^2 operation - but with this variable set, it scales
14088 as N.")
14090 (defun org-scan-tags (action matcher todo-only &optional start-level)
14091 "Scan headline tags with inheritance and produce output ACTION.
14093 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14094 or `agenda' to produce an entry list for an agenda view. It can also be
14095 a Lisp form or a function that should be called at each matched headline, in
14096 this case the return value is a list of all return values from these calls.
14098 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14099 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14100 only lines with a not-done TODO keyword are included in the output.
14101 This should be the same variable that was scoped into
14102 and set by `org-make-tags-matcher' when it constructed MATCHER.
14104 START-LEVEL can be a string with asterisks, reducing the scope to
14105 headlines matching this string."
14106 (require 'org-agenda)
14107 (let* ((re (concat "^"
14108 (if start-level
14109 ;; Get the correct level to match
14110 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14111 org-outline-regexp)
14112 " *\\(\\<\\("
14113 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14114 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14115 (props (list 'face 'default
14116 'done-face 'org-agenda-done
14117 'undone-face 'default
14118 'mouse-face 'highlight
14119 'org-not-done-regexp org-not-done-regexp
14120 'org-todo-regexp org-todo-regexp
14121 'org-complex-heading-regexp org-complex-heading-regexp
14122 'help-echo
14123 (format "mouse-2 or RET jump to org file %s"
14124 (abbreviate-file-name
14125 (or (buffer-file-name (buffer-base-buffer))
14126 (buffer-name (buffer-base-buffer)))))))
14127 (org-map-continue-from nil)
14128 lspos tags tags-list
14129 (tags-alist (list (cons 0 org-file-tags)))
14130 (llast 0) rtn rtn1 level category i txt
14131 todo marker entry priority)
14132 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14133 (setq action (list 'lambda nil action)))
14134 (save-excursion
14135 (goto-char (point-min))
14136 (when (eq action 'sparse-tree)
14137 (org-overview)
14138 (org-remove-occur-highlights))
14139 (while (let (case-fold-search)
14140 (re-search-forward re nil t))
14141 (setq org-map-continue-from nil)
14142 (catch :skip
14143 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14144 tags (if (match-end 4) (org-match-string-no-properties 4)))
14145 (goto-char (setq lspos (match-beginning 0)))
14146 (setq level (org-reduced-level (org-outline-level))
14147 category (org-get-category))
14148 (setq i llast llast level)
14149 ;; remove tag lists from same and sublevels
14150 (while (>= i level)
14151 (when (setq entry (assoc i tags-alist))
14152 (setq tags-alist (delete entry tags-alist)))
14153 (setq i (1- i)))
14154 ;; add the next tags
14155 (when tags
14156 (setq tags (org-split-string tags ":")
14157 tags-alist
14158 (cons (cons level tags) tags-alist)))
14159 ;; compile tags for current headline
14160 (setq tags-list
14161 (if org-use-tag-inheritance
14162 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14163 tags)
14164 org-scanner-tags tags-list)
14165 (when org-use-tag-inheritance
14166 (setcdr (car tags-alist)
14167 (mapcar (lambda (x)
14168 (setq x (copy-sequence x))
14169 (org-add-prop-inherited x))
14170 (cdar tags-alist))))
14171 (when (and tags org-use-tag-inheritance
14172 (or (not (eq t org-use-tag-inheritance))
14173 org-tags-exclude-from-inheritance))
14174 ;; selective inheritance, remove uninherited ones
14175 (setcdr (car tags-alist)
14176 (org-remove-uninherited-tags (cdar tags-alist))))
14177 (when (and
14179 ;; eval matcher only when the todo condition is OK
14180 (and (or (not todo-only) (member todo org-not-done-keywords))
14181 (let ((case-fold-search t) (org-trust-scanner-tags t))
14182 (eval matcher)))
14184 ;; Call the skipper, but return t if it does not skip,
14185 ;; so that the `and' form continues evaluating
14186 (progn
14187 (unless (eq action 'sparse-tree) (org-agenda-skip))
14190 ;; Check if timestamps are deselecting this entry
14191 (or (not todo-only)
14192 (and (member todo org-not-done-keywords)
14193 (or (not org-agenda-tags-todo-honor-ignore-options)
14194 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14196 ;; select this headline
14197 (cond
14198 ((eq action 'sparse-tree)
14199 (and org-highlight-sparse-tree-matches
14200 (org-get-heading) (match-end 0)
14201 (org-highlight-new-match
14202 (match-beginning 1) (match-end 1)))
14203 (org-show-context 'tags-tree))
14204 ((eq action 'agenda)
14205 (setq txt (org-agenda-format-item
14207 (concat
14208 (if (eq org-tags-match-list-sublevels 'indented)
14209 (make-string (1- level) ?.) "")
14210 (org-get-heading))
14211 level category
14212 tags-list)
14213 priority (org-get-priority txt))
14214 (goto-char lspos)
14215 (setq marker (org-agenda-new-marker))
14216 (org-add-props txt props
14217 'org-marker marker 'org-hd-marker marker 'org-category category
14218 'todo-state todo
14219 'priority priority 'type "tagsmatch")
14220 (push txt rtn))
14221 ((functionp action)
14222 (setq org-map-continue-from nil)
14223 (save-excursion
14224 (setq rtn1 (funcall action))
14225 (push rtn1 rtn)))
14226 (t (user-error "Invalid action")))
14228 ;; if we are to skip sublevels, jump to end of subtree
14229 (unless org-tags-match-list-sublevels
14230 (org-end-of-subtree t)
14231 (backward-char 1))))
14232 ;; Get the correct position from where to continue
14233 (if org-map-continue-from
14234 (goto-char org-map-continue-from)
14235 (and (= (point) lspos) (end-of-line 1)))))
14236 (when (and (eq action 'sparse-tree)
14237 (not org-sparse-tree-open-archived-trees))
14238 (org-hide-archived-subtrees (point-min) (point-max)))
14239 (nreverse rtn)))
14241 (defun org-remove-uninherited-tags (tags)
14242 "Remove all tags that are not inherited from the list TAGS."
14243 (cond
14244 ((eq org-use-tag-inheritance t)
14245 (if org-tags-exclude-from-inheritance
14246 (org-delete-all org-tags-exclude-from-inheritance tags)
14247 tags))
14248 ((not org-use-tag-inheritance) nil)
14249 ((stringp org-use-tag-inheritance)
14250 (delq nil (mapcar
14251 (lambda (x)
14252 (if (and (string-match org-use-tag-inheritance x)
14253 (not (member x org-tags-exclude-from-inheritance)))
14254 x nil))
14255 tags)))
14256 ((listp org-use-tag-inheritance)
14257 (delq nil (mapcar
14258 (lambda (x)
14259 (if (member x org-use-tag-inheritance) x nil))
14260 tags)))))
14262 (defun org-match-sparse-tree (&optional todo-only match)
14263 "Create a sparse tree according to tags string MATCH.
14264 MATCH can contain positive and negative selection of tags, like
14265 \"+WORK+URGENT-WITHBOSS\".
14266 If optional argument TODO-ONLY is non-nil, only select lines that are
14267 also TODO lines."
14268 (interactive "P")
14269 (org-agenda-prepare-buffers (list (current-buffer)))
14270 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14272 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14274 (defvar org-cached-props nil)
14275 (defun org-cached-entry-get (pom property)
14276 (if (or (eq t org-use-property-inheritance)
14277 (and (stringp org-use-property-inheritance)
14278 (string-match org-use-property-inheritance property))
14279 (and (listp org-use-property-inheritance)
14280 (member property org-use-property-inheritance)))
14281 ;; Caching is not possible, check it directly
14282 (org-entry-get pom property 'inherit)
14283 ;; Get all properties, so that we can do complicated checks easily
14284 (cdr (assoc property (or org-cached-props
14285 (setq org-cached-props
14286 (org-entry-properties pom)))))))
14288 (defun org-global-tags-completion-table (&optional files)
14289 "Return the list of all tags in all agenda buffer/files.
14290 Optional FILES argument is a list of files which can be used
14291 instead of the agenda files."
14292 (save-excursion
14293 (org-uniquify
14294 (delq nil
14295 (apply 'append
14296 (mapcar
14297 (lambda (file)
14298 (set-buffer (find-file-noselect file))
14299 (append (org-get-buffer-tags)
14300 (mapcar (lambda (x) (if (stringp (car-safe x))
14301 (list (car-safe x)) nil))
14302 org-tag-alist)))
14303 (if (and files (car files))
14304 files
14305 (org-agenda-files))))))))
14307 (defun org-make-tags-matcher (match)
14308 "Create the TAGS/TODO matcher form for the selection string MATCH.
14310 The variable `todo-only' is scoped dynamically into this function.
14311 It will be set to t if the matcher restricts matching to TODO entries,
14312 otherwise will not be touched.
14314 Returns a cons of the selection string MATCH and the constructed
14315 lisp form implementing the matcher. The matcher is to be evaluated
14316 at an Org entry, with point on the headline, and returns t if the
14317 entry matches the selection string MATCH. The returned lisp form
14318 references two variables with information about the entry, which
14319 must be bound around the form's evaluation: todo, the TODO keyword
14320 at the entry (or nil of none); and tags-list, the list of all tags
14321 at the entry including inherited ones. Additionally, the category
14322 of the entry (if any) must be specified as the text property
14323 'org-category on the headline.
14325 See also `org-scan-tags'.
14327 (declare (special todo-only))
14328 (unless (boundp 'todo-only)
14329 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14330 (unless match
14331 ;; Get a new match request, with completion against the global
14332 ;; tags table and the local tags in current buffer
14333 (let ((org-last-tags-completion-table
14334 (org-uniquify
14335 (delq nil (append (org-get-buffer-tags)
14336 (org-global-tags-completion-table))))))
14337 (setq match (org-completing-read-no-i
14338 "Match: " 'org-tags-completion-function nil nil nil
14339 'org-tags-history))))
14341 ;; Parse the string and create a lisp form
14342 (let ((match0 match)
14343 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14344 minus tag mm
14345 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14346 orterms term orlist re-p str-p level-p level-op time-p
14347 prop-p pn pv po gv rest (start 0) (ss 0))
14348 ;; Expand group tags
14349 (setq match (org-tags-expand match))
14351 ;; Check if there is a TODO part of this match, which would be the
14352 ;; part after a "/". TO make sure that this slash is not part of
14353 ;; a property value to be matched against, we also check that there
14354 ;; is no " after that slash.
14355 ;; First, find the last slash
14356 (while (string-match "/+" match ss)
14357 (setq start (match-beginning 0) ss (match-end 0)))
14358 (if (and (string-match "/+" match start)
14359 (not (save-match-data (string-match "\"" match start))))
14360 ;; match contains also a todo-matching request
14361 (progn
14362 (setq tagsmatch (substring match 0 (match-beginning 0))
14363 todomatch (substring match (match-end 0)))
14364 (if (string-match "^!" todomatch)
14365 (setq todo-only t todomatch (substring todomatch 1)))
14366 (if (string-match "^\\s-*$" todomatch)
14367 (setq todomatch nil)))
14368 ;; only matching tags
14369 (setq tagsmatch match todomatch nil))
14371 ;; Make the tags matcher
14372 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14373 (setq tagsmatcher t)
14374 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14375 (while (setq term (pop orterms))
14376 (while (and (equal (substring term -1) "\\") orterms)
14377 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14378 (while (string-match re term)
14379 (setq rest (substring term (match-end 0))
14380 minus (and (match-end 1)
14381 (equal (match-string 1 term) "-"))
14382 tag (save-match-data (replace-regexp-in-string
14383 "\\\\-" "-"
14384 (match-string 2 term)))
14385 re-p (equal (string-to-char tag) ?{)
14386 level-p (match-end 4)
14387 prop-p (match-end 5)
14388 mm (cond
14389 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14390 (level-p
14391 (setq level-op (org-op-to-function (match-string 3 term)))
14392 `(,level-op level ,(string-to-number
14393 (match-string 4 term))))
14394 (prop-p
14395 (setq pn (match-string 5 term)
14396 po (match-string 6 term)
14397 pv (match-string 7 term)
14398 re-p (equal (string-to-char pv) ?{)
14399 str-p (equal (string-to-char pv) ?\")
14400 time-p (save-match-data
14401 (string-match "^\"[[<].*[]>]\"$" pv))
14402 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14403 (if time-p (setq pv (org-matcher-time pv)))
14404 (setq po (org-op-to-function po (if time-p 'time str-p)))
14405 (cond
14406 ((equal pn "CATEGORY")
14407 (setq gv '(get-text-property (point) 'org-category)))
14408 ((equal pn "TODO")
14409 (setq gv 'todo))
14411 (setq gv `(org-cached-entry-get nil ,pn))))
14412 (if re-p
14413 (if (eq po 'org<>)
14414 `(not (string-match ,pv (or ,gv "")))
14415 `(string-match ,pv (or ,gv "")))
14416 (if str-p
14417 `(,po (or ,gv "") ,pv)
14418 `(,po (string-to-number (or ,gv ""))
14419 ,(string-to-number pv) ))))
14420 (t `(member ,tag tags-list)))
14421 mm (if minus (list 'not mm) mm)
14422 term rest)
14423 (push mm tagsmatcher))
14424 (push (if (> (length tagsmatcher) 1)
14425 (cons 'and tagsmatcher)
14426 (car tagsmatcher))
14427 orlist)
14428 (setq tagsmatcher nil))
14429 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14430 (setq tagsmatcher
14431 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14432 ;; Make the todo matcher
14433 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14434 (setq todomatcher t)
14435 (setq orterms (org-split-string todomatch "|") orlist nil)
14436 (while (setq term (pop orterms))
14437 (while (string-match re term)
14438 (setq minus (and (match-end 1)
14439 (equal (match-string 1 term) "-"))
14440 kwd (match-string 2 term)
14441 re-p (equal (string-to-char kwd) ?{)
14442 term (substring term (match-end 0))
14443 mm (if re-p
14444 `(string-match ,(substring kwd 1 -1) todo)
14445 (list 'equal 'todo kwd))
14446 mm (if minus (list 'not mm) mm))
14447 (push mm todomatcher))
14448 (push (if (> (length todomatcher) 1)
14449 (cons 'and todomatcher)
14450 (car todomatcher))
14451 orlist)
14452 (setq todomatcher nil))
14453 (setq todomatcher (if (> (length orlist) 1)
14454 (cons 'or orlist) (car orlist))))
14456 ;; Return the string and lisp forms of the matcher
14457 (setq matcher (if todomatcher
14458 (list 'and tagsmatcher todomatcher)
14459 tagsmatcher))
14460 (when todo-only
14461 (setq matcher (list 'and '(member todo org-not-done-keywords)
14462 matcher)))
14463 (cons match0 matcher)))
14465 (defun org-tags-expand (match &optional single-as-list downcased)
14466 "Expand group tags in MATCH.
14468 This replaces every group tag in MATCH with a regexp tag search.
14469 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14470 will be replaced like this:
14472 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14473 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14474 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14476 Replacing by a regexp preserves the structure of the match.
14477 E.g., this expansion
14479 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14481 will match anything tagged with \"Lab\" and \"Home\", or tagged
14482 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14484 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14485 assumed to be a single group tag, and the function will return
14486 the list of tags in this group.
14488 When DOWNCASE is non-nil, expand downcased TAGS."
14489 (if org-group-tags
14490 (let* ((case-fold-search t)
14491 (stable org-mode-syntax-table)
14492 (tal (or org-tag-groups-alist-for-agenda
14493 org-tag-groups-alist))
14494 (tal (if downcased
14495 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14496 (tml (mapcar 'car tal))
14497 (rtnmatch match) rpl)
14498 ;; @ and _ are allowed as word-components in tags
14499 (modify-syntax-entry ?@ "w" stable)
14500 (modify-syntax-entry ?_ "w" stable)
14501 (while (and tml
14502 (with-syntax-table stable
14503 (string-match
14504 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14505 (regexp-opt tml) "\\>\\)") rtnmatch)))
14506 (let* ((dir (match-string 1 rtnmatch))
14507 (tag (match-string 2 rtnmatch))
14508 (tag (if downcased (downcase tag) tag)))
14509 (setq tml (delete tag tml))
14510 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14511 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14512 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14513 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14514 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14515 (if single-as-list
14516 (or (reverse rpl) (list rtnmatch))
14517 rtnmatch))
14518 (if single-as-list (list (if downcased (downcase match) match))
14519 match)))
14521 (defun org-op-to-function (op &optional stringp)
14522 "Turn an operator into the appropriate function."
14523 (setq op
14524 (cond
14525 ((equal op "<" ) '(< string< org-time<))
14526 ((equal op ">" ) '(> org-string> org-time>))
14527 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14528 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14529 ((member op '("=" "==")) '(= string= org-time=))
14530 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14531 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14533 (defun org<> (a b) (not (= a b)))
14534 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14535 (defun org-string>= (a b) (not (string< a b)))
14536 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14537 (defun org-string<> (a b) (not (string= a b)))
14538 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14539 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14540 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14541 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14542 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14543 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14544 (defun org-2ft (s)
14545 "Convert S to a floating point time.
14546 If S is already a number, just return it. If it is a string, parse
14547 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14548 (cond
14549 ((numberp s) s)
14550 ((stringp s)
14551 (condition-case nil
14552 (float-time (apply 'encode-time (org-parse-time-string s)))
14553 (error 0.)))
14554 (t 0.)))
14556 (defun org-time-today ()
14557 "Time in seconds today at 0:00.
14558 Returns the float number of seconds since the beginning of the
14559 epoch to the beginning of today (00:00)."
14560 (float-time (apply 'encode-time
14561 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14563 (defun org-matcher-time (s)
14564 "Interpret a time comparison value."
14565 (save-match-data
14566 (cond
14567 ((string= s "<now>") (float-time))
14568 ((string= s "<today>") (org-time-today))
14569 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14570 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14571 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14572 (+ (org-time-today)
14573 (* (string-to-number (match-string 1 s))
14574 (cdr (assoc (match-string 2 s)
14575 '(("d" . 86400.0) ("w" . 604800.0)
14576 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14577 (t (org-2ft s)))))
14579 (defun org-match-any-p (re list)
14580 "Does re match any element of list?"
14581 (setq list (mapcar (lambda (x) (string-match re x)) list))
14582 (delq nil list))
14584 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14585 (defvar org-tags-overlay (make-overlay 1 1))
14586 (org-detach-overlay org-tags-overlay)
14588 (defun org-get-local-tags-at (&optional pos)
14589 "Get a list of tags defined in the current headline."
14590 (org-get-tags-at pos 'local))
14592 (defun org-get-local-tags ()
14593 "Get a list of tags defined in the current headline."
14594 (org-get-tags-at nil 'local))
14596 (defun org-get-tags-at (&optional pos local)
14597 "Get a list of all headline tags applicable at POS.
14598 POS defaults to point. If tags are inherited, the list contains
14599 the targets in the same sequence as the headlines appear, i.e.
14600 the tags of the current headline come last.
14601 When LOCAL is non-nil, only return tags from the current headline,
14602 ignore inherited ones."
14603 (interactive)
14604 (if (and org-trust-scanner-tags
14605 (or (not pos) (equal pos (point)))
14606 (not local))
14607 org-scanner-tags
14608 (let (tags ltags lastpos parent)
14609 (save-excursion
14610 (save-restriction
14611 (widen)
14612 (goto-char (or pos (point)))
14613 (save-match-data
14614 (catch 'done
14615 (condition-case nil
14616 (progn
14617 (org-back-to-heading t)
14618 (while (not (equal lastpos (point)))
14619 (setq lastpos (point))
14620 (when (looking-at
14621 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14622 (setq ltags (org-split-string
14623 (org-match-string-no-properties 1) ":"))
14624 (when parent
14625 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14626 (setq tags (append
14627 (if parent
14628 (org-remove-uninherited-tags ltags)
14629 ltags)
14630 tags)))
14631 (or org-use-tag-inheritance (throw 'done t))
14632 (if local (throw 'done t))
14633 (or (org-up-heading-safe) (error nil))
14634 (setq parent t)))
14635 (error nil)))))
14636 (if local
14637 tags
14638 (reverse (delete-dups
14639 (reverse (append
14640 (org-remove-uninherited-tags
14641 org-file-tags) tags)))))))))
14643 (defun org-add-prop-inherited (s)
14644 (add-text-properties 0 (length s) '(inherited t) s)
14647 (defun org-toggle-tag (tag &optional onoff)
14648 "Toggle the tag TAG for the current line.
14649 If ONOFF is `on' or `off', don't toggle but set to this state."
14650 (let (res current)
14651 (save-excursion
14652 (org-back-to-heading t)
14653 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14654 (point-at-eol) t)
14655 (progn
14656 (setq current (match-string 1))
14657 (replace-match ""))
14658 (setq current ""))
14659 (setq current (nreverse (org-split-string current ":")))
14660 (cond
14661 ((eq onoff 'on)
14662 (setq res t)
14663 (or (member tag current) (push tag current)))
14664 ((eq onoff 'off)
14665 (or (not (member tag current)) (setq current (delete tag current))))
14666 (t (if (member tag current)
14667 (setq current (delete tag current))
14668 (setq res t)
14669 (push tag current))))
14670 (end-of-line 1)
14671 (if current
14672 (progn
14673 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14674 (org-set-tags nil t))
14675 (delete-horizontal-space))
14676 (run-hooks 'org-after-tags-change-hook))
14677 res))
14679 (defun org-align-tags-here (to-col)
14680 ;; Assumes that this is a headline
14681 "Align tags on the current headline to TO-COL."
14682 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14683 (beginning-of-line 1)
14684 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14685 (< pos (match-beginning 2)))
14686 (progn
14687 (setq tags-l (- (match-end 2) (match-beginning 2)))
14688 (goto-char (match-beginning 1))
14689 (insert " ")
14690 (delete-region (point) (1+ (match-beginning 2)))
14691 (setq ncol (max (current-column)
14692 (1+ col)
14693 (if (> to-col 0)
14694 to-col
14695 (- (abs to-col) tags-l))))
14696 (setq p (point))
14697 (insert (make-string (- ncol (current-column)) ?\ ))
14698 (setq ncol (current-column))
14699 (when indent-tabs-mode (tabify p (point-at-eol)))
14700 (org-move-to-column (min ncol col)))
14701 (goto-char pos))))
14703 (defun org-set-tags-command (&optional arg just-align)
14704 "Call the set-tags command for the current entry."
14705 (interactive "P")
14706 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14707 (org-set-tags arg just-align)
14708 (save-excursion
14709 (unless (and (org-region-active-p)
14710 org-loop-over-headlines-in-active-region)
14711 (org-back-to-heading t))
14712 (org-set-tags arg just-align))))
14714 (defun org-set-tags-to (data)
14715 "Set the tags of the current entry to DATA, replacing the current tags.
14716 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14717 If DATA is nil or the empty string, any tags will be removed."
14718 (interactive "sTags: ")
14719 (setq data
14720 (cond
14721 ((eq data nil) "")
14722 ((equal data "") "")
14723 ((stringp data)
14724 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14725 ":"))
14726 ((listp data)
14727 (concat ":" (mapconcat 'identity data ":") ":"))))
14728 (when data
14729 (save-excursion
14730 (org-back-to-heading t)
14731 (when (looking-at org-complex-heading-regexp)
14732 (if (match-end 5)
14733 (progn
14734 (goto-char (match-beginning 5))
14735 (insert data)
14736 (delete-region (point) (point-at-eol))
14737 (org-set-tags nil 'align))
14738 (goto-char (point-at-eol))
14739 (insert " " data)
14740 (org-set-tags nil 'align)))
14741 (beginning-of-line 1)
14742 (if (looking-at ".*?\\([ \t]+\\)$")
14743 (delete-region (match-beginning 1) (match-end 1))))))
14745 (defun org-align-all-tags ()
14746 "Align the tags i all headings."
14747 (interactive)
14748 (save-excursion
14749 (or (ignore-errors (org-back-to-heading t))
14750 (outline-next-heading))
14751 (if (org-at-heading-p)
14752 (org-set-tags t)
14753 (message "No headings"))))
14755 (defvar org-indent-indentation-per-level)
14756 (defun org-set-tags (&optional arg just-align)
14757 "Set the tags for the current headline.
14758 With prefix ARG, realign all tags in headings in the current buffer.
14759 When JUST-ALIGN is non-nil, only align tags."
14760 (interactive "P")
14761 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14762 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14763 'region-start-level 'region))
14764 org-loop-over-headlines-in-active-region)
14765 (org-map-entries
14766 ;; We don't use ARG and JUST-ALIGN here because these args
14767 ;; are not useful when looping over headlines.
14768 `(org-set-tags)
14769 org-loop-over-headlines-in-active-region
14770 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14771 (let* ((re org-outline-regexp-bol)
14772 (current (unless arg (org-get-tags-string)))
14773 (col (current-column))
14774 (org-setting-tags t)
14775 table current-tags inherited-tags ; computed below when needed
14776 tags p0 c0 c1 rpl di tc level)
14777 (if arg
14778 (save-excursion
14779 (goto-char (point-min))
14780 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14781 (while (re-search-forward re nil t)
14782 (org-set-tags nil t)
14783 (end-of-line 1)))
14784 (message "All tags realigned to column %d" org-tags-column))
14785 (if just-align
14786 (setq tags current)
14787 ;; Get a new set of tags from the user
14788 (save-excursion
14789 (setq table (append org-tag-persistent-alist
14790 (or org-tag-alist (org-get-buffer-tags))
14791 (and
14792 org-complete-tags-always-offer-all-agenda-tags
14793 (org-global-tags-completion-table
14794 (org-agenda-files))))
14795 org-last-tags-completion-table table
14796 current-tags (org-split-string current ":")
14797 inherited-tags (nreverse
14798 (nthcdr (length current-tags)
14799 (nreverse (org-get-tags-at))))
14800 tags
14801 (if (or (eq t org-use-fast-tag-selection)
14802 (and org-use-fast-tag-selection
14803 (delq nil (mapcar 'cdr table))))
14804 (org-fast-tag-selection
14805 current-tags inherited-tags table
14806 (if org-fast-tag-selection-include-todo
14807 org-todo-key-alist))
14808 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14809 (org-trim
14810 (org-icompleting-read "Tags: "
14811 'org-tags-completion-function
14812 nil nil current 'org-tags-history))))))
14813 (while (string-match "[-+&]+" tags)
14814 ;; No boolean logic, just a list
14815 (setq tags (replace-match ":" t t tags))))
14817 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14819 (if org-tags-sort-function
14820 (setq tags (mapconcat 'identity
14821 (sort (org-split-string
14822 tags (org-re "[^[:alnum:]_@#%]+"))
14823 org-tags-sort-function) ":")))
14825 (if (string-match "\\`[\t ]*\\'" tags)
14826 (setq tags "")
14827 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14828 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14830 ;; Insert new tags at the correct column
14831 (beginning-of-line 1)
14832 (setq level (or (and (looking-at org-outline-regexp)
14833 (- (match-end 0) (point) 1))
14835 (cond
14836 ((and (equal current "") (equal tags "")))
14837 ((re-search-forward
14838 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14839 (point-at-eol) t)
14840 (if (equal tags "")
14841 (setq rpl "")
14842 (goto-char (match-beginning 0))
14843 (setq c0 (current-column)
14844 ;; compute offset for the case of org-indent-mode active
14845 di (if (org-bound-and-true-p org-indent-mode)
14846 (* (1- org-indent-indentation-per-level) (1- level))
14848 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14849 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14850 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14851 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14852 (replace-match rpl t t)
14853 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14854 tags)
14855 (t (error "Tags alignment failed")))
14856 (org-move-to-column col)
14857 (unless just-align
14858 (run-hooks 'org-after-tags-change-hook))))))
14860 (defun org-change-tag-in-region (beg end tag off)
14861 "Add or remove TAG for each entry in the region.
14862 This works in the agenda, and also in an org-mode buffer."
14863 (interactive
14864 (list (region-beginning) (region-end)
14865 (let ((org-last-tags-completion-table
14866 (if (derived-mode-p 'org-mode)
14867 (org-uniquify
14868 (delq nil (append (org-get-buffer-tags)
14869 (org-global-tags-completion-table))))
14870 (org-global-tags-completion-table))))
14871 (org-icompleting-read
14872 "Tag: " 'org-tags-completion-function nil nil nil
14873 'org-tags-history))
14874 (progn
14875 (message "[s]et or [r]emove? ")
14876 (equal (read-char-exclusive) ?r))))
14877 (if (fboundp 'deactivate-mark) (deactivate-mark))
14878 (let ((agendap (equal major-mode 'org-agenda-mode))
14879 l1 l2 m buf pos newhead (cnt 0))
14880 (goto-char end)
14881 (setq l2 (1- (org-current-line)))
14882 (goto-char beg)
14883 (setq l1 (org-current-line))
14884 (loop for l from l1 to l2 do
14885 (org-goto-line l)
14886 (setq m (get-text-property (point) 'org-hd-marker))
14887 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14888 (and agendap m))
14889 (setq buf (if agendap (marker-buffer m) (current-buffer))
14890 pos (if agendap m (point)))
14891 (with-current-buffer buf
14892 (save-excursion
14893 (save-restriction
14894 (goto-char pos)
14895 (setq cnt (1+ cnt))
14896 (org-toggle-tag tag (if off 'off 'on))
14897 (setq newhead (org-get-heading)))))
14898 (and agendap (org-agenda-change-all-lines newhead m))))
14899 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14901 (defun org-tags-completion-function (string predicate &optional flag)
14902 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14903 (confirm (lambda (x) (stringp (car x)))))
14904 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14905 (setq s1 (match-string 1 string)
14906 s2 (match-string 2 string))
14907 (setq s1 "" s2 string))
14908 (cond
14909 ((eq flag nil)
14910 ;; try completion
14911 (setq rtn (try-completion s2 ctable confirm))
14912 (if (stringp rtn)
14913 (setq rtn
14914 (concat s1 s2 (substring rtn (length s2))
14915 (if (and org-add-colon-after-tag-completion
14916 (assoc rtn ctable))
14917 ":" ""))))
14918 rtn)
14919 ((eq flag t)
14920 ;; all-completions
14921 (all-completions s2 ctable confirm))
14922 ((eq flag 'lambda)
14923 ;; exact match?
14924 (assoc s2 ctable)))))
14926 (defun org-fast-tag-insert (kwd tags face &optional end)
14927 "Insert KDW, and the TAGS, the latter with face FACE.
14928 Also insert END."
14929 (insert (format "%-12s" (concat kwd ":"))
14930 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14931 (or end "")))
14933 (defun org-fast-tag-show-exit (flag)
14934 (save-excursion
14935 (org-goto-line 3)
14936 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14937 (replace-match ""))
14938 (when flag
14939 (end-of-line 1)
14940 (org-move-to-column (- (window-width) 19) t)
14941 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14943 (defun org-set-current-tags-overlay (current prefix)
14944 "Add an overlay to CURRENT tag with PREFIX."
14945 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14946 (if (featurep 'xemacs)
14947 (org-overlay-display org-tags-overlay (concat prefix s)
14948 'secondary-selection)
14949 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14950 (org-overlay-display org-tags-overlay (concat prefix s)))))
14952 (defvar org-last-tag-selection-key nil)
14953 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14954 "Fast tag selection with single keys.
14955 CURRENT is the current list of tags in the headline, INHERITED is the
14956 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14957 possibly with grouping information. TODO-TABLE is a similar table with
14958 TODO keywords, should these have keys assigned to them.
14959 If the keys are nil, a-z are automatically assigned.
14960 Returns the new tags string, or nil to not change the current settings."
14961 (let* ((fulltable (append table todo-table))
14962 (maxlen (apply 'max (mapcar
14963 (lambda (x)
14964 (if (stringp (car x)) (string-width (car x)) 0))
14965 fulltable)))
14966 (buf (current-buffer))
14967 (expert (eq org-fast-tag-selection-single-key 'expert))
14968 (buffer-tags nil)
14969 (fwidth (+ maxlen 3 1 3))
14970 (ncol (/ (- (window-width) 4) fwidth))
14971 (i-face 'org-done)
14972 (c-face 'org-todo)
14973 tg cnt e c char c1 c2 ntable tbl rtn
14974 ov-start ov-end ov-prefix
14975 (exit-after-next org-fast-tag-selection-single-key)
14976 (done-keywords org-done-keywords)
14977 groups ingroup)
14978 (save-excursion
14979 (beginning-of-line 1)
14980 (if (looking-at
14981 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14982 (setq ov-start (match-beginning 1)
14983 ov-end (match-end 1)
14984 ov-prefix "")
14985 (setq ov-start (1- (point-at-eol))
14986 ov-end (1+ ov-start))
14987 (skip-chars-forward "^\n\r")
14988 (setq ov-prefix
14989 (concat
14990 (buffer-substring (1- (point)) (point))
14991 (if (> (current-column) org-tags-column)
14993 (make-string (- org-tags-column (current-column)) ?\ ))))))
14994 (move-overlay org-tags-overlay ov-start ov-end)
14995 (save-window-excursion
14996 (if expert
14997 (set-buffer (get-buffer-create " *Org tags*"))
14998 (delete-other-windows)
14999 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15000 (org-switch-to-buffer-other-window " *Org tags*"))
15001 (erase-buffer)
15002 (org-set-local 'org-done-keywords done-keywords)
15003 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15004 (org-fast-tag-insert "Current" current c-face "\n\n")
15005 (org-fast-tag-show-exit exit-after-next)
15006 (org-set-current-tags-overlay current ov-prefix)
15007 (setq tbl fulltable char ?a cnt 0)
15008 (while (setq e (pop tbl))
15009 (cond
15010 ((equal (car e) :startgroup)
15011 (push '() groups) (setq ingroup t)
15012 (when (not (= cnt 0))
15013 (setq cnt 0)
15014 (insert "\n"))
15015 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15016 ((equal (car e) :endgroup)
15017 (setq ingroup nil cnt 0)
15018 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15019 ((equal e '(:newline))
15020 (when (not (= cnt 0))
15021 (setq cnt 0)
15022 (insert "\n")
15023 (setq e (car tbl))
15024 (while (equal (car tbl) '(:newline))
15025 (insert "\n")
15026 (setq tbl (cdr tbl)))))
15027 ((equal e '(:grouptags)) nil)
15029 (setq tg (copy-sequence (car e)) c2 nil)
15030 (if (cdr e)
15031 (setq c (cdr e))
15032 ;; automatically assign a character.
15033 (setq c1 (string-to-char
15034 (downcase (substring
15035 tg (if (= (string-to-char tg) ?@) 1 0)))))
15036 (if (or (rassoc c1 ntable) (rassoc c1 table))
15037 (while (or (rassoc char ntable) (rassoc char table))
15038 (setq char (1+ char)))
15039 (setq c2 c1))
15040 (setq c (or c2 char)))
15041 (if ingroup (push tg (car groups)))
15042 (setq tg (org-add-props tg nil 'face
15043 (cond
15044 ((not (assoc tg table))
15045 (org-get-todo-face tg))
15046 ((member tg current) c-face)
15047 ((member tg inherited) i-face))))
15048 (if (equal (caar tbl) :grouptags)
15049 (org-add-props tg nil 'face 'org-tag-group))
15050 (if (and (= cnt 0) (not ingroup)) (insert " "))
15051 (insert "[" c "] " tg (make-string
15052 (- fwidth 4 (length tg)) ?\ ))
15053 (push (cons tg c) ntable)
15054 (when (= (setq cnt (1+ cnt)) ncol)
15055 (insert "\n")
15056 (if ingroup (insert " "))
15057 (setq cnt 0)))))
15058 (setq ntable (nreverse ntable))
15059 (insert "\n")
15060 (goto-char (point-min))
15061 (if (not expert) (org-fit-window-to-buffer))
15062 (setq rtn
15063 (catch 'exit
15064 (while t
15065 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15066 (if (not groups) "no " "")
15067 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15068 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15069 (setq org-last-tag-selection-key c)
15070 (cond
15071 ((= c ?\r) (throw 'exit t))
15072 ((= c ?!)
15073 (setq groups (not groups))
15074 (goto-char (point-min))
15075 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15076 ((= c ?\C-c)
15077 (if (not expert)
15078 (org-fast-tag-show-exit
15079 (setq exit-after-next (not exit-after-next)))
15080 (setq expert nil)
15081 (delete-other-windows)
15082 (set-window-buffer (split-window-vertically) " *Org tags*")
15083 (org-switch-to-buffer-other-window " *Org tags*")
15084 (org-fit-window-to-buffer)))
15085 ((or (= c ?\C-g)
15086 (and (= c ?q) (not (rassoc c ntable))))
15087 (org-detach-overlay org-tags-overlay)
15088 (setq quit-flag t))
15089 ((= c ?\ )
15090 (setq current nil)
15091 (if exit-after-next (setq exit-after-next 'now)))
15092 ((= c ?\t)
15093 (condition-case nil
15094 (setq tg (org-icompleting-read
15095 "Tag: "
15096 (or buffer-tags
15097 (with-current-buffer buf
15098 (org-get-buffer-tags)))))
15099 (quit (setq tg "")))
15100 (when (string-match "\\S-" tg)
15101 (add-to-list 'buffer-tags (list tg))
15102 (if (member tg current)
15103 (setq current (delete tg current))
15104 (push tg current)))
15105 (if exit-after-next (setq exit-after-next 'now)))
15106 ((setq e (rassoc c todo-table) tg (car e))
15107 (with-current-buffer buf
15108 (save-excursion (org-todo tg)))
15109 (if exit-after-next (setq exit-after-next 'now)))
15110 ((setq e (rassoc c ntable) tg (car e))
15111 (if (member tg current)
15112 (setq current (delete tg current))
15113 (loop for g in groups do
15114 (if (member tg g)
15115 (mapc (lambda (x)
15116 (setq current (delete x current)))
15117 g)))
15118 (push tg current))
15119 (if exit-after-next (setq exit-after-next 'now))))
15121 ;; Create a sorted list
15122 (setq current
15123 (sort current
15124 (lambda (a b)
15125 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15126 (if (eq exit-after-next 'now) (throw 'exit t))
15127 (goto-char (point-min))
15128 (beginning-of-line 2)
15129 (delete-region (point) (point-at-eol))
15130 (org-fast-tag-insert "Current" current c-face)
15131 (org-set-current-tags-overlay current ov-prefix)
15132 (while (re-search-forward
15133 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15134 (setq tg (match-string 1))
15135 (add-text-properties
15136 (match-beginning 1) (match-end 1)
15137 (list 'face
15138 (cond
15139 ((member tg current) c-face)
15140 ((member tg inherited) i-face)
15141 (t (get-text-property (match-beginning 1) 'face))))))
15142 (goto-char (point-min)))))
15143 (org-detach-overlay org-tags-overlay)
15144 (if rtn
15145 (mapconcat 'identity current ":")
15146 nil))))
15148 (defun org-get-tags-string ()
15149 "Get the TAGS string in the current headline."
15150 (unless (org-at-heading-p t)
15151 (user-error "Not on a heading"))
15152 (save-excursion
15153 (beginning-of-line 1)
15154 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15155 (org-match-string-no-properties 1)
15156 "")))
15158 (defun org-get-tags ()
15159 "Get the list of tags specified in the current headline."
15160 (org-split-string (org-get-tags-string) ":"))
15162 (defun org-get-buffer-tags ()
15163 "Get a table of all tags used in the buffer, for completion."
15164 (let (tags)
15165 (save-excursion
15166 (goto-char (point-min))
15167 (while (re-search-forward
15168 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15169 (when (equal (char-after (point-at-bol 0)) ?*)
15170 (mapc (lambda (x) (add-to-list 'tags x))
15171 (org-split-string (org-match-string-no-properties 1) ":")))))
15172 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15173 (mapcar 'list tags)))
15175 ;;;; The mapping API
15177 (defun org-map-entries (func &optional match scope &rest skip)
15178 "Call FUNC at each headline selected by MATCH in SCOPE.
15180 FUNC is a function or a lisp form. The function will be called without
15181 arguments, with the cursor positioned at the beginning of the headline.
15182 The return values of all calls to the function will be collected and
15183 returned as a list.
15185 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15186 does not need to preserve point. After evaluation, the cursor will be
15187 moved to the end of the line (presumably of the headline of the
15188 processed entry) and search continues from there. Under some
15189 circumstances, this may not produce the wanted results. For example,
15190 if you have removed (e.g. archived) the current (sub)tree it could
15191 mean that the next entry will be skipped entirely. In such cases, you
15192 can specify the position from where search should continue by making
15193 FUNC set the variable `org-map-continue-from' to the desired buffer
15194 position.
15196 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15197 Only headlines that are matched by this query will be considered during
15198 the iteration. When MATCH is nil or t, all headlines will be
15199 visited by the iteration.
15201 SCOPE determines the scope of this command. It can be any of:
15203 nil The current buffer, respecting the restriction if any
15204 tree The subtree started with the entry at point
15205 region The entries within the active region, if any
15206 region-start-level
15207 The entries within the active region, but only those at
15208 the same level than the first one.
15209 file The current buffer, without restriction
15210 file-with-archives
15211 The current buffer, and any archives associated with it
15212 agenda All agenda files
15213 agenda-with-archives
15214 All agenda files with any archive files associated with them
15215 \(file1 file2 ...)
15216 If this is a list, all files in the list will be scanned
15218 The remaining args are treated as settings for the skipping facilities of
15219 the scanner. The following items can be given here:
15221 archive skip trees with the archive tag
15222 comment skip trees with the COMMENT keyword
15223 function or Emacs Lisp form:
15224 will be used as value for `org-agenda-skip-function', so
15225 whenever the function returns a position, FUNC will not be
15226 called for that entry and search will continue from the
15227 position returned
15229 If your function needs to retrieve the tags including inherited tags
15230 at the *current* entry, you can use the value of the variable
15231 `org-scanner-tags' which will be much faster than getting the value
15232 with `org-get-tags-at'. If your function gets properties with
15233 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15234 to t around the call to `org-entry-properties' to get the same speedup.
15235 Note that if your function moves around to retrieve tags and properties at
15236 a *different* entry, you cannot use these techniques."
15237 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15238 (not (org-region-active-p)))
15239 (let* ((org-agenda-archives-mode nil) ; just to make sure
15240 (org-agenda-skip-archived-trees (memq 'archive skip))
15241 (org-agenda-skip-comment-trees (memq 'comment skip))
15242 (org-agenda-skip-function
15243 (car (org-delete-all '(comment archive) skip)))
15244 (org-tags-match-list-sublevels t)
15245 (start-level (eq scope 'region-start-level))
15246 matcher file res
15247 org-todo-keywords-for-agenda
15248 org-done-keywords-for-agenda
15249 org-todo-keyword-alist-for-agenda
15250 org-tag-alist-for-agenda
15251 todo-only)
15253 (cond
15254 ((eq match t) (setq matcher t))
15255 ((eq match nil) (setq matcher t))
15256 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15258 (save-excursion
15259 (save-restriction
15260 (cond ((eq scope 'tree)
15261 (org-back-to-heading t)
15262 (org-narrow-to-subtree)
15263 (setq scope nil))
15264 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15265 (org-region-active-p))
15266 ;; If needed, set start-level to a string like "2"
15267 (when start-level
15268 (save-excursion
15269 (goto-char (region-beginning))
15270 (unless (org-at-heading-p) (outline-next-heading))
15271 (setq start-level (org-current-level))))
15272 (narrow-to-region (region-beginning)
15273 (save-excursion
15274 (goto-char (region-end))
15275 (unless (and (bolp) (org-at-heading-p))
15276 (outline-next-heading))
15277 (point)))
15278 (setq scope nil)))
15280 (if (not scope)
15281 (progn
15282 (org-agenda-prepare-buffers
15283 (list (buffer-file-name (current-buffer))))
15284 (setq res (org-scan-tags func matcher todo-only start-level)))
15285 ;; Get the right scope
15286 (cond
15287 ((and scope (listp scope) (symbolp (car scope)))
15288 (setq scope (eval scope)))
15289 ((eq scope 'agenda)
15290 (setq scope (org-agenda-files t)))
15291 ((eq scope 'agenda-with-archives)
15292 (setq scope (org-agenda-files t))
15293 (setq scope (org-add-archive-files scope)))
15294 ((eq scope 'file)
15295 (setq scope (list (buffer-file-name))))
15296 ((eq scope 'file-with-archives)
15297 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15298 (org-agenda-prepare-buffers scope)
15299 (while (setq file (pop scope))
15300 (with-current-buffer (org-find-base-buffer-visiting file)
15301 (save-excursion
15302 (save-restriction
15303 (widen)
15304 (goto-char (point-min))
15305 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15306 res)))
15308 ;;; Properties API
15310 (defconst org-special-properties
15311 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOSED" "PRIORITY"
15312 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15313 "The special properties valid in Org-mode.
15314 These are properties that are not defined in the property drawer,
15315 but in some other way.")
15317 (defconst org-default-properties
15318 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15319 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15320 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15321 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15322 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15323 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15324 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15325 "Some properties that are used by Org mode for various purposes.
15326 Being in this list makes sure that they are offered for completion.")
15328 (defun org--update-property-plist (key val props)
15329 "Associate KEY to VAL in alist PROPS.
15330 Modifications are made by side-effect. Return new alist."
15331 (let* ((appending (string= (substring key -1) "+"))
15332 (key (if appending (substring key 0 -1) key))
15333 (old (assoc-string key props t)))
15334 (if (not old) (cons (cons key val) props)
15335 (setcdr old (if appending (concat (cdr old) " " val) val))
15336 props)))
15338 (defun org-get-property-block (&optional beg force)
15339 "Return the (beg . end) range of the body of the property drawer.
15340 BEG is the beginning of the current subtree, or of the part
15341 before the first headline. If it is not given, it will be found.
15342 If the drawer does not exist, create it if FORCE is non-nil, or
15343 return nil."
15344 (org-with-wide-buffer
15345 (when beg (goto-char beg))
15346 (unless (org-before-first-heading-p)
15347 (let ((beg (cond (beg)
15348 ((or (not (featurep 'org-inlinetask))
15349 (org-inlinetask-in-task-p))
15350 (org-back-to-heading t))
15351 (t (org-with-limited-levels (org-back-to-heading t))))))
15352 (forward-line)
15353 (when (org-looking-at-p org-planning-line-re) (forward-line))
15354 (cond ((looking-at org-property-drawer-re)
15355 (forward-line)
15356 (cons (point) (progn (goto-char (match-end 0))
15357 (line-beginning-position))))
15358 (force
15359 (org-insert-property-drawer)
15360 (let ((pos (save-excursion (search-forward ":END:")
15361 (line-beginning-position))))
15362 (cons pos pos))))))))
15364 (defun org-at-property-p ()
15365 "Non-nil when point is inside a property drawer.
15366 See `org-property-re' for match data, if applicable."
15367 (save-excursion
15368 (beginning-of-line)
15369 (and (looking-at org-property-re)
15370 (let ((property-drawer (save-match-data (org-get-property-block))))
15371 (and property-drawer (< (point) (cdr property-drawer)))))))
15373 (defun org-property-action ()
15374 "Do an action on properties."
15375 (interactive)
15376 (unless (org-at-property-p) (user-error "Not at a property"))
15377 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15378 (let ((c (read-char-exclusive)))
15379 (case c
15380 (?s (call-interactively #'org-set-property))
15381 (?d (call-interactively #'org-delete-property))
15382 (?D (call-interactively #'org-delete-property-globally))
15383 (?c (call-interactively #'org-compute-property-at-point))
15384 (otherwise (user-error "No such property action %c" c)))))
15386 (defun org-inc-effort ()
15387 "Increment the value of the effort property in the current entry."
15388 (interactive)
15389 (org-set-effort nil t))
15391 (defvar org-clock-effort) ; Defined in org-clock.el.
15392 (defvar org-clock-current-task) ; Defined in org-clock.el.
15393 (defun org-set-effort (&optional value increment)
15394 "Set the effort property of the current entry.
15395 With numerical prefix arg, use the nth allowed value, 0 stands for the
15396 10th allowed value.
15398 When INCREMENT is non-nil, set the property to the next allowed value."
15399 (interactive "P")
15400 (if (equal value 0) (setq value 10))
15401 (let* ((completion-ignore-case t)
15402 (prop org-effort-property)
15403 (cur (org-entry-get nil prop))
15404 (allowed (org-property-get-allowed-values nil prop 'table))
15405 (existing (mapcar 'list (org-property-values prop)))
15406 (heading (nth 4 (org-heading-components)))
15408 (val (cond
15409 ((stringp value) value)
15410 ((and allowed (integerp value))
15411 (or (car (nth (1- value) allowed))
15412 (car (org-last allowed))))
15413 ((and allowed increment)
15414 (or (caadr (member (list cur) allowed))
15415 (user-error "Allowed effort values are not set")))
15416 (allowed
15417 (message "Select 1-9,0, [RET%s]: %s"
15418 (if cur (concat "=" cur) "")
15419 (mapconcat 'car allowed " "))
15420 (setq rpl (read-char-exclusive))
15421 (if (equal rpl ?\r)
15423 (setq rpl (- rpl ?0))
15424 (if (equal rpl 0) (setq rpl 10))
15425 (if (and (> rpl 0) (<= rpl (length allowed)))
15426 (car (nth (1- rpl) allowed))
15427 (org-completing-read "Effort: " allowed nil))))
15429 (let (org-completion-use-ido org-completion-use-iswitchb)
15430 (org-completing-read
15431 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15432 (concat "[" cur "]") "")
15433 ": ")
15434 existing nil nil "" nil cur))))))
15435 (unless (equal (org-entry-get nil prop) val)
15436 (org-entry-put nil prop val))
15437 (org-refresh-property
15438 '((effort . identity)
15439 (effort-minutes . org-duration-string-to-minutes))
15440 val)
15441 (when (string= heading org-clock-current-task)
15442 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15443 (org-clock-update-mode-line))
15444 (message "%s is now %s" prop val)))
15446 (defun org-entry-properties (&optional pom which)
15447 "Get all properties of the current entry.
15449 When POM is a buffer position, get all properties from the entry
15450 there instead.
15452 This includes the TODO keyword, the tags, time strings for
15453 deadline, scheduled, and clocking, and any additional properties
15454 defined in the entry.
15456 If WHICH is nil or `all', get all properties. If WHICH is
15457 `special' or `standard', only get that subclass. If WHICH is
15458 a string, only get that property.
15460 Return value is an alist. Keys are properties, as upcased
15461 strings."
15462 (org-with-point-at pom
15463 (when (and (derived-mode-p 'org-mode)
15464 (ignore-errors (org-back-to-heading t)))
15465 (catch 'exit
15466 (let* ((beg (point))
15467 (specific (and (stringp which) (upcase which)))
15468 (which (cond ((not specific) which)
15469 ((member specific org-special-properties) 'special)
15470 (t 'standard)))
15471 props)
15472 ;; Get the special properties, like TODO and TAGS.
15473 (when (memq which '(nil all special))
15474 (when (or (not specific) (string= specific "CLOCKSUM"))
15475 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15476 (when clocksum
15477 (push (cons "CLOCKSUM"
15478 (org-columns-number-to-string
15479 (/ (float clocksum) 60.) 'add_times))
15480 props)))
15481 (when specific (throw 'exit props)))
15482 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15483 (let ((clocksumt (get-text-property (point)
15484 :org-clock-minutes-today)))
15485 (when clocksumt
15486 (push (cons "CLOCKSUM_T"
15487 (org-columns-number-to-string
15488 (/ (float clocksumt) 60.) 'add_times))
15489 props)))
15490 (when specific (throw 'exit props)))
15491 (when (or (not specific) (string= specific "TODO"))
15492 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15493 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15494 (when specific (throw 'exit props)))
15495 (when (or (not specific) (string= specific "PRIORITY"))
15496 (when (looking-at org-priority-regexp)
15497 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15498 (when specific (throw 'exit props)))
15499 (when (or (not specific) (string= specific "FILE"))
15500 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15501 props)
15502 (when specific (throw 'exit props)))
15503 (when (or (not specific) (string= specific "TAGS"))
15504 (let ((value (org-string-nw-p (org-get-tags-string))))
15505 (when value (push (cons "TAGS" value) props)))
15506 (when specific (throw 'exit props)))
15507 (when (or (not specific) (string= specific "ALLTAGS"))
15508 (let ((value (org-get-tags-at)))
15509 (when value
15510 (push (cons "ALLTAGS"
15511 (format ":%s:" (mapconcat #'identity value ":")))
15512 props)))
15513 (when specific (throw 'exit props)))
15514 (when (or (not specific) (string= specific "BLOCKED"))
15515 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15516 (when specific (throw 'exit props)))
15517 (when (or (not specific)
15518 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15519 (forward-line)
15520 (when (org-looking-at-p org-planning-line-re)
15521 (end-of-line)
15522 (let ((bol (line-beginning-position)))
15523 ;; Backward compatibility: time keywords used to be
15524 ;; configurable (before 8.3). Make sure we get the
15525 ;; correct keyword.
15526 (dolist (k (if (not specific)
15527 (list org-closed-string
15528 org-deadline-string
15529 org-scheduled-string)
15530 (list (cond ((string= specific "CLOSED")
15531 org-closed-string)
15532 ((string= specific "DEADLINE")
15533 org-deadline-string)
15534 (t org-scheduled-string)))))
15535 (save-excursion
15536 (when (search-backward k bol t)
15537 (goto-char (match-end 0))
15538 (skip-chars-forward " \t")
15539 (and (looking-at org-ts-regexp-both)
15540 (push (cons specific (match-string 0)) props)))))))
15541 (when specific (throw 'exit props)))
15542 (when (or (not specific)
15543 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15544 (let ((find-ts
15545 (lambda (end ts)
15546 (let ((regexp (if (or (string= specific "TIMESTAMP")
15547 (assoc "TIMESTAMP_IA" ts))
15548 org-ts-regexp
15549 org-ts-regexp-both)))
15550 (catch 'next
15551 (while (re-search-forward regexp end t)
15552 (backward-char)
15553 (let ((object (org-element-context)))
15554 ;; Accept to match timestamps in node
15555 ;; properties, too.
15556 (when (memq (org-element-type object)
15557 '(node-property timestamp))
15558 (let ((type
15559 (org-element-property :type object)))
15560 (cond
15561 ((and (memq type '(active active-range))
15562 (not (equal specific "TIMESTAMP_IA")))
15563 (unless (assoc "TIMESTAMP" ts)
15564 (push (cons "TIMESTAMP"
15565 (org-element-property
15566 :raw-value object))
15568 (when specific (throw 'exit ts))))
15569 ((and (memq type '(inactive inactive-range))
15570 (not (string= specific "TIMESTAMP")))
15571 (unless (assoc "TIMESTAMP_IA" ts)
15572 (push (cons "TIMESTAMP_IA"
15573 (org-element-property
15574 :raw-value object))
15576 (when specific (throw 'exit ts))))))
15577 ;; Both timestamp types are found,
15578 ;; move to next part.
15579 (when (= (length ts) 2) (throw 'next ts)))))
15580 ts)))))
15581 (goto-char beg)
15582 ;; First look for timestamps within headline.
15583 (let ((ts (funcall find-ts (line-end-position) nil)))
15584 (if (= (length ts) 2) (setq props (nconc ts props))
15585 (forward-line)
15586 ;; Then find timestamps in the section, skipping
15587 ;; planning line.
15588 (when (org-looking-at-p org-planning-line-re)
15589 (forward-line))
15590 (let ((end (save-excursion (outline-next-heading))))
15591 (setq props (nconc (funcall find-ts end ts) props))))))))
15592 ;; Get the standard properties, like :PROP:.
15593 (when (memq which '(nil all standard))
15594 ;; If we are looking after a specific property, delegate
15595 ;; to `org-entry-get', which is faster. However, make an
15596 ;; exception for "CATEGORY", since it can be also set
15597 ;; through keywords (i.e. #+CATEGORY).
15598 (if (and specific (not (equal specific "CATEGORY")))
15599 (let ((value (org-entry-get beg specific nil t)))
15600 (throw 'exit (and value (list (cons specific value)))))
15601 (let ((range (org-get-property-block beg)))
15602 (when range
15603 (let ((end (cdr range)) seen-base)
15604 (goto-char (car range))
15605 ;; Unlike to `org--update-property-plist', we
15606 ;; handle the case where base values is found
15607 ;; after its extension. We also forbid standard
15608 ;; properties to be named as special properties.
15609 (while (re-search-forward org-property-re end t)
15610 (let* ((key (upcase (org-match-string-no-properties 2)))
15611 (extendp (org-string-match-p "\\+\\'" key))
15612 (key-base (if extendp (substring key 0 -1) key))
15613 (value (org-match-string-no-properties 3)))
15614 (cond
15615 ((member-ignore-case key-base org-special-properties))
15616 (extendp
15617 (setq props
15618 (org--update-property-plist key value props)))
15619 ((member key seen-base))
15620 (t (push key seen-base)
15621 (let ((p (assoc-string key props t)))
15622 (if p (setcdr p (concat value " " (cdr p)))
15623 (push (cons key value) props))))))))))))
15624 (unless (assoc "CATEGORY" props)
15625 (push (cons "CATEGORY" (org-get-category)) props)
15626 (when (string= specific "CATEGORY") (throw 'exit props)))
15627 ;; Return value.
15628 (append (get-text-property beg 'org-summaries) props))))))
15630 (defun org-entry-get (pom property &optional inherit literal-nil)
15631 "Get value of PROPERTY for entry or content at point-or-marker POM.
15633 If INHERIT is non-nil and the entry does not have the property,
15634 then also check higher levels of the hierarchy. If INHERIT is
15635 the symbol `selective', use inheritance only if the setting in
15636 `org-use-property-inheritance' selects PROPERTY for inheritance.
15638 If the property is present but empty, the return value is the
15639 empty string. If the property is not present at all, nil is
15640 returned. In any other case, return the value as a string.
15641 Search is case-insensitive.
15643 If LITERAL-NIL is set, return the string value \"nil\" as
15644 a string, do not interpret it as the list atom nil. This is used
15645 for inheritance when a \"nil\" value can supersede a non-nil
15646 value higher up the hierarchy."
15647 (org-with-point-at pom
15648 (cond
15649 ((and inherit
15650 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15651 (org-entry-get-with-inheritance property literal-nil))
15652 ((member-ignore-case property org-special-properties)
15653 ;; We need a special property. Use `org-entry-properties' to
15654 ;; retrieve it, but specify the wanted property.
15655 (cdr (assoc-string property (org-entry-properties nil property))))
15657 (let ((range (org-get-property-block)))
15658 (when range
15659 (let* ((case-fold-search t)
15660 (end (cdr range))
15661 (props
15662 (let ((global
15663 (or (assoc-string property org-file-properties t)
15664 (assoc-string property org-global-properties t)
15665 (assoc-string
15666 property org-global-properties-fixed t))))
15667 ;; Make sure to not re-use GLOBAL as
15668 ;; `org--update-property-plist' would alter it by
15669 ;; side-effect.
15670 (and global (list (cons property (cdr global))))))
15671 (find-value
15672 (lambda (key)
15673 (when (re-search-forward (org-re-property key nil t) end t)
15674 (setq props
15675 (org--update-property-plist
15676 key (org-match-string-no-properties 3) props))))))
15677 (goto-char (car range))
15678 ;; Find base value.
15679 (save-excursion (funcall find-value property))
15680 ;; Find additional values.
15681 (let ((property+ (concat property "+")))
15682 (while (funcall find-value property+)))
15683 ;; Return final value.
15684 (let ((val (cdr (assoc-string property props t))))
15685 (if literal-nil val (org-not-nil val))))))))))
15687 (defun org-property-or-variable-value (var &optional inherit)
15688 "Check if there is a property fixing the value of VAR.
15689 If yes, return this value. If not, return the current value of the variable."
15690 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15691 (if (and prop (stringp prop) (string-match "\\S-" prop))
15692 (read prop)
15693 (symbol-value var))))
15695 (defun org-entry-delete (pom property)
15696 "Delete the property PROPERTY from entry at point-or-marker POM."
15697 (unless (member property org-special-properties)
15698 (org-with-point-at pom
15699 (let ((range (org-get-property-block)))
15700 (when range
15701 (let ((begin (car range))
15702 (end (copy-marker (cdr range))))
15703 (goto-char begin)
15704 (when (re-search-forward (org-re-property property nil t) end t)
15705 (delete-region (match-beginning 0) (line-beginning-position 2))
15706 ;; If drawer is empty, remove it altogether.
15707 (when (= begin end)
15708 (delete-region (line-beginning-position 0)
15709 (line-beginning-position 2)))
15710 (set-marker end nil))))))))
15712 ;; Multi-values properties are properties that contain multiple values
15713 ;; These values are assumed to be single words, separated by whitespace.
15714 (defun org-entry-add-to-multivalued-property (pom property value)
15715 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15716 (let* ((old (org-entry-get pom property))
15717 (values (and old (org-split-string old "[ \t]"))))
15718 (setq value (org-entry-protect-space value))
15719 (unless (member value values)
15720 (setq values (append values (list value)))
15721 (org-entry-put pom property
15722 (mapconcat 'identity values " ")))))
15724 (defun org-entry-remove-from-multivalued-property (pom property value)
15725 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15726 (let* ((old (org-entry-get pom property))
15727 (values (and old (org-split-string old "[ \t]"))))
15728 (setq value (org-entry-protect-space value))
15729 (when (member value values)
15730 (setq values (delete value values))
15731 (org-entry-put pom property
15732 (mapconcat 'identity values " ")))))
15734 (defun org-entry-member-in-multivalued-property (pom property value)
15735 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15736 (let* ((old (org-entry-get pom property))
15737 (values (and old (org-split-string old "[ \t]"))))
15738 (setq value (org-entry-protect-space value))
15739 (member value values)))
15741 (defun org-entry-get-multivalued-property (pom property)
15742 "Return a list of values in a multivalued property."
15743 (let* ((value (org-entry-get pom property))
15744 (values (and value (org-split-string value "[ \t]"))))
15745 (mapcar 'org-entry-restore-space values)))
15747 (defun org-entry-put-multivalued-property (pom property &rest values)
15748 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15749 VALUES should be a list of strings. Spaces will be protected."
15750 (org-entry-put pom property
15751 (mapconcat 'org-entry-protect-space values " "))
15752 (let* ((value (org-entry-get pom property))
15753 (values (and value (org-split-string value "[ \t]"))))
15754 (mapcar 'org-entry-restore-space values)))
15756 (defun org-entry-protect-space (s)
15757 "Protect spaces and newline in string S."
15758 (while (string-match " " s)
15759 (setq s (replace-match "%20" t t s)))
15760 (while (string-match "\n" s)
15761 (setq s (replace-match "%0A" t t s)))
15764 (defun org-entry-restore-space (s)
15765 "Restore spaces and newline in string S."
15766 (while (string-match "%20" s)
15767 (setq s (replace-match " " t t s)))
15768 (while (string-match "%0A" s)
15769 (setq s (replace-match "\n" t t s)))
15772 (defvar org-entry-property-inherited-from (make-marker)
15773 "Marker pointing to the entry from where a property was inherited.
15774 Each call to `org-entry-get-with-inheritance' will set this marker to the
15775 location of the entry where the inheritance search matched. If there was
15776 no match, the marker will point nowhere.
15777 Note that also `org-entry-get' calls this function, if the INHERIT flag
15778 is set.")
15780 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15781 "Get PROPERTY of entry or content at point, search higher levels if needed.
15782 The search will stop at the first ancestor which has the property defined.
15783 If the value found is \"nil\", return nil to show that the property
15784 should be considered as undefined (this is the meaning of nil here).
15785 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15786 (move-marker org-entry-property-inherited-from nil)
15787 (let (value)
15788 (org-with-wide-buffer
15789 (catch 'exit
15790 (while t
15791 (when (setq value (org-entry-get nil property nil literal-nil))
15792 (org-back-to-heading t)
15793 (move-marker org-entry-property-inherited-from (point))
15794 (throw 'exit nil))
15795 (or (org-up-heading-safe) (throw 'exit nil)))))
15796 (unless value
15797 (setq value
15798 (cdr (or (assoc-string property org-file-properties t)
15799 (assoc-string property org-global-properties t)
15800 (assoc-string property org-global-properties-fixed t)))))
15801 (if literal-nil value (org-not-nil value))))
15803 (defvar org-property-changed-functions nil
15804 "Hook called when the value of a property has changed.
15805 Each hook function should accept two arguments, the name of the property
15806 and the new value.")
15808 (defun org-entry-put (pom property value)
15809 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15811 If the value is `nil', it is converted to the empty string. If
15812 it is not a string, an error is raised.
15814 PROPERTY can be any regular property (see
15815 `org-special-properties'). It can also be \"TODO\",
15816 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15818 For the last two properties, VALUE may have any of the special
15819 values \"earlier\" and \"later\". The function then increases or
15820 decreases scheduled or deadline date by one day."
15821 (cond ((null value) (setq value ""))
15822 ((not (stringp value)) (error "Properties values should be strings")))
15823 (org-with-point-at pom
15824 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15825 (org-back-to-heading t)
15826 (org-with-limited-levels (org-back-to-heading t)))
15827 (let ((beg (point)))
15828 (cond
15829 ((equal property "TODO")
15830 (cond ((not (org-string-nw-p value)) (setq value 'none))
15831 ((not (member value org-todo-keywords-1))
15832 (user-error "\"%s\" is not a valid TODO state" value)))
15833 (org-todo value)
15834 (org-set-tags nil 'align))
15835 ((equal property "PRIORITY")
15836 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15837 (org-set-tags nil 'align))
15838 ((equal property "SCHEDULED")
15839 (forward-line)
15840 (if (and (org-looking-at-p org-planning-line-re)
15841 (re-search-forward
15842 org-scheduled-time-regexp (line-end-position) t))
15843 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15844 ((string= value "later") (org-timestamp-change 1 'day))
15845 ((string= value "") (org-schedule '(4)))
15846 (t (org-schedule nil value)))
15847 (if (member value '("earlier" "later" ""))
15848 (call-interactively #'org-schedule)
15849 (org-schedule nil value))))
15850 ((equal property "DEADLINE")
15851 (forward-line)
15852 (if (and (org-looking-at-p org-planning-line-re)
15853 (re-search-forward
15854 org-deadline-time-regexp (line-end-position) t))
15855 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15856 ((string= value "later") (org-timestamp-change 1 'day))
15857 ((string= value "") (org-deadline '(4)))
15858 (t (org-deadline nil value)))
15859 (if (member value '("earlier" "later" ""))
15860 (call-interactively #'org-deadline)
15861 (org-deadline nil value))))
15862 ((member property org-special-properties)
15863 (error "The %s property cannot be set with `org-entry-put'" property))
15865 (let* ((range (org-get-property-block beg 'force))
15866 (end (cdr range))
15867 (case-fold-search t))
15868 (goto-char (car range))
15869 (if (re-search-forward (org-re-property property nil t) end t)
15870 (progn (delete-region (match-beginning 0) (match-end 0))
15871 (goto-char (match-beginning 0)))
15872 (goto-char end)
15873 (insert "\n")
15874 (backward-char))
15875 (insert ":" property ":")
15876 (when value (insert " " value))
15877 (org-indent-line)))))
15878 (run-hook-with-args 'org-property-changed-functions property value)))
15880 (defun org-buffer-property-keys (&optional specials defaults columns)
15881 "Get all property keys in the current buffer.
15883 When SPECIALS is non-nil, also list the special properties that
15884 reflect things like tags and TODO state.
15886 When DEFAULTS is non-nil, also include properties that has
15887 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15888 DESCRIPTION, LOCATION, and LOGGING and others.
15890 When COLUMNS in non-nil, also include property names given in
15891 COLUMN formats in the current buffer."
15892 (let ((case-fold-search t)
15893 (props (append
15894 (and specials org-special-properties)
15895 (and defaults (cons org-effort-property org-default-properties))
15896 nil)))
15897 (org-with-wide-buffer
15898 (goto-char (point-min))
15899 (while (re-search-forward org-property-start-re nil t)
15900 (let ((range (org-get-property-block)))
15901 (catch 'skip
15902 (unless range
15903 (when (and (not (org-before-first-heading-p))
15904 (y-or-n-p (format "Malformed drawer at %d, repair?"
15905 (line-beginning-position))))
15906 (org-get-property-block nil t))
15907 (throw 'skip nil))
15908 (goto-char (car range))
15909 (let ((begin (car range))
15910 (end (cdr range)))
15911 ;; Make sure that found property block is not located
15912 ;; before current point, as it would generate an infloop.
15913 ;; It can happen, for example, in the following
15914 ;; situation:
15916 ;; * Headline
15917 ;; :PROPERTIES:
15918 ;; ...
15919 ;; :END:
15920 ;; *************** Inlinetask
15921 ;; #+BEGIN_EXAMPLE
15922 ;; :PROPERTIES:
15923 ;; #+END_EXAMPLE
15925 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
15926 (while (< (point) end)
15927 (let ((p (progn (looking-at org-property-re)
15928 (org-match-string-no-properties 2))))
15929 ;; Only add true property name, not extension symbol.
15930 (add-to-list 'props
15931 (if (not (org-string-match-p "\\+\\'" p)) p
15932 (substring p 0 -1))))
15933 (forward-line))))
15934 (outline-next-heading)))
15935 (when columns
15936 (goto-char (point-min))
15937 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15938 (let ((element (org-element-at-point)))
15939 (when (memq (org-element-type element) '(keyword node-property))
15940 (let ((value (org-element-property :value element))
15941 (start 0))
15942 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
15943 (setq start (match-end 0))
15944 (let ((p (org-match-string-no-properties 1 value)))
15945 (unless (member-ignore-case
15946 p (cons "ITEM" org-special-properties))
15947 (add-to-list 'props p))))))))))
15948 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
15950 (defun org-property-values (key)
15951 "List all non-nil values of property KEY in current buffer."
15952 (org-with-wide-buffer
15953 (goto-char (point-min))
15954 (let ((case-fold-search t)
15955 (re (org-re-property key))
15956 values)
15957 (while (re-search-forward re nil t)
15958 (add-to-list 'values (org-entry-get (point) key)))
15959 values)))
15961 (defun org-insert-property-drawer ()
15962 "Insert a property drawer into the current entry."
15963 (org-with-wide-buffer
15964 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15965 (org-back-to-heading t)
15966 (org-with-limited-levels (org-back-to-heading t)))
15967 (forward-line)
15968 (when (org-looking-at-p org-planning-line-re) (forward-line))
15969 (unless (org-looking-at-p org-property-drawer-re)
15970 (let ((inhibit-read-only t))
15971 (unless (bolp) (insert "\n"))
15972 (let ((begin (point)))
15973 (insert ":PROPERTIES:\n:END:\n")
15974 (org-indent-region begin (point)))))))
15976 (defun org-insert-drawer (&optional arg drawer)
15977 "Insert a drawer at point.
15979 When optional argument ARG is non-nil, insert a property drawer.
15981 Optional argument DRAWER, when non-nil, is a string representing
15982 drawer's name. Otherwise, the user is prompted for a name.
15984 If a region is active, insert the drawer around that region
15985 instead.
15987 Point is left between drawer's boundaries."
15988 (interactive "P")
15989 (let* ((drawer (if arg "PROPERTIES"
15990 (or drawer (read-from-minibuffer "Drawer: ")))))
15991 (cond
15992 ;; With C-u, fall back on `org-insert-property-drawer'
15993 (arg (org-insert-property-drawer))
15994 ;; Check validity of suggested drawer's name.
15995 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15996 (user-error "Invalid drawer name"))
15997 ;; With an active region, insert a drawer at point.
15998 ((not (org-region-active-p))
15999 (progn
16000 (unless (bolp) (insert "\n"))
16001 (insert (format ":%s:\n\n:END:\n" drawer))
16002 (forward-line -2)))
16003 ;; Otherwise, insert the drawer at point
16005 (let ((rbeg (region-beginning))
16006 (rend (copy-marker (region-end))))
16007 (unwind-protect
16008 (progn
16009 (goto-char rbeg)
16010 (beginning-of-line)
16011 (when (save-excursion
16012 (re-search-forward org-outline-regexp-bol rend t))
16013 (user-error "Drawers cannot contain headlines"))
16014 ;; Position point at the beginning of the first
16015 ;; non-blank line in region. Insert drawer's opening
16016 ;; there, then indent it.
16017 (org-skip-whitespace)
16018 (beginning-of-line)
16019 (insert ":" drawer ":\n")
16020 (forward-line -1)
16021 (indent-for-tab-command)
16022 ;; Move point to the beginning of the first blank line
16023 ;; after the last non-blank line in region. Insert
16024 ;; drawer's closing, then indent it.
16025 (goto-char rend)
16026 (skip-chars-backward " \r\t\n")
16027 (insert "\n:END:")
16028 (deactivate-mark t)
16029 (indent-for-tab-command)
16030 (unless (eolp) (insert "\n")))
16031 ;; Clear marker, whatever the outcome of insertion is.
16032 (set-marker rend nil)))))))
16034 (defvar org-property-set-functions-alist nil
16035 "Property set function alist.
16036 Each entry should have the following format:
16038 (PROPERTY . READ-FUNCTION)
16040 The read function will be called with the same argument as
16041 `org-completing-read'.")
16043 (defun org-set-property-function (property)
16044 "Get the function that should be used to set PROPERTY.
16045 This is computed according to `org-property-set-functions-alist'."
16046 (or (cdr (assoc property org-property-set-functions-alist))
16047 'org-completing-read))
16049 (defun org-read-property-value (property)
16050 "Read PROPERTY value from user."
16051 (let* ((completion-ignore-case t)
16052 (allowed (org-property-get-allowed-values nil property 'table))
16053 (cur (org-entry-get nil property))
16054 (prompt (concat property " value"
16055 (if (and cur (string-match "\\S-" cur))
16056 (concat " [" cur "]") "") ": "))
16057 (set-function (org-set-property-function property))
16058 (val (if allowed
16059 (funcall set-function prompt allowed nil
16060 (not (get-text-property 0 'org-unrestricted
16061 (caar allowed))))
16062 (let (org-completion-use-ido org-completion-use-iswitchb)
16063 (funcall set-function prompt
16064 (mapcar 'list (org-property-values property))
16065 nil nil "" nil cur)))))
16066 (org-trim val)))
16068 (defvar org-last-set-property nil)
16069 (defvar org-last-set-property-value nil)
16070 (defun org-read-property-name ()
16071 "Read a property name."
16072 (let* ((completion-ignore-case t)
16073 (keys (org-buffer-property-keys nil t t))
16074 (default-prop (or (save-excursion
16075 (save-match-data
16076 (beginning-of-line)
16077 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16078 (null (string= (match-string 1) "END"))
16079 (match-string 1))))
16080 org-last-set-property))
16081 (property (org-icompleting-read
16082 (concat "Property"
16083 (if default-prop (concat " [" default-prop "]") "")
16084 ": ")
16085 (mapcar 'list keys)
16086 nil nil nil nil
16087 default-prop)))
16088 (if (member property keys)
16089 property
16090 (or (cdr (assoc (downcase property)
16091 (mapcar (lambda (x) (cons (downcase x) x))
16092 keys)))
16093 property))))
16095 (defun org-set-property-and-value (use-last)
16096 "Allow to set [PROPERTY]: [value] direction from prompt.
16097 When use-default, don't even ask, just use the last
16098 \"[PROPERTY]: [value]\" string from the history."
16099 (interactive "P")
16100 (let* ((completion-ignore-case t)
16101 (pv (or (and use-last org-last-set-property-value)
16102 (org-completing-read
16103 "Enter a \"[Property]: [value]\" pair: "
16104 nil nil nil nil nil
16105 org-last-set-property-value)))
16106 prop val)
16107 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16108 (setq prop (match-string 1 pv)
16109 val (match-string 2 pv))
16110 (org-set-property prop val))))
16112 (defun org-set-property (property value)
16113 "In the current entry, set PROPERTY to VALUE.
16114 When called interactively, this will prompt for a property name, offering
16115 completion on existing and default properties. And then it will prompt
16116 for a value, offering completion either on allowed values (via an inherited
16117 xxx_ALL property) or on existing values in other instances of this property
16118 in the current file."
16119 (interactive (list nil nil))
16120 (let* ((property (or property (org-read-property-name)))
16121 (value (or value (org-read-property-value property)))
16122 (fn (cdr (assoc property org-properties-postprocess-alist))))
16123 (setq org-last-set-property property)
16124 (setq org-last-set-property-value (concat property ": " value))
16125 ;; Possibly postprocess the inserted value:
16126 (when fn (setq value (funcall fn value)))
16127 (unless (equal (org-entry-get nil property) value)
16128 (org-entry-put nil property value))))
16130 (defun org-delete-property (property)
16131 "In the current entry, delete PROPERTY."
16132 (interactive
16133 (let* ((completion-ignore-case t)
16134 (cat (org-entry-get (point) "CATEGORY"))
16135 (props0 (org-entry-properties nil 'standard))
16136 (props (if cat props0
16137 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16138 (prop (if (< 1 (length props))
16139 (org-icompleting-read "Property: " props nil t)
16140 (caar props))))
16141 (list prop)))
16142 (if (not property)
16143 (message "No property to delete in this entry")
16144 (org-entry-delete nil property)
16145 (message "Property \"%s\" deleted" property)))
16147 (defun org-delete-property-globally (property)
16148 "Remove PROPERTY globally, from all entries."
16149 (interactive
16150 (let* ((completion-ignore-case t)
16151 (prop (org-icompleting-read
16152 "Globally remove property: "
16153 (mapcar 'list (org-buffer-property-keys)))))
16154 (list prop)))
16155 (save-excursion
16156 (save-restriction
16157 (widen)
16158 (goto-char (point-min))
16159 (let ((cnt 0))
16160 (while (re-search-forward
16161 (org-re-property property)
16162 nil t)
16163 (setq cnt (1+ cnt))
16164 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16165 (message "Property \"%s\" removed from %d entries" property cnt)))))
16167 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16169 (defun org-compute-property-at-point ()
16170 "Compute the property at point.
16171 This looks for an enclosing column format, extracts the operator and
16172 then applies it to the property in the column format's scope."
16173 (interactive)
16174 (unless (org-at-property-p)
16175 (user-error "Not at a property"))
16176 (let ((prop (org-match-string-no-properties 2)))
16177 (org-columns-get-format-and-top-level)
16178 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16179 (user-error "No operator defined for property %s" prop))
16180 (org-columns-compute prop)))
16182 (defvar org-property-allowed-value-functions nil
16183 "Hook for functions supplying allowed values for a specific property.
16184 The functions must take a single argument, the name of the property, and
16185 return a flat list of allowed values. If \":ETC\" is one of
16186 the values, this means that these values are intended as defaults for
16187 completion, but that other values should be allowed too.
16188 The functions must return nil if they are not responsible for this
16189 property.")
16191 (defun org-property-get-allowed-values (pom property &optional table)
16192 "Get allowed values for the property PROPERTY.
16193 When TABLE is non-nil, return an alist that can directly be used for
16194 completion."
16195 (let (vals)
16196 (cond
16197 ((equal property "TODO")
16198 (setq vals (org-with-point-at pom
16199 (append org-todo-keywords-1 '("")))))
16200 ((equal property "PRIORITY")
16201 (let ((n org-lowest-priority))
16202 (while (>= n org-highest-priority)
16203 (push (char-to-string n) vals)
16204 (setq n (1- n)))))
16205 ((member property org-special-properties))
16206 ((setq vals (run-hook-with-args-until-success
16207 'org-property-allowed-value-functions property)))
16209 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16210 (when (and vals (string-match "\\S-" vals))
16211 (setq vals (car (read-from-string (concat "(" vals ")"))))
16212 (setq vals (mapcar (lambda (x)
16213 (cond ((stringp x) x)
16214 ((numberp x) (number-to-string x))
16215 ((symbolp x) (symbol-name x))
16216 (t "???")))
16217 vals)))))
16218 (when (member ":ETC" vals)
16219 (setq vals (remove ":ETC" vals))
16220 (org-add-props (car vals) '(org-unrestricted t)))
16221 (if table (mapcar 'list vals) vals)))
16223 (defun org-property-previous-allowed-value (&optional previous)
16224 "Switch to the next allowed value for this property."
16225 (interactive)
16226 (org-property-next-allowed-value t))
16228 (defun org-property-next-allowed-value (&optional previous)
16229 "Switch to the next allowed value for this property."
16230 (interactive)
16231 (unless (org-at-property-p)
16232 (user-error "Not at a property"))
16233 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16234 (key (match-string 2))
16235 (value (match-string 3))
16236 (allowed (or (org-property-get-allowed-values (point) key)
16237 (and (member value '("[ ]" "[-]" "[X]"))
16238 '("[ ]" "[X]"))))
16239 (heading (save-match-data (nth 4 (org-heading-components))))
16240 nval)
16241 (unless allowed
16242 (user-error "Allowed values for this property have not been defined"))
16243 (if previous (setq allowed (reverse allowed)))
16244 (if (member value allowed)
16245 (setq nval (car (cdr (member value allowed)))))
16246 (setq nval (or nval (car allowed)))
16247 (if (equal nval value)
16248 (user-error "Only one allowed value for this property"))
16249 (org-at-property-p)
16250 (replace-match (concat " :" key ": " nval) t t)
16251 (org-indent-line)
16252 (beginning-of-line 1)
16253 (skip-chars-forward " \t")
16254 (when (equal prop org-effort-property)
16255 (org-refresh-property
16256 '((effort . identity)
16257 (effort-minutes . org-duration-string-to-minutes))
16258 nval)
16259 (when (string= org-clock-current-task heading)
16260 (setq org-clock-effort nval)
16261 (org-clock-update-mode-line)))
16262 (run-hook-with-args 'org-property-changed-functions key nval)))
16264 (defun org-find-olp (path &optional this-buffer)
16265 "Return a marker pointing to the entry at outline path OLP.
16266 If anything goes wrong, throw an error.
16267 You can wrap this call to catch the error like this:
16269 (condition-case msg
16270 (org-mobile-locate-entry (match-string 4))
16271 (error (nth 1 msg)))
16273 The return value will then be either a string with the error message,
16274 or a marker if everything is OK.
16276 If THIS-BUFFER is set, the outline path does not contain a file,
16277 only headings."
16278 (let* ((file (if this-buffer buffer-file-name (pop path)))
16279 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16280 (level 1)
16281 (lmin 1)
16282 (lmax 1)
16283 limit re end found pos heading cnt flevel)
16284 (unless buffer (error "File not found :%s" file))
16285 (with-current-buffer buffer
16286 (save-excursion
16287 (save-restriction
16288 (widen)
16289 (setq limit (point-max))
16290 (goto-char (point-min))
16291 (while (setq heading (pop path))
16292 (setq re (format org-complex-heading-regexp-format
16293 (regexp-quote heading)))
16294 (setq cnt 0 pos (point))
16295 (while (re-search-forward re end t)
16296 (setq level (- (match-end 1) (match-beginning 1)))
16297 (if (and (>= level lmin) (<= level lmax))
16298 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16299 (when (= cnt 0) (error "Heading not found on level %d: %s"
16300 lmax heading))
16301 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16302 lmax heading))
16303 (goto-char found)
16304 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16305 (setq end (save-excursion (org-end-of-subtree t t))))
16306 (when (org-at-heading-p)
16307 (point-marker)))))))
16309 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16310 "Find node HEADING in BUFFER.
16311 Return a marker to the heading if it was found, or nil if not.
16312 If POS-ONLY is set, return just the position instead of a marker.
16314 The heading text must match exact, but it may have a TODO keyword,
16315 a priority cookie and tags in the standard locations."
16316 (with-current-buffer (or buffer (current-buffer))
16317 (save-excursion
16318 (save-restriction
16319 (widen)
16320 (goto-char (point-min))
16321 (let (case-fold-search)
16322 (if (re-search-forward
16323 (format org-complex-heading-regexp-format
16324 (regexp-quote heading)) nil t)
16325 (if pos-only
16326 (match-beginning 0)
16327 (move-marker (make-marker) (match-beginning 0)))))))))
16329 (defun org-find-exact-heading-in-directory (heading &optional dir)
16330 "Find Org node headline HEADING in all .org files in directory DIR.
16331 When the target headline is found, return a marker to this location."
16332 (let ((files (directory-files (or dir default-directory)
16333 t "\\`[^.#].*\\.org\\'"))
16334 file visiting m buffer)
16335 (catch 'found
16336 (while (setq file (pop files))
16337 (message "trying %s" file)
16338 (setq visiting (org-find-base-buffer-visiting file))
16339 (setq buffer (or visiting (find-file-noselect file)))
16340 (setq m (org-find-exact-headline-in-buffer
16341 heading buffer))
16342 (when (and (not m) (not visiting)) (kill-buffer buffer))
16343 (and m (throw 'found m))))))
16345 (defun org-find-entry-with-id (ident)
16346 "Locate the entry that contains the ID property with exact value IDENT.
16347 IDENT can be a string, a symbol or a number, this function will search for
16348 the string representation of it.
16349 Return the position where this entry starts, or nil if there is no such entry."
16350 (interactive "sID: ")
16351 (let ((id (cond
16352 ((stringp ident) ident)
16353 ((symbol-name ident) (symbol-name ident))
16354 ((numberp ident) (number-to-string ident))
16355 (t (error "IDENT %s must be a string, symbol or number" ident))))
16356 (case-fold-search nil))
16357 (save-excursion
16358 (save-restriction
16359 (widen)
16360 (goto-char (point-min))
16361 (when (re-search-forward
16362 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16363 nil t)
16364 (org-back-to-heading t)
16365 (point))))))
16367 ;;;; Timestamps
16369 (defvar org-last-changed-timestamp nil)
16370 (defvar org-last-inserted-timestamp nil
16371 "The last time stamp inserted with `org-insert-time-stamp'.")
16372 (defvar org-ts-what) ; dynamically scoped parameter
16374 (defun org-time-stamp (arg &optional inactive)
16375 "Prompt for a date/time and insert a time stamp.
16376 If the user specifies a time like HH:MM or if this command is
16377 called with at least one prefix argument, the time stamp contains
16378 the date and the time. Otherwise, only the date is be included.
16380 All parts of a date not specified by the user is filled in from
16381 the current date/time. So if you just press return without
16382 typing anything, the time stamp will represent the current
16383 date/time.
16385 If there is already a timestamp at the cursor, it will be
16386 modified.
16388 With two universal prefix arguments, insert an active timestamp
16389 with the current time without prompting the user.
16391 When called from lisp, the timestamp is inactive if INACTIVE is
16392 non-nil."
16393 (interactive "P")
16394 (let* ((ts nil)
16395 (default-time
16396 ;; Default time is either today, or, when entering a range,
16397 ;; the range start.
16398 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16399 (save-excursion
16400 (re-search-backward
16401 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16402 (- (point) 20) t)))
16403 (apply 'encode-time (org-parse-time-string (match-string 1)))
16404 (current-time)))
16405 (default-input (and ts (org-get-compact-tod ts)))
16406 (repeater (save-excursion
16407 (save-match-data
16408 (beginning-of-line)
16409 (when (re-search-forward
16410 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16411 (save-excursion (progn (end-of-line) (point))) t)
16412 (match-string 0)))))
16413 org-time-was-given org-end-time-was-given time)
16414 (cond
16415 ((and (org-at-timestamp-p t)
16416 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16417 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16418 (insert "--")
16419 (setq time (let ((this-command this-command))
16420 (org-read-date arg 'totime nil nil
16421 default-time default-input inactive)))
16422 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16423 ((org-at-timestamp-p t)
16424 (setq time (let ((this-command this-command))
16425 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16426 (when (org-at-timestamp-p t) ; just to get the match data
16427 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16428 (replace-match "")
16429 (setq org-last-changed-timestamp
16430 (org-insert-time-stamp
16431 time (or org-time-was-given arg)
16432 inactive nil nil (list org-end-time-was-given)))
16433 (when repeater (goto-char (1- (point))) (insert " " repeater)
16434 (setq org-last-changed-timestamp
16435 (concat (substring org-last-inserted-timestamp 0 -1)
16436 " " repeater ">"))))
16437 (message "Timestamp updated"))
16438 ((equal arg '(16))
16439 (org-insert-time-stamp (current-time) t inactive))
16441 (setq time (let ((this-command this-command))
16442 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16443 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16444 nil nil (list org-end-time-was-given))))))
16446 ;; FIXME: can we use this for something else, like computing time differences?
16447 (defun org-get-compact-tod (s)
16448 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16449 (let* ((t1 (match-string 1 s))
16450 (h1 (string-to-number (match-string 2 s)))
16451 (m1 (string-to-number (match-string 3 s)))
16452 (t2 (and (match-end 4) (match-string 5 s)))
16453 (h2 (and t2 (string-to-number (match-string 6 s))))
16454 (m2 (and t2 (string-to-number (match-string 7 s))))
16455 dh dm)
16456 (if (not t2)
16458 (setq dh (- h2 h1) dm (- m2 m1))
16459 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16460 (concat t1 "+" (number-to-string dh)
16461 (and (/= 0 dm) (format ":%02d" dm)))))))
16463 (defun org-time-stamp-inactive (&optional arg)
16464 "Insert an inactive time stamp.
16465 An inactive time stamp is enclosed in square brackets instead of angle
16466 brackets. It is inactive in the sense that it does not trigger agenda entries,
16467 does not link to the calendar and cannot be changed with the S-cursor keys.
16468 So these are more for recording a certain time/date."
16469 (interactive "P")
16470 (org-time-stamp arg 'inactive))
16472 (defvar org-date-ovl (make-overlay 1 1))
16473 (overlay-put org-date-ovl 'face 'org-date-selected)
16474 (org-detach-overlay org-date-ovl)
16476 (defvar org-ans1) ; dynamically scoped parameter
16477 (defvar org-ans2) ; dynamically scoped parameter
16479 (defvar org-plain-time-of-day-regexp) ; defined below
16481 (defvar org-overriding-default-time nil) ; dynamically scoped
16482 (defvar org-read-date-overlay nil)
16483 (defvar org-dcst nil) ; dynamically scoped
16484 (defvar org-read-date-history nil)
16485 (defvar org-read-date-final-answer nil)
16486 (defvar org-read-date-analyze-futurep nil)
16487 (defvar org-read-date-analyze-forced-year nil)
16488 (defvar org-read-date-inactive)
16490 (defvar org-read-date-minibuffer-local-map
16491 (let* ((org-replace-disputed-keys nil)
16492 (map (make-sparse-keymap)))
16493 (set-keymap-parent map minibuffer-local-map)
16494 (org-defkey map (kbd ".")
16495 (lambda () (interactive)
16496 ;; Are we at the beginning of the prompt?
16497 (if (looking-back "^[^:]+: ")
16498 (org-eval-in-calendar '(calendar-goto-today))
16499 (insert "."))))
16500 (org-defkey map (kbd "C-.")
16501 (lambda () (interactive)
16502 (org-eval-in-calendar '(calendar-goto-today))))
16503 (org-defkey map [(meta shift left)]
16504 (lambda () (interactive)
16505 (org-eval-in-calendar '(calendar-backward-month 1))))
16506 (org-defkey map [(meta shift right)]
16507 (lambda () (interactive)
16508 (org-eval-in-calendar '(calendar-forward-month 1))))
16509 (org-defkey map [(meta shift up)]
16510 (lambda () (interactive)
16511 (org-eval-in-calendar '(calendar-backward-year 1))))
16512 (org-defkey map [(meta shift down)]
16513 (lambda () (interactive)
16514 (org-eval-in-calendar '(calendar-forward-year 1))))
16515 (org-defkey map [?\e (shift left)]
16516 (lambda () (interactive)
16517 (org-eval-in-calendar '(calendar-backward-month 1))))
16518 (org-defkey map [?\e (shift right)]
16519 (lambda () (interactive)
16520 (org-eval-in-calendar '(calendar-forward-month 1))))
16521 (org-defkey map [?\e (shift up)]
16522 (lambda () (interactive)
16523 (org-eval-in-calendar '(calendar-backward-year 1))))
16524 (org-defkey map [?\e (shift down)]
16525 (lambda () (interactive)
16526 (org-eval-in-calendar '(calendar-forward-year 1))))
16527 (org-defkey map [(shift up)]
16528 (lambda () (interactive)
16529 (org-eval-in-calendar '(calendar-backward-week 1))))
16530 (org-defkey map [(shift down)]
16531 (lambda () (interactive)
16532 (org-eval-in-calendar '(calendar-forward-week 1))))
16533 (org-defkey map [(shift left)]
16534 (lambda () (interactive)
16535 (org-eval-in-calendar '(calendar-backward-day 1))))
16536 (org-defkey map [(shift right)]
16537 (lambda () (interactive)
16538 (org-eval-in-calendar '(calendar-forward-day 1))))
16539 (org-defkey map "!"
16540 (lambda () (interactive)
16541 (org-eval-in-calendar '(diary-view-entries))
16542 (message "")))
16543 (org-defkey map ">"
16544 (lambda () (interactive)
16545 (org-eval-in-calendar '(calendar-scroll-left 1))))
16546 (org-defkey map "<"
16547 (lambda () (interactive)
16548 (org-eval-in-calendar '(calendar-scroll-right 1))))
16549 (org-defkey map "\C-v"
16550 (lambda () (interactive)
16551 (org-eval-in-calendar
16552 '(calendar-scroll-left-three-months 1))))
16553 (org-defkey map "\M-v"
16554 (lambda () (interactive)
16555 (org-eval-in-calendar
16556 '(calendar-scroll-right-three-months 1))))
16557 map)
16558 "Keymap for minibuffer commands when using `org-read-date'.")
16560 (defvar org-def)
16561 (defvar org-defdecode)
16562 (defvar org-with-time)
16564 (defun org-read-date (&optional org-with-time to-time from-string prompt
16565 default-time default-input inactive)
16566 "Read a date, possibly a time, and make things smooth for the user.
16567 The prompt will suggest to enter an ISO date, but you can also enter anything
16568 which will at least partially be understood by `parse-time-string'.
16569 Unrecognized parts of the date will default to the current day, month, year,
16570 hour and minute. If this command is called to replace a timestamp at point,
16571 or to enter the second timestamp of a range, the default time is taken
16572 from the existing stamp. Furthermore, the command prefers the future,
16573 so if you are giving a date where the year is not given, and the day-month
16574 combination is already past in the current year, it will assume you
16575 mean next year. For details, see the manual. A few examples:
16577 3-2-5 --> 2003-02-05
16578 feb 15 --> currentyear-02-15
16579 2/15 --> currentyear-02-15
16580 sep 12 9 --> 2009-09-12
16581 12:45 --> today 12:45
16582 22 sept 0:34 --> currentyear-09-22 0:34
16583 12 --> currentyear-currentmonth-12
16584 Fri --> nearest Friday after today
16585 -Tue --> last Tuesday
16586 etc.
16588 Furthermore you can specify a relative date by giving, as the *first* thing
16589 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16590 change in days weeks, months, years.
16591 With a single plus or minus, the date is relative to today. With a double
16592 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16593 +4d --> four days from today
16594 +4 --> same as above
16595 +2w --> two weeks from today
16596 ++5 --> five days from default date
16598 The function understands only English month and weekday abbreviations.
16600 While prompting, a calendar is popped up - you can also select the
16601 date with the mouse (button 1). The calendar shows a period of three
16602 months. To scroll it to other months, use the keys `>' and `<'.
16603 If you don't like the calendar, turn it off with
16604 \(setq org-read-date-popup-calendar nil)
16606 With optional argument TO-TIME, the date will immediately be converted
16607 to an internal time.
16608 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16609 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16610 still enter a time, and this function will inform the calling routine
16611 about this change. The calling routine may then choose to change the
16612 format used to insert the time stamp into the buffer to include the time.
16613 With optional argument FROM-STRING, read from this string instead from
16614 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16615 the time/date that is used for everything that is not specified by the
16616 user."
16617 (require 'parse-time)
16618 (let* ((org-time-stamp-rounding-minutes
16619 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16620 (org-dcst org-display-custom-times)
16621 (ct (org-current-time))
16622 (org-def (or org-overriding-default-time default-time ct))
16623 (org-defdecode (decode-time org-def))
16624 (dummy (progn
16625 (when (< (nth 2 org-defdecode) org-extend-today-until)
16626 (setcar (nthcdr 2 org-defdecode) -1)
16627 (setcar (nthcdr 1 org-defdecode) 59)
16628 (setq org-def (apply 'encode-time org-defdecode)
16629 org-defdecode (decode-time org-def)))))
16630 (mouse-autoselect-window nil) ; Don't let the mouse jump
16631 (calendar-frame-setup nil)
16632 (calendar-setup nil)
16633 (calendar-move-hook nil)
16634 (calendar-view-diary-initially-flag nil)
16635 (calendar-view-holidays-initially-flag nil)
16636 (timestr (format-time-string
16637 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16638 (prompt (concat (if prompt (concat prompt " ") "")
16639 (format "Date+time [%s]: " timestr)))
16640 ans (org-ans0 "") org-ans1 org-ans2 final)
16642 (cond
16643 (from-string (setq ans from-string))
16644 (org-read-date-popup-calendar
16645 (save-excursion
16646 (save-window-excursion
16647 (calendar)
16648 (org-eval-in-calendar '(setq cursor-type nil) t)
16649 (unwind-protect
16650 (progn
16651 (calendar-forward-day (- (time-to-days org-def)
16652 (calendar-absolute-from-gregorian
16653 (calendar-current-date))))
16654 (org-eval-in-calendar nil t)
16655 (let* ((old-map (current-local-map))
16656 (map (copy-keymap calendar-mode-map))
16657 (minibuffer-local-map
16658 (copy-keymap org-read-date-minibuffer-local-map)))
16659 (org-defkey map (kbd "RET") 'org-calendar-select)
16660 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16661 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16662 (unwind-protect
16663 (progn
16664 (use-local-map map)
16665 (setq org-read-date-inactive inactive)
16666 (add-hook 'post-command-hook 'org-read-date-display)
16667 (setq org-ans0 (read-string prompt default-input
16668 'org-read-date-history nil))
16669 ;; org-ans0: from prompt
16670 ;; org-ans1: from mouse click
16671 ;; org-ans2: from calendar motion
16672 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16673 (remove-hook 'post-command-hook 'org-read-date-display)
16674 (use-local-map old-map)
16675 (when org-read-date-overlay
16676 (delete-overlay org-read-date-overlay)
16677 (setq org-read-date-overlay nil)))))
16678 (bury-buffer "*Calendar*")))))
16680 (t ; Naked prompt only
16681 (unwind-protect
16682 (setq ans (read-string prompt default-input
16683 'org-read-date-history timestr))
16684 (when org-read-date-overlay
16685 (delete-overlay org-read-date-overlay)
16686 (setq org-read-date-overlay nil)))))
16688 (setq final (org-read-date-analyze ans org-def org-defdecode))
16690 (when org-read-date-analyze-forced-year
16691 (message "Year was forced into %s"
16692 (if org-read-date-force-compatible-dates
16693 "compatible range (1970-2037)"
16694 "range representable on this machine"))
16695 (ding))
16697 ;; One round trip to get rid of 34th of August and stuff like that....
16698 (setq final (decode-time (apply 'encode-time final)))
16700 (setq org-read-date-final-answer ans)
16702 (if to-time
16703 (apply 'encode-time final)
16704 (if (and (boundp 'org-time-was-given) org-time-was-given)
16705 (format "%04d-%02d-%02d %02d:%02d"
16706 (nth 5 final) (nth 4 final) (nth 3 final)
16707 (nth 2 final) (nth 1 final))
16708 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16710 (defun org-read-date-display ()
16711 "Display the current date prompt interpretation in the minibuffer."
16712 (when org-read-date-display-live
16713 (when org-read-date-overlay
16714 (delete-overlay org-read-date-overlay))
16715 (when (minibufferp (current-buffer))
16716 (save-excursion
16717 (end-of-line 1)
16718 (while (not (equal (buffer-substring
16719 (max (point-min) (- (point) 4)) (point))
16720 " "))
16721 (insert " ")))
16722 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16723 " " (or org-ans1 org-ans2)))
16724 (org-end-time-was-given nil)
16725 (f (org-read-date-analyze ans org-def org-defdecode))
16726 (fmts (if org-dcst
16727 org-time-stamp-custom-formats
16728 org-time-stamp-formats))
16729 (fmt (if (or org-with-time
16730 (and (boundp 'org-time-was-given) org-time-was-given))
16731 (cdr fmts)
16732 (car fmts)))
16733 (txt (format-time-string fmt (apply 'encode-time f)))
16734 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16735 (txt (concat "=> " txt)))
16736 (when (and org-end-time-was-given
16737 (string-match org-plain-time-of-day-regexp txt))
16738 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16739 org-end-time-was-given
16740 (substring txt (match-end 0)))))
16741 (when org-read-date-analyze-futurep
16742 (setq txt (concat txt " (=>F)")))
16743 (setq org-read-date-overlay
16744 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16745 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16747 (defun org-read-date-analyze (ans org-def org-defdecode)
16748 "Analyze the combined answer of the date prompt."
16749 ;; FIXME: cleanup and comment
16750 (let ((nowdecode (decode-time (current-time)))
16751 delta deltan deltaw deltadef year month day
16752 hour minute second wday pm h2 m2 tl wday1
16753 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16754 (setq org-read-date-analyze-futurep nil
16755 org-read-date-analyze-forced-year nil)
16756 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16757 (setq ans "+0"))
16759 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16760 (setq ans (replace-match "" t t ans)
16761 deltan (car delta)
16762 deltaw (nth 1 delta)
16763 deltadef (nth 2 delta)))
16765 ;; Check if there is an iso week date in there. If yes, store the
16766 ;; info and postpone interpreting it until the rest of the parsing
16767 ;; is done.
16768 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16769 (setq iso-year (if (match-end 1)
16770 (org-small-year-to-year
16771 (string-to-number (match-string 1 ans))))
16772 iso-weekday (if (match-end 3)
16773 (string-to-number (match-string 3 ans)))
16774 iso-week (string-to-number (match-string 2 ans)))
16775 (setq ans (replace-match "" t t ans)))
16777 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16778 (when (string-match
16779 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16780 (setq year (if (match-end 2)
16781 (string-to-number (match-string 2 ans))
16782 (progn (setq kill-year t)
16783 (string-to-number (format-time-string "%Y"))))
16784 month (string-to-number (match-string 3 ans))
16785 day (string-to-number (match-string 4 ans)))
16786 (if (< year 100) (setq year (+ 2000 year)))
16787 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16788 t nil ans)))
16790 ;; Help matching dotted european dates
16791 (when (string-match
16792 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16793 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16794 (setq kill-year t)
16795 (string-to-number (format-time-string "%Y")))
16796 day (string-to-number (match-string 1 ans))
16797 month (string-to-number (match-string 2 ans))
16798 ans (replace-match (format "%04d-%02d-%02d" year month day)
16799 t nil ans)))
16801 ;; Help matching american dates, like 5/30 or 5/30/7
16802 (when (string-match
16803 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16804 (setq year (if (match-end 4)
16805 (string-to-number (match-string 4 ans))
16806 (progn (setq kill-year t)
16807 (string-to-number (format-time-string "%Y"))))
16808 month (string-to-number (match-string 1 ans))
16809 day (string-to-number (match-string 2 ans)))
16810 (if (< year 100) (setq year (+ 2000 year)))
16811 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16812 t nil ans)))
16813 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16814 ;; If there is a time with am/pm, and *no* time without it, we convert
16815 ;; so that matching will be successful.
16816 (loop for i from 1 to 2 do ; twice, for end time as well
16817 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16818 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16819 (setq hour (string-to-number (match-string 1 ans))
16820 minute (if (match-end 3)
16821 (string-to-number (match-string 3 ans))
16823 pm (equal ?p
16824 (string-to-char (downcase (match-string 4 ans)))))
16825 (if (and (= hour 12) (not pm))
16826 (setq hour 0)
16827 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16828 (setq ans (replace-match (format "%02d:%02d" hour minute)
16829 t t ans))))
16831 ;; Check if a time range is given as a duration
16832 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16833 (setq hour (string-to-number (match-string 1 ans))
16834 h2 (+ hour (string-to-number (match-string 3 ans)))
16835 minute (string-to-number (match-string 2 ans))
16836 m2 (+ minute (if (match-end 5) (string-to-number
16837 (match-string 5 ans))0)))
16838 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16839 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16840 t t ans)))
16842 ;; Check if there is a time range
16843 (when (boundp 'org-end-time-was-given)
16844 (setq org-time-was-given nil)
16845 (when (and (string-match org-plain-time-of-day-regexp ans)
16846 (match-end 8))
16847 (setq org-end-time-was-given (match-string 8 ans))
16848 (setq ans (concat (substring ans 0 (match-beginning 7))
16849 (substring ans (match-end 7))))))
16851 (setq tl (parse-time-string ans)
16852 day (or (nth 3 tl) (nth 3 org-defdecode))
16853 month (or (nth 4 tl)
16854 (if (and org-read-date-prefer-future
16855 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16856 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16857 (nth 4 org-defdecode)))
16858 year (or (and (not kill-year) (nth 5 tl))
16859 (if (and org-read-date-prefer-future
16860 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16861 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16862 (nth 5 org-defdecode)))
16863 hour (or (nth 2 tl) (nth 2 org-defdecode))
16864 minute (or (nth 1 tl) (nth 1 org-defdecode))
16865 second (or (nth 0 tl) 0)
16866 wday (nth 6 tl))
16868 (when (and (eq org-read-date-prefer-future 'time)
16869 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16870 (equal day (nth 3 nowdecode))
16871 (equal month (nth 4 nowdecode))
16872 (equal year (nth 5 nowdecode))
16873 (nth 2 tl)
16874 (or (< (nth 2 tl) (nth 2 nowdecode))
16875 (and (= (nth 2 tl) (nth 2 nowdecode))
16876 (nth 1 tl)
16877 (< (nth 1 tl) (nth 1 nowdecode)))))
16878 (setq day (1+ day)
16879 futurep t))
16881 ;; Special date definitions below
16882 (cond
16883 (iso-week
16884 ;; There was an iso week
16885 (require 'cal-iso)
16886 (setq futurep nil)
16887 (setq year (or iso-year year)
16888 day (or iso-weekday wday 1)
16889 wday nil ; to make sure that the trigger below does not match
16890 iso-date (calendar-gregorian-from-absolute
16891 (calendar-absolute-from-iso
16892 (list iso-week day year))))
16893 ; FIXME: Should we also push ISO weeks into the future?
16894 ; (when (and org-read-date-prefer-future
16895 ; (not iso-year)
16896 ; (< (calendar-absolute-from-gregorian iso-date)
16897 ; (time-to-days (current-time))))
16898 ; (setq year (1+ year)
16899 ; iso-date (calendar-gregorian-from-absolute
16900 ; (calendar-absolute-from-iso
16901 ; (list iso-week day year)))))
16902 (setq month (car iso-date)
16903 year (nth 2 iso-date)
16904 day (nth 1 iso-date)))
16905 (deltan
16906 (setq futurep nil)
16907 (unless deltadef
16908 (let ((now (decode-time (current-time))))
16909 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16910 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16911 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16912 ((equal deltaw "m") (setq month (+ month deltan)))
16913 ((equal deltaw "y") (setq year (+ year deltan)))))
16914 ((and wday (not (nth 3 tl)))
16915 ;; Weekday was given, but no day, so pick that day in the week
16916 ;; on or after the derived date.
16917 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16918 (unless (equal wday wday1)
16919 (setq day (+ day (% (- wday wday1 -7) 7))))))
16920 (if (and (boundp 'org-time-was-given)
16921 (nth 2 tl))
16922 (setq org-time-was-given t))
16923 (if (< year 100) (setq year (+ 2000 year)))
16924 ;; Check of the date is representable
16925 (if org-read-date-force-compatible-dates
16926 (progn
16927 (if (< year 1970)
16928 (setq year 1970 org-read-date-analyze-forced-year t))
16929 (if (> year 2037)
16930 (setq year 2037 org-read-date-analyze-forced-year t)))
16931 (condition-case nil
16932 (ignore (encode-time second minute hour day month year))
16933 (error
16934 (setq year (nth 5 org-defdecode))
16935 (setq org-read-date-analyze-forced-year t))))
16936 (setq org-read-date-analyze-futurep futurep)
16937 (list second minute hour day month year)))
16939 (defvar parse-time-weekdays)
16940 (defun org-read-date-get-relative (s today default)
16941 "Check string S for special relative date string.
16942 TODAY and DEFAULT are internal times, for today and for a default.
16943 Return shift list (N what def-flag)
16944 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16945 N is the number of WHATs to shift.
16946 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16947 the DEFAULT date rather than TODAY."
16948 (require 'parse-time)
16949 (when (and
16950 (string-match
16951 (concat
16952 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16953 "\\([0-9]+\\)?"
16954 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16955 "\\([ \t]\\|$\\)") s)
16956 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16957 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16958 (string-to-char (substring (match-string 1 s) -1))
16959 ?+))
16960 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16961 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16962 (what (if (match-end 3) (match-string 3 s) "d"))
16963 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16964 (date (if rel default today))
16965 (wday (nth 6 (decode-time date)))
16966 delta)
16967 (if wday1
16968 (progn
16969 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16970 (if (= delta 0) (setq delta 7))
16971 (if (= dir ?-)
16972 (progn
16973 (setq delta (- delta 7))
16974 (if (= delta 0) (setq delta -7))))
16975 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16976 (list delta "d" rel))
16977 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16979 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16980 "Turn a user-specified date into the internal representation.
16981 The internal representation needed by the calendar is (month day year).
16982 This is a wrapper to handle the brain-dead convention in calendar that
16983 user function argument order change dependent on argument order."
16984 (if (boundp 'calendar-date-style)
16985 (cond
16986 ((eq calendar-date-style 'american)
16987 (list arg1 arg2 arg3))
16988 ((eq calendar-date-style 'european)
16989 (list arg2 arg1 arg3))
16990 ((eq calendar-date-style 'iso)
16991 (list arg2 arg3 arg1)))
16992 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16993 (if (org-bound-and-true-p european-calendar-style)
16994 (list arg2 arg1 arg3)
16995 (list arg1 arg2 arg3)))))
16997 (defun org-eval-in-calendar (form &optional keepdate)
16998 "Eval FORM in the calendar window and return to current window.
16999 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17000 otherwise stick to the current value of `org-ans2'."
17001 (let ((sf (selected-frame))
17002 (sw (selected-window)))
17003 (select-window (get-buffer-window "*Calendar*" t))
17004 (eval form)
17005 (when (and (not keepdate) (calendar-cursor-to-date))
17006 (let* ((date (calendar-cursor-to-date))
17007 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17008 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17009 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17010 (select-window sw)
17011 (org-select-frame-set-input-focus sf)))
17013 (defun org-calendar-select ()
17014 "Return to `org-read-date' with the date currently selected.
17015 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17016 (interactive)
17017 (when (calendar-cursor-to-date)
17018 (let* ((date (calendar-cursor-to-date))
17019 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17020 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17021 (if (active-minibuffer-window) (exit-minibuffer))))
17023 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17024 "Insert a date stamp for the date given by the internal TIME.
17025 WITH-HM means use the stamp format that includes the time of the day.
17026 INACTIVE means use square brackets instead of angular ones, so that the
17027 stamp will not contribute to the agenda.
17028 PRE and POST are optional strings to be inserted before and after the
17029 stamp.
17030 The command returns the inserted time stamp."
17031 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17032 stamp)
17033 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17034 (insert-before-markers (or pre ""))
17035 (when (listp extra)
17036 (setq extra (car extra))
17037 (if (and (stringp extra)
17038 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17039 (setq extra (format "-%02d:%02d"
17040 (string-to-number (match-string 1 extra))
17041 (string-to-number (match-string 2 extra))))
17042 (setq extra nil)))
17043 (when extra
17044 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17045 (insert-before-markers (setq stamp (format-time-string fmt time)))
17046 (insert-before-markers (or post ""))
17047 (setq org-last-inserted-timestamp stamp)))
17049 (defun org-toggle-time-stamp-overlays ()
17050 "Toggle the use of custom time stamp formats."
17051 (interactive)
17052 (setq org-display-custom-times (not org-display-custom-times))
17053 (unless org-display-custom-times
17054 (let ((p (point-min)) (bmp (buffer-modified-p)))
17055 (while (setq p (next-single-property-change p 'display))
17056 (if (and (get-text-property p 'display)
17057 (eq (get-text-property p 'face) 'org-date))
17058 (remove-text-properties
17059 p (setq p (next-single-property-change p 'display))
17060 '(display t))))
17061 (set-buffer-modified-p bmp)))
17062 (if (featurep 'xemacs)
17063 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17064 (org-restart-font-lock)
17065 (setq org-table-may-need-update t)
17066 (if org-display-custom-times
17067 (message "Time stamps are overlaid with custom format")
17068 (message "Time stamp overlays removed")))
17070 (defun org-display-custom-time (beg end)
17071 "Overlay modified time stamp format over timestamp between BEG and END."
17072 (let* ((ts (buffer-substring beg end))
17073 t1 w1 with-hm tf time str w2 (off 0))
17074 (save-match-data
17075 (setq t1 (org-parse-time-string ts t))
17076 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17077 (setq off (- (match-end 0) (match-beginning 0)))))
17078 (setq end (- end off))
17079 (setq w1 (- end beg)
17080 with-hm (and (nth 1 t1) (nth 2 t1))
17081 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17082 time (org-fix-decoded-time t1)
17083 str (org-add-props
17084 (format-time-string
17085 (substring tf 1 -1) (apply 'encode-time time))
17086 nil 'mouse-face 'highlight)
17087 w2 (length str))
17088 (if (not (= w2 w1))
17089 (add-text-properties (1+ beg) (+ 2 beg)
17090 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17091 (if (featurep 'xemacs)
17092 (progn
17093 (put-text-property beg end 'invisible t)
17094 (put-text-property beg end 'end-glyph (make-glyph str)))
17095 (put-text-property beg end 'display str))))
17097 (defun org-translate-time (string)
17098 "Translate all timestamps in STRING to custom format.
17099 But do this only if the variable `org-display-custom-times' is set."
17100 (when org-display-custom-times
17101 (save-match-data
17102 (let* ((start 0)
17103 (re org-ts-regexp-both)
17104 t1 with-hm inactive tf time str beg end)
17105 (while (setq start (string-match re string start))
17106 (setq beg (match-beginning 0)
17107 end (match-end 0)
17108 t1 (save-match-data
17109 (org-parse-time-string (substring string beg end) t))
17110 with-hm (and (nth 1 t1) (nth 2 t1))
17111 inactive (equal (substring string beg (1+ beg)) "[")
17112 tf (funcall (if with-hm 'cdr 'car)
17113 org-time-stamp-custom-formats)
17114 time (org-fix-decoded-time t1)
17115 str (format-time-string
17116 (concat
17117 (if inactive "[" "<") (substring tf 1 -1)
17118 (if inactive "]" ">"))
17119 (apply 'encode-time time))
17120 string (replace-match str t t string)
17121 start (+ start (length str)))))))
17122 string)
17124 (defun org-fix-decoded-time (time)
17125 "Set 0 instead of nil for the first 6 elements of time.
17126 Don't touch the rest."
17127 (let ((n 0))
17128 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17130 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17132 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17133 "Difference between TIMESTAMP-STRING and now in days.
17134 If SECONDS is non-nil, return the difference in seconds."
17135 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17136 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17137 (funcall fdiff (current-time)))))
17139 (defun org-deadline-close (timestamp-string &optional ndays)
17140 "Is the time in TIMESTAMP-STRING close to the current date?"
17141 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17142 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17143 (not (org-entry-is-done-p))))
17145 (defun org-get-wdays (ts &optional delay zero-delay)
17146 "Get the deadline lead time appropriate for timestring TS.
17147 When DELAY is non-nil, get the delay time for scheduled items
17148 instead of the deadline lead time. When ZERO-DELAY is non-nil
17149 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17150 don't try to find the delay cookie in the scheduled timestamp."
17151 (let ((tv (if delay org-scheduled-delay-days
17152 org-deadline-warning-days)))
17153 (cond
17154 ((or (and delay (< tv 0))
17155 (and delay zero-delay (<= tv 0))
17156 (and (not delay) (<= tv 0)))
17157 ;; Enforce this value no matter what
17158 (- tv))
17159 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17160 ;; lead time is specified.
17161 (floor (* (string-to-number (match-string 1 ts))
17162 (cdr (assoc (match-string 2 ts)
17163 '(("d" . 1) ("w" . 7)
17164 ("m" . 30.4) ("y" . 365.25)
17165 ("h" . 0.041667)))))))
17166 ;; go for the default.
17167 (t tv))))
17169 (defun org-calendar-select-mouse (ev)
17170 "Return to `org-read-date' with the date currently selected.
17171 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17172 (interactive "e")
17173 (mouse-set-point ev)
17174 (when (calendar-cursor-to-date)
17175 (let* ((date (calendar-cursor-to-date))
17176 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17177 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17178 (if (active-minibuffer-window) (exit-minibuffer))))
17180 (defun org-check-deadlines (ndays)
17181 "Check if there are any deadlines due or past due.
17182 A deadline is considered due if it happens within `org-deadline-warning-days'
17183 days from today's date. If the deadline appears in an entry marked DONE,
17184 it is not shown. The prefix arg NDAYS can be used to test that many
17185 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17186 (interactive "P")
17187 (let* ((org-warn-days
17188 (cond
17189 ((equal ndays '(4)) 100000)
17190 (ndays (prefix-numeric-value ndays))
17191 (t (abs org-deadline-warning-days))))
17192 (case-fold-search nil)
17193 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17194 (callback
17195 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17197 (message "%d deadlines past-due or due within %d days"
17198 (org-occur regexp nil callback)
17199 org-warn-days)))
17201 (defsubst org-re-timestamp (type)
17202 "Return a regexp for timestamp TYPE.
17203 Allowed values for TYPE are:
17205 all: all timestamps
17206 active: only active timestamps (<...>)
17207 inactive: only inactive timestamps ([...])
17208 scheduled: only scheduled timestamps
17209 deadline: only deadline timestamps
17210 closed: only closed time-stamps
17212 When TYPE is nil, fall back on returning a regexp that matches
17213 both scheduled and deadline timestamps."
17214 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17215 ((eq type 'active) org-ts-regexp)
17216 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17217 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17218 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17219 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17220 ((eq type 'scheduled-or-deadline)
17221 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17223 (defun org-check-before-date (date)
17224 "Check if there are deadlines or scheduled entries before DATE."
17225 (interactive (list (org-read-date)))
17226 (let ((case-fold-search nil)
17227 (regexp (org-re-timestamp org-ts-type))
17228 (callback
17229 (lambda () (time-less-p
17230 (org-time-string-to-time (match-string 1))
17231 (org-time-string-to-time date)))))
17232 (message "%d entries before %s"
17233 (org-occur regexp nil callback) date)))
17235 (defun org-check-after-date (date)
17236 "Check if there are deadlines or scheduled entries after DATE."
17237 (interactive (list (org-read-date)))
17238 (let ((case-fold-search nil)
17239 (regexp (org-re-timestamp org-ts-type))
17240 (callback
17241 (lambda () (not
17242 (time-less-p
17243 (org-time-string-to-time (match-string 1))
17244 (org-time-string-to-time date))))))
17245 (message "%d entries after %s"
17246 (org-occur regexp nil callback) date)))
17248 (defun org-check-dates-range (start-date end-date)
17249 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17250 (interactive (list (org-read-date nil nil nil "Range starts")
17251 (org-read-date nil nil nil "Range end")))
17252 (let ((case-fold-search nil)
17253 (regexp (org-re-timestamp org-ts-type))
17254 (callback
17255 (lambda ()
17256 (let ((match (match-string 1)))
17257 (and
17258 (not (time-less-p
17259 (org-time-string-to-time match)
17260 (org-time-string-to-time start-date)))
17261 (time-less-p
17262 (org-time-string-to-time match)
17263 (org-time-string-to-time end-date)))))))
17264 (message "%d entries between %s and %s"
17265 (org-occur regexp nil callback) start-date end-date)))
17267 (defun org-evaluate-time-range (&optional to-buffer)
17268 "Evaluate a time range by computing the difference between start and end.
17269 Normally the result is just printed in the echo area, but with prefix arg
17270 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17271 If the time range is actually in a table, the result is inserted into the
17272 next column.
17273 For time difference computation, a year is assumed to be exactly 365
17274 days in order to avoid rounding problems."
17275 (interactive "P")
17277 (org-clock-update-time-maybe)
17278 (save-excursion
17279 (unless (org-at-date-range-p t)
17280 (goto-char (point-at-bol))
17281 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17282 (if (not (org-at-date-range-p t))
17283 (user-error "Not at a time-stamp range, and none found in current line")))
17284 (let* ((ts1 (match-string 1))
17285 (ts2 (match-string 2))
17286 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17287 (match-end (match-end 0))
17288 (time1 (org-time-string-to-time ts1))
17289 (time2 (org-time-string-to-time ts2))
17290 (t1 (org-float-time time1))
17291 (t2 (org-float-time time2))
17292 (diff (abs (- t2 t1)))
17293 (negative (< (- t2 t1) 0))
17294 ;; (ys (floor (* 365 24 60 60)))
17295 (ds (* 24 60 60))
17296 (hs (* 60 60))
17297 (fy "%dy %dd %02d:%02d")
17298 (fy1 "%dy %dd")
17299 (fd "%dd %02d:%02d")
17300 (fd1 "%dd")
17301 (fh "%02d:%02d")
17302 y d h m align)
17303 (if havetime
17304 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17306 d (floor (/ diff ds)) diff (mod diff ds)
17307 h (floor (/ diff hs)) diff (mod diff hs)
17308 m (floor (/ diff 60)))
17309 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17311 d (floor (+ (/ diff ds) 0.5))
17312 h 0 m 0))
17313 (if (not to-buffer)
17314 (message "%s" (org-make-tdiff-string y d h m))
17315 (if (org-at-table-p)
17316 (progn
17317 (goto-char match-end)
17318 (setq align t)
17319 (and (looking-at " *|") (goto-char (match-end 0))))
17320 (goto-char match-end))
17321 (if (looking-at
17322 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17323 (replace-match ""))
17324 (if negative (insert " -"))
17325 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17326 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17327 (insert " " (format fh h m))))
17328 (if align (org-table-align))
17329 (message "Time difference inserted")))))
17331 (defun org-make-tdiff-string (y d h m)
17332 (let ((fmt "")
17333 (l nil))
17334 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17335 l (push y l)))
17336 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17337 l (push d l)))
17338 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17339 l (push h l)))
17340 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17341 l (push m l)))
17342 (apply 'format fmt (nreverse l))))
17344 (defun org-time-string-to-time (s &optional buffer pos)
17345 "Convert a timestamp string into internal time."
17346 (condition-case errdata
17347 (apply 'encode-time (org-parse-time-string s))
17348 (error (error "Bad timestamp `%s'%s\nError was: %s"
17349 s (if (not (and buffer pos))
17351 (format " at %d in buffer `%s'" pos buffer))
17352 (cdr errdata)))))
17354 (defun org-time-string-to-seconds (s)
17355 "Convert a timestamp string to a number of seconds."
17356 (org-float-time (org-time-string-to-time s)))
17358 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17359 "Convert a time stamp to an absolute day number.
17360 If there is a specifier for a cyclic time stamp, get the closest
17361 date to DAYNR.
17362 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17363 The variable `date' is bound by the calendar when this is called."
17364 (cond
17365 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17366 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17367 daynr
17368 (+ daynr 1000)))
17369 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17370 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17371 (time-to-days (current-time))) (match-string 0 s)
17372 prefer show-all))
17373 (t (time-to-days
17374 (condition-case errdata
17375 (apply 'encode-time (org-parse-time-string s))
17376 (error (error "Bad timestamp `%s'%s\nError was: %s"
17377 s (if (not (and buffer pos))
17379 (format " at %d in buffer `%s'" pos buffer))
17380 (cdr errdata))))))))
17382 (defun org-days-to-iso-week (days)
17383 "Return the iso week number."
17384 (require 'cal-iso)
17385 (car (calendar-iso-from-absolute days)))
17387 (defun org-small-year-to-year (year)
17388 "Convert 2-digit years into 4-digit years.
17389 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17390 The year 2000 cannot be abbreviated. Any year larger than 99
17391 is returned unchanged."
17392 (if (< year 38)
17393 (setq year (+ 2000 year))
17394 (if (< year 100)
17395 (setq year (+ 1900 year))))
17396 year)
17398 (defun org-time-from-absolute (d)
17399 "Return the time corresponding to date D.
17400 D may be an absolute day number, or a calendar-type list (month day year)."
17401 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17402 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17404 (defun org-calendar-holiday ()
17405 "List of holidays, for Diary display in Org-mode."
17406 (require 'holidays)
17407 (let ((hl (funcall
17408 (if (fboundp 'calendar-check-holidays)
17409 'calendar-check-holidays 'check-calendar-holidays) date)))
17410 (if hl (mapconcat 'identity hl "; "))))
17412 (defun org-diary-sexp-entry (sexp entry date)
17413 "Process a SEXP diary ENTRY for DATE."
17414 (require 'diary-lib)
17415 (let ((result (if calendar-debug-sexp
17416 (let ((stack-trace-on-error t))
17417 (eval (car (read-from-string sexp))))
17418 (condition-case nil
17419 (eval (car (read-from-string sexp)))
17420 (error
17421 (beep)
17422 (message "Bad sexp at line %d in %s: %s"
17423 (org-current-line)
17424 (buffer-file-name) sexp)
17425 (sleep-for 2))))))
17426 (cond ((stringp result) (split-string result "; "))
17427 ((and (consp result)
17428 (not (consp (cdr result)))
17429 (stringp (cdr result))) (cdr result))
17430 ((and (consp result)
17431 (stringp (car result))) result)
17432 (result entry))))
17434 (defun org-diary-to-ical-string (frombuf)
17435 "Get iCalendar entries from diary entries in buffer FROMBUF.
17436 This uses the icalendar.el library."
17437 (let* ((tmpdir (if (featurep 'xemacs)
17438 (temp-directory)
17439 temporary-file-directory))
17440 (tmpfile (make-temp-name
17441 (expand-file-name "orgics" tmpdir)))
17442 buf rtn b e)
17443 (with-current-buffer frombuf
17444 (icalendar-export-region (point-min) (point-max) tmpfile)
17445 (setq buf (find-buffer-visiting tmpfile))
17446 (set-buffer buf)
17447 (goto-char (point-min))
17448 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17449 (setq b (match-beginning 0)))
17450 (goto-char (point-max))
17451 (if (re-search-backward "^END:VEVENT" nil t)
17452 (setq e (match-end 0)))
17453 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17454 (kill-buffer buf)
17455 (delete-file tmpfile)
17456 rtn))
17458 (defun org-closest-date (start current change prefer show-all)
17459 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17460 When PREFER is `past', return a date that is either CURRENT or past.
17461 When PREFER is `future', return a date that is either CURRENT or future.
17462 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17463 ;; Make the proper lists from the dates
17464 (catch 'exit
17465 (let ((a1 '(("h" . hour)
17466 ("d" . day)
17467 ("w" . week)
17468 ("m" . month)
17469 ("y" . year)))
17470 (shour (nth 2 (org-parse-time-string start)))
17471 dn dw sday cday n1 n2 n0
17472 d m y y1 y2 date1 date2 nmonths nm ny m2)
17474 (setq start (org-date-to-gregorian start)
17475 current (org-date-to-gregorian
17476 (if show-all
17477 current
17478 (time-to-days (current-time))))
17479 sday (calendar-absolute-from-gregorian start)
17480 cday (calendar-absolute-from-gregorian current))
17482 (if (<= cday sday) (throw 'exit sday))
17484 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17485 (setq dn (string-to-number (match-string 1 change))
17486 dw (cdr (assoc (match-string 2 change) a1)))
17487 (user-error "Invalid change specifier: %s" change))
17488 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17489 (cond
17490 ((eq dw 'hour)
17491 (let ((missing-hours
17492 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17493 dn)))
17494 (setq n1 (if (zerop missing-hours) cday
17495 (- cday (1+ (floor (/ missing-hours 24)))))
17496 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17497 ((eq dw 'day)
17498 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17499 n2 (+ n1 dn)))
17500 ((eq dw 'year)
17501 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17502 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17503 (setq date1 (list m d y1)
17504 n1 (calendar-absolute-from-gregorian date1)
17505 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17506 n2 (calendar-absolute-from-gregorian date2)))
17507 ((eq dw 'month)
17508 ;; approx number of month between the two dates
17509 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17510 ;; How often does dn fit in there?
17511 (setq d (nth 1 start) m (car start) y (nth 2 start)
17512 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17513 m (+ m nm)
17514 ny (floor (/ m 12))
17515 y (+ y ny)
17516 m (- m (* ny 12)))
17517 (while (> m 12) (setq m (- m 12) y (1+ y)))
17518 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17519 (setq m2 (+ m dn) y2 y)
17520 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17521 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17522 (while (<= n2 cday)
17523 (setq n1 n2 m m2 y y2)
17524 (setq m2 (+ m dn) y2 y)
17525 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17526 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17527 ;; Make sure n1 is the earlier date
17528 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17529 (if show-all
17530 (cond
17531 ((eq prefer 'past) (if (= cday n2) n2 n1))
17532 ((eq prefer 'future) (if (= cday n1) n1 n2))
17533 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17534 (cond
17535 ((eq prefer 'past) (if (= cday n2) n2 n1))
17536 ((eq prefer 'future) (if (= cday n1) n1 n2))
17537 (t (if (= cday n1) n1 n2)))))))
17539 (defun org-date-to-gregorian (date)
17540 "Turn any specification of DATE into a Gregorian date for the calendar."
17541 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17542 ((and (listp date) (= (length date) 3)) date)
17543 ((stringp date)
17544 (setq date (org-parse-time-string date))
17545 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17546 ((listp date)
17547 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17549 (defun org-parse-time-string (s &optional nodefault)
17550 "Parse the standard Org-mode time string.
17551 This should be a lot faster than the normal `parse-time-string'.
17552 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17553 hour and minute fields will be nil if not given."
17554 (cond ((string-match org-ts-regexp0 s)
17555 (list 0
17556 (if (or (match-beginning 8) (not nodefault))
17557 (string-to-number (or (match-string 8 s) "0")))
17558 (if (or (match-beginning 7) (not nodefault))
17559 (string-to-number (or (match-string 7 s) "0")))
17560 (string-to-number (match-string 4 s))
17561 (string-to-number (match-string 3 s))
17562 (string-to-number (match-string 2 s))
17563 nil nil nil))
17564 ((string-match "^<[^>]+>$" s)
17565 (decode-time (seconds-to-time (org-matcher-time s))))
17566 (t (error "Not a standard Org-mode time string: %s" s))))
17568 (defun org-timestamp-up (&optional arg)
17569 "Increase the date item at the cursor by one.
17570 If the cursor is on the year, change the year. If it is on the month,
17571 the day or the time, change that.
17572 With prefix ARG, change by that many units."
17573 (interactive "p")
17574 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17576 (defun org-timestamp-down (&optional arg)
17577 "Decrease the date item at the cursor by one.
17578 If the cursor is on the year, change the year. If it is on the month,
17579 the day or the time, change that.
17580 With prefix ARG, change by that many units."
17581 (interactive "p")
17582 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17584 (defun org-timestamp-up-day (&optional arg)
17585 "Increase the date in the time stamp by one day.
17586 With prefix ARG, change that many days."
17587 (interactive "p")
17588 (if (and (not (org-at-timestamp-p t))
17589 (org-at-heading-p))
17590 (org-todo 'up)
17591 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17593 (defun org-timestamp-down-day (&optional arg)
17594 "Decrease the date in the time stamp by one day.
17595 With prefix ARG, change that many days."
17596 (interactive "p")
17597 (if (and (not (org-at-timestamp-p t))
17598 (org-at-heading-p))
17599 (org-todo 'down)
17600 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17602 (defun org-at-timestamp-p (&optional inactive-ok)
17603 "Determine if the cursor is in or at a timestamp."
17604 (interactive)
17605 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17606 (pos (point))
17607 (ans (or (looking-at tsr)
17608 (save-excursion
17609 (skip-chars-backward "^[<\n\r\t")
17610 (if (> (point) (point-min)) (backward-char 1))
17611 (and (looking-at tsr)
17612 (> (- (match-end 0) pos) -1))))))
17613 (and ans
17614 (boundp 'org-ts-what)
17615 (setq org-ts-what
17616 (cond
17617 ((= pos (match-beginning 0)) 'bracket)
17618 ;; Point is considered to be "on the bracket" whether
17619 ;; it's really on it or right after it.
17620 ((= pos (1- (match-end 0))) 'bracket)
17621 ((= pos (match-end 0)) 'after)
17622 ((org-pos-in-match-range pos 2) 'year)
17623 ((org-pos-in-match-range pos 3) 'month)
17624 ((org-pos-in-match-range pos 7) 'hour)
17625 ((org-pos-in-match-range pos 8) 'minute)
17626 ((or (org-pos-in-match-range pos 4)
17627 (org-pos-in-match-range pos 5)) 'day)
17628 ((and (> pos (or (match-end 8) (match-end 5)))
17629 (< pos (match-end 0)))
17630 (- pos (or (match-end 8) (match-end 5))))
17631 (t 'day))))
17632 ans))
17634 (defun org-toggle-timestamp-type ()
17635 "Toggle the type (<active> or [inactive]) of a time stamp."
17636 (interactive)
17637 (when (org-at-timestamp-p t)
17638 (let ((beg (match-beginning 0)) (end (match-end 0))
17639 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17640 (save-excursion
17641 (goto-char beg)
17642 (while (re-search-forward "[][<>]" end t)
17643 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17644 t t)))
17645 (message "Timestamp is now %sactive"
17646 (if (equal (char-after beg) ?<) "" "in")))))
17648 (defun org-at-clock-log-p nil
17649 "Is the cursor on the clock log line?"
17650 (save-excursion
17651 (move-beginning-of-line 1)
17652 (looking-at org-clock-line-re)))
17654 (defvar org-clock-history) ; defined in org-clock.el
17655 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17656 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17657 "Change the date in the time stamp at point.
17658 The date will be changed by N times WHAT. WHAT can be `day', `month',
17659 `year', `minute', `second'. If WHAT is not given, the cursor position
17660 in the timestamp determines what will be changed.
17661 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17662 (let ((origin (point)) origin-cat
17663 with-hm inactive
17664 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17665 org-ts-what
17666 extra rem
17667 ts time time0 fixnext clrgx)
17668 (if (not (org-at-timestamp-p t))
17669 (user-error "Not at a timestamp"))
17670 (if (and (not what) (eq org-ts-what 'bracket))
17671 (org-toggle-timestamp-type)
17672 ;; Point isn't on brackets. Remember the part of the time-stamp
17673 ;; the point was in. Indeed, size of time-stamps may change,
17674 ;; but point must be kept in the same category nonetheless.
17675 (setq origin-cat org-ts-what)
17676 (if (and (not what) (not (eq org-ts-what 'day))
17677 org-display-custom-times
17678 (get-text-property (point) 'display)
17679 (not (get-text-property (1- (point)) 'display)))
17680 (setq org-ts-what 'day))
17681 (setq org-ts-what (or what org-ts-what)
17682 inactive (= (char-after (match-beginning 0)) ?\[)
17683 ts (match-string 0))
17684 (replace-match "")
17685 (when (string-match
17686 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17688 (setq extra (match-string 1 ts))
17689 (if suppress-tmp-delay
17690 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17691 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17692 (setq with-hm t))
17693 (setq time0 (org-parse-time-string ts))
17694 (when (and updown
17695 (eq org-ts-what 'minute)
17696 (not current-prefix-arg))
17697 ;; This looks like s-up and s-down. Change by one rounding step.
17698 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17699 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17700 (setcar (cdr time0) (+ (nth 1 time0)
17701 (if (> n 0) (- rem) (- dm rem))))))
17702 (setq time
17703 (encode-time (or (car time0) 0)
17704 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17705 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17706 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17707 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17708 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17709 (nthcdr 6 time0)))
17710 (when (and (member org-ts-what '(hour minute))
17711 extra
17712 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17713 (setq extra (org-modify-ts-extra
17714 extra
17715 (if (eq org-ts-what 'hour) 2 5)
17716 n dm)))
17717 (when (integerp org-ts-what)
17718 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17719 (if (eq what 'calendar)
17720 (let ((cal-date (org-get-date-from-calendar)))
17721 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17722 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17723 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17724 (setcar time0 (or (car time0) 0))
17725 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17726 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17727 (setq time (apply 'encode-time time0))))
17728 ;; Insert the new time-stamp, and ensure point stays in the same
17729 ;; category as before (i.e. not after the last position in that
17730 ;; category).
17731 (let ((pos (point)))
17732 ;; Stay before inserted string. `save-excursion' is of no use.
17733 (setq org-last-changed-timestamp
17734 (org-insert-time-stamp time with-hm inactive nil nil extra))
17735 (goto-char pos))
17736 (save-match-data
17737 (looking-at org-ts-regexp3)
17738 (goto-char (cond
17739 ;; `day' category ends before `hour' if any, or at
17740 ;; the end of the day name.
17741 ((eq origin-cat 'day)
17742 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17743 ((eq origin-cat 'hour) (min (match-end 7) origin))
17744 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17745 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17746 ;; `year' and `month' have both fixed size: point
17747 ;; couldn't have moved into another part.
17748 (t origin))))
17749 ;; Update clock if on a CLOCK line.
17750 (org-clock-update-time-maybe)
17751 ;; Maybe adjust the closest clock in `org-clock-history'
17752 (when org-clock-adjust-closest
17753 (if (not (and (org-at-clock-log-p)
17754 (< 1 (length (delq nil (mapcar 'marker-position
17755 org-clock-history))))))
17756 (message "No clock to adjust")
17757 (cond ((save-excursion ; fix previous clock?
17758 (re-search-backward org-ts-regexp0 nil t)
17759 (org-looking-back (concat org-clock-string " \\[")))
17760 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17761 ((save-excursion ; fix next clock?
17762 (re-search-backward org-ts-regexp0 nil t)
17763 (looking-at (concat org-ts-regexp0 "\\] =>")))
17764 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17765 (save-window-excursion
17766 ;; Find closest clock to point, adjust the previous/next one in history
17767 (let* ((p (save-excursion (org-back-to-heading t)))
17768 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17769 (clfixnth
17770 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17771 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17772 (if (not clfixpos)
17773 (message "No clock to adjust")
17774 (save-excursion
17775 (org-goto-marker-or-bmk clfixpos)
17776 (org-show-subtree)
17777 (when (re-search-forward clrgx nil t)
17778 (goto-char (match-beginning 1))
17779 (let (org-clock-adjust-closest)
17780 (org-timestamp-change n org-ts-what updown))
17781 (message "Clock adjusted in %s for heading: %s"
17782 (file-name-nondirectory (buffer-file-name))
17783 (org-get-heading t t)))))))))
17784 ;; Try to recenter the calendar window, if any.
17785 (if (and org-calendar-follow-timestamp-change
17786 (get-buffer-window "*Calendar*" t)
17787 (memq org-ts-what '(day month year)))
17788 (org-recenter-calendar (time-to-days time))))))
17790 (defun org-modify-ts-extra (s pos n dm)
17791 "Change the different parts of the lead-time and repeat fields in timestamp."
17792 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17793 ng h m new rem)
17794 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17795 (cond
17796 ((or (org-pos-in-match-range pos 2)
17797 (org-pos-in-match-range pos 3))
17798 (setq m (string-to-number (match-string 3 s))
17799 h (string-to-number (match-string 2 s)))
17800 (if (org-pos-in-match-range pos 2)
17801 (setq h (+ h n))
17802 (setq n (* dm (org-no-warnings (signum n))))
17803 (when (not (= 0 (setq rem (% m dm))))
17804 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17805 (setq m (+ m n)))
17806 (if (< m 0) (setq m (+ m 60) h (1- h)))
17807 (if (> m 59) (setq m (- m 60) h (1+ h)))
17808 (setq h (min 24 (max 0 h)))
17809 (setq ng 1 new (format "-%02d:%02d" h m)))
17810 ((org-pos-in-match-range pos 6)
17811 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17812 ((org-pos-in-match-range pos 5)
17813 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17815 ((org-pos-in-match-range pos 9)
17816 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17817 ((org-pos-in-match-range pos 8)
17818 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17820 (when ng
17821 (setq s (concat
17822 (substring s 0 (match-beginning ng))
17824 (substring s (match-end ng))))))
17827 (defun org-recenter-calendar (date)
17828 "If the calendar is visible, recenter it to DATE."
17829 (let ((cwin (get-buffer-window "*Calendar*" t)))
17830 (when cwin
17831 (let ((calendar-move-hook nil))
17832 (with-selected-window cwin
17833 (calendar-goto-date (if (listp date) date
17834 (calendar-gregorian-from-absolute date))))))))
17836 (defun org-goto-calendar (&optional arg)
17837 "Go to the Emacs calendar at the current date.
17838 If there is a time stamp in the current line, go to that date.
17839 A prefix ARG can be used to force the current date."
17840 (interactive "P")
17841 (let ((tsr org-ts-regexp) diff
17842 (calendar-move-hook nil)
17843 (calendar-view-holidays-initially-flag nil)
17844 (calendar-view-diary-initially-flag nil))
17845 (if (or (org-at-timestamp-p)
17846 (save-excursion
17847 (beginning-of-line 1)
17848 (looking-at (concat ".*" tsr))))
17849 (let ((d1 (time-to-days (current-time)))
17850 (d2 (time-to-days
17851 (org-time-string-to-time (match-string 1)))))
17852 (setq diff (- d2 d1))))
17853 (calendar)
17854 (calendar-goto-today)
17855 (if (and diff (not arg)) (calendar-forward-day diff))))
17857 (defun org-get-date-from-calendar ()
17858 "Return a list (month day year) of date at point in calendar."
17859 (with-current-buffer "*Calendar*"
17860 (save-match-data
17861 (calendar-cursor-to-date))))
17863 (defun org-date-from-calendar ()
17864 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17865 If there is already a time stamp at the cursor position, update it."
17866 (interactive)
17867 (if (org-at-timestamp-p t)
17868 (org-timestamp-change 0 'calendar)
17869 (let ((cal-date (org-get-date-from-calendar)))
17870 (org-insert-time-stamp
17871 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17873 (defcustom org-effort-durations
17874 `(("h" . 60)
17875 ("d" . ,(* 60 8))
17876 ("w" . ,(* 60 8 5))
17877 ("m" . ,(* 60 8 5 4))
17878 ("y" . ,(* 60 8 5 40)))
17879 "Conversion factor to minutes for an effort modifier.
17881 Each entry has the form (MODIFIER . MINUTES).
17883 In an effort string, a number followed by MODIFIER is multiplied
17884 by the specified number of MINUTES to obtain an effort in
17885 minutes.
17887 For example, if the value of this variable is ((\"hours\" . 60)), then an
17888 effort string \"2hours\" is equivalent to 120 minutes."
17889 :group 'org-agenda
17890 :version "24.1"
17891 :type '(alist :key-type (string :tag "Modifier")
17892 :value-type (number :tag "Minutes")))
17894 (defun org-minutes-to-clocksum-string (m)
17895 "Format number of minutes as a clocksum string.
17896 The format is determined by `org-time-clocksum-format',
17897 `org-time-clocksum-use-fractional' and
17898 `org-time-clocksum-fractional-format' and
17899 `org-time-clocksum-use-effort-durations'."
17900 (let ((clocksum "")
17901 (m (round m)) ; Don't allow fractions of minutes
17902 h d w mo y fmt n)
17903 (setq h (if org-time-clocksum-use-effort-durations
17904 (cdr (assoc "h" org-effort-durations)) 60)
17905 d (if org-time-clocksum-use-effort-durations
17906 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17907 w (if org-time-clocksum-use-effort-durations
17908 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17909 mo (if org-time-clocksum-use-effort-durations
17910 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17911 y (if org-time-clocksum-use-effort-durations
17912 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17913 ;; fractional format
17914 (if org-time-clocksum-use-fractional
17915 (cond
17916 ;; single format string
17917 ((stringp org-time-clocksum-fractional-format)
17918 (format org-time-clocksum-fractional-format (/ m (float h))))
17919 ;; choice of fractional formats for different time units
17920 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17921 (> (/ (truncate m) (* y d h)) 0))
17922 (format fmt (/ m (* y d (float h)))))
17923 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17924 (> (/ (truncate m) (* mo d h)) 0))
17925 (format fmt (/ m (* mo d (float h)))))
17926 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17927 (> (/ (truncate m) (* w d h)) 0))
17928 (format fmt (/ m (* w d (float h)))))
17929 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17930 (> (/ (truncate m) (* d h)) 0))
17931 (format fmt (/ m (* d (float h)))))
17932 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17933 (> (/ (truncate m) h) 0))
17934 (format fmt (/ m (float h))))
17935 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17936 (format fmt m))
17937 ;; fall back to smallest time unit with a format
17938 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17939 (format fmt (/ m (float h))))
17940 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17941 (format fmt (/ m (* d (float h)))))
17942 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17943 (format fmt (/ m (* w d (float h)))))
17944 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17945 (format fmt (/ m (* mo d (float h)))))
17946 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17947 (format fmt (/ m (* y d (float h))))))
17948 ;; standard (non-fractional) format, with single format string
17949 (if (stringp org-time-clocksum-format)
17950 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17951 ;; separate formats components
17952 (and (setq fmt (plist-get org-time-clocksum-format :years))
17953 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17954 (plist-get org-time-clocksum-format :require-years))
17955 (setq clocksum (concat clocksum (format fmt n))
17956 m (- m (* n y d h))))
17957 (and (setq fmt (plist-get org-time-clocksum-format :months))
17958 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17959 (plist-get org-time-clocksum-format :require-months))
17960 (setq clocksum (concat clocksum (format fmt n))
17961 m (- m (* n mo d h))))
17962 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17963 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17964 (plist-get org-time-clocksum-format :require-weeks))
17965 (setq clocksum (concat clocksum (format fmt n))
17966 m (- m (* n w d h))))
17967 (and (setq fmt (plist-get org-time-clocksum-format :days))
17968 (or (> (setq n (/ (truncate m) (* d h))) 0)
17969 (plist-get org-time-clocksum-format :require-days))
17970 (setq clocksum (concat clocksum (format fmt n))
17971 m (- m (* n d h))))
17972 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17973 (or (> (setq n (/ (truncate m) h)) 0)
17974 (plist-get org-time-clocksum-format :require-hours))
17975 (setq clocksum (concat clocksum (format fmt n))
17976 m (- m (* n h))))
17977 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17978 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17979 (setq clocksum (concat clocksum (format fmt m))))
17980 ;; return formatted time duration
17981 clocksum))))
17983 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17984 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17985 "Org mode version 8.0")
17987 (defun org-hours-to-clocksum-string (n)
17988 (org-minutes-to-clocksum-string (* n 60)))
17990 (defun org-hh:mm-string-to-minutes (s)
17991 "Convert a string H:MM to a number of minutes.
17992 If the string is just a number, interpret it as minutes.
17993 In fact, the first hh:mm or number in the string will be taken,
17994 there can be extra stuff in the string.
17995 If no number is found, the return value is 0."
17996 (cond
17997 ((integerp s) s)
17998 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17999 (+ (* (string-to-number (match-string 1 s)) 60)
18000 (string-to-number (match-string 2 s))))
18001 ((string-match "\\([0-9]+\\)" s)
18002 (string-to-number (match-string 1 s)))
18003 (t 0)))
18005 (defcustom org-image-actual-width t
18006 "Should we use the actual width of images when inlining them?
18008 When set to `t', always use the image width.
18010 When set to a number, use imagemagick (when available) to set
18011 the image's width to this value.
18013 When set to a number in a list, try to get the width from any
18014 #+ATTR.* keyword if it matches a width specification like
18016 #+ATTR_HTML: :width 300px
18018 and fall back on that number if none is found.
18020 When set to nil, try to get the width from an #+ATTR.* keyword
18021 and fall back on the original width if none is found.
18023 This requires Emacs >= 24.1, build with imagemagick support."
18024 :group 'org-appearance
18025 :version "24.4"
18026 :package-version '(Org . "8.0")
18027 :type '(choice
18028 (const :tag "Use the image width" t)
18029 (integer :tag "Use a number of pixels")
18030 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18031 (const :tag "Use #+ATTR* or don't resize" nil)))
18033 (defcustom org-agenda-inhibit-startup nil
18034 "Inhibit startup when preparing agenda buffers.
18035 When this variable is `t', the initialization of the Org agenda
18036 buffers is inhibited: e.g. the visibility state is not set, the
18037 tables are not re-aligned, etc."
18038 :type 'boolean
18039 :version "24.3"
18040 :group 'org-agenda)
18042 (define-obsolete-variable-alias
18043 'org-agenda-ignore-drawer-properties
18044 'org-agenda-ignore-properties "25.1")
18046 (defcustom org-agenda-ignore-properties nil
18047 "Avoid updating text properties when building the agenda.
18048 Properties are used to prepare buffers for effort estimates,
18049 appointments, statistics and subtree-local categories.
18050 If you don't use these in the agenda, you can add them to this
18051 list and agenda building will be a bit faster.
18052 The value is a list, with zero or more of the symbols `effort', `appt',
18053 `stats' or `category'."
18054 :type '(set :greedy t
18055 (const effort)
18056 (const appt)
18057 (const stats)
18058 (const category))
18059 :version "25.1"
18060 :package-version '(Org . "8.3")
18061 :group 'org-agenda)
18063 (defun org-duration-string-to-minutes (s &optional output-to-string)
18064 "Convert a duration string S to minutes.
18066 A bare number is interpreted as minutes, modifiers can be set by
18067 customizing `org-effort-durations' (which see).
18069 Entries containing a colon are interpreted as H:MM by
18070 `org-hh:mm-string-to-minutes'."
18071 (let ((result 0)
18072 (re (concat "\\([0-9.]+\\) *\\("
18073 (regexp-opt (mapcar 'car org-effort-durations))
18074 "\\)")))
18075 (while (string-match re s)
18076 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18077 (string-to-number (match-string 1 s))))
18078 (setq s (replace-match "" nil t s)))
18079 (setq result (floor result))
18080 (incf result (org-hh:mm-string-to-minutes s))
18081 (if output-to-string (number-to-string result) result)))
18083 ;;;; Files
18085 (defun org-save-all-org-buffers ()
18086 "Save all Org-mode buffers without user confirmation."
18087 (interactive)
18088 (message "Saving all Org-mode buffers...")
18089 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18090 (when (featurep 'org-id) (org-id-locations-save))
18091 (message "Saving all Org-mode buffers... done"))
18093 (defun org-revert-all-org-buffers ()
18094 "Revert all Org-mode buffers.
18095 Prompt for confirmation when there are unsaved changes.
18096 Be sure you know what you are doing before letting this function
18097 overwrite your changes.
18099 This function is useful in a setup where one tracks org files
18100 with a version control system, to revert on one machine after pulling
18101 changes from another. I believe the procedure must be like this:
18103 1. M-x org-save-all-org-buffers
18104 2. Pull changes from the other machine, resolve conflicts
18105 3. M-x org-revert-all-org-buffers"
18106 (interactive)
18107 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18108 (user-error "Abort"))
18109 (save-excursion
18110 (save-window-excursion
18111 (mapc
18112 (lambda (b)
18113 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18114 (with-current-buffer b buffer-file-name))
18115 (org-pop-to-buffer-same-window b)
18116 (revert-buffer t 'no-confirm)))
18117 (buffer-list))
18118 (when (and (featurep 'org-id) org-id-track-globally)
18119 (org-id-locations-load)))))
18121 ;;;; Agenda files
18123 ;;;###autoload
18124 (defun org-switchb (&optional arg)
18125 "Switch between Org buffers.
18126 With one prefix argument, restrict available buffers to files.
18127 With two prefix arguments, restrict available buffers to agenda files.
18129 Defaults to `iswitchb' for buffer name completion.
18130 Set `org-completion-use-ido' to make it use ido instead."
18131 (interactive "P")
18132 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18133 ((equal arg '(16)) (org-buffer-list 'agenda))
18134 (t (org-buffer-list))))
18135 (org-completion-use-iswitchb org-completion-use-iswitchb)
18136 (org-completion-use-ido org-completion-use-ido))
18137 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18138 (setq org-completion-use-iswitchb t))
18139 (org-pop-to-buffer-same-window
18140 (org-icompleting-read "Org buffer: "
18141 (mapcar 'list (mapcar 'buffer-name blist))
18142 nil t))))
18144 ;;; Define some older names previously used for this functionality
18145 ;;;###autoload
18146 (defalias 'org-ido-switchb 'org-switchb)
18147 ;;;###autoload
18148 (defalias 'org-iswitchb 'org-switchb)
18150 (defun org-buffer-list (&optional predicate exclude-tmp)
18151 "Return a list of Org buffers.
18152 PREDICATE can be `export', `files' or `agenda'.
18154 export restrict the list to Export buffers.
18155 files restrict the list to buffers visiting Org files.
18156 agenda restrict the list to buffers visiting agenda files.
18158 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18159 (let* ((bfn nil)
18160 (agenda-files (and (eq predicate 'agenda)
18161 (mapcar 'file-truename (org-agenda-files t))))
18162 (filter
18163 (cond
18164 ((eq predicate 'files)
18165 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18166 ((eq predicate 'export)
18167 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18168 ((eq predicate 'agenda)
18169 (lambda (b)
18170 (with-current-buffer b
18171 (and (derived-mode-p 'org-mode)
18172 (setq bfn (buffer-file-name b))
18173 (member (file-truename bfn) agenda-files)))))
18174 (t (lambda (b) (with-current-buffer b
18175 (or (derived-mode-p 'org-mode)
18176 (string-match "\*Org .*Export"
18177 (buffer-name b)))))))))
18178 (delq nil
18179 (mapcar
18180 (lambda(b)
18181 (if (and (funcall filter b)
18182 (or (not exclude-tmp)
18183 (not (string-match "tmp" (buffer-name b)))))
18185 nil))
18186 (buffer-list)))))
18188 (defun org-agenda-files (&optional unrestricted archives)
18189 "Get the list of agenda files.
18190 Optional UNRESTRICTED means return the full list even if a restriction
18191 is currently in place.
18192 When ARCHIVES is t, include all archive files that are really being
18193 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18194 `org-agenda-archives-mode' is t."
18195 (let ((files
18196 (cond
18197 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18198 ((stringp org-agenda-files) (org-read-agenda-file-list))
18199 ((listp org-agenda-files) org-agenda-files)
18200 (t (error "Invalid value of `org-agenda-files'")))))
18201 (setq files (apply 'append
18202 (mapcar (lambda (f)
18203 (if (file-directory-p f)
18204 (directory-files
18205 f t org-agenda-file-regexp)
18206 (list f)))
18207 files)))
18208 (when org-agenda-skip-unavailable-files
18209 (setq files (delq nil
18210 (mapcar (function
18211 (lambda (file)
18212 (and (file-readable-p file) file)))
18213 files))))
18214 (when (or (eq archives t)
18215 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18216 (setq files (org-add-archive-files files)))
18217 files))
18219 (defun org-agenda-file-p (&optional file)
18220 "Return non-nil, if FILE is an agenda file.
18221 If FILE is omitted, use the file associated with the current
18222 buffer."
18223 (let ((fname (or file (buffer-file-name))))
18224 (and fname
18225 (member (file-truename fname)
18226 (mapcar #'file-truename (org-agenda-files t))))))
18228 (defun org-edit-agenda-file-list ()
18229 "Edit the list of agenda files.
18230 Depending on setup, this either uses customize to edit the variable
18231 `org-agenda-files', or it visits the file that is holding the list. In the
18232 latter case, the buffer is set up in a way that saving it automatically kills
18233 the buffer and restores the previous window configuration."
18234 (interactive)
18235 (if (stringp org-agenda-files)
18236 (let ((cw (current-window-configuration)))
18237 (find-file org-agenda-files)
18238 (org-set-local 'org-window-configuration cw)
18239 (org-add-hook 'after-save-hook
18240 (lambda ()
18241 (set-window-configuration
18242 (prog1 org-window-configuration
18243 (kill-buffer (current-buffer))))
18244 (org-install-agenda-files-menu)
18245 (message "New agenda file list installed"))
18246 nil 'local)
18247 (message "%s" (substitute-command-keys
18248 "Edit list and finish with \\[save-buffer]")))
18249 (customize-variable 'org-agenda-files)))
18251 (defun org-store-new-agenda-file-list (list)
18252 "Set new value for the agenda file list and save it correctly."
18253 (if (stringp org-agenda-files)
18254 (let ((fe (org-read-agenda-file-list t)) b u)
18255 (while (setq b (find-buffer-visiting org-agenda-files))
18256 (kill-buffer b))
18257 (with-temp-file org-agenda-files
18258 (insert
18259 (mapconcat
18260 (lambda (f) ;; Keep un-expanded entries.
18261 (if (setq u (assoc f fe))
18262 (cdr u)
18264 list "\n")
18265 "\n")))
18266 (let ((org-mode-hook nil) (org-inhibit-startup t)
18267 (org-insert-mode-line-in-empty-file nil))
18268 (setq org-agenda-files list)
18269 (customize-save-variable 'org-agenda-files org-agenda-files))))
18271 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18272 "Read the list of agenda files from a file.
18273 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18274 filenames, used by `org-store-new-agenda-file-list' to write back
18275 un-expanded file names."
18276 (when (file-directory-p org-agenda-files)
18277 (error "`org-agenda-files' cannot be a single directory"))
18278 (when (stringp org-agenda-files)
18279 (with-temp-buffer
18280 (insert-file-contents org-agenda-files)
18281 (mapcar
18282 (lambda (f)
18283 (let ((e (expand-file-name (substitute-in-file-name f)
18284 org-directory)))
18285 (if pair-with-expansion
18286 (cons e f)
18287 e)))
18288 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18290 ;;;###autoload
18291 (defun org-cycle-agenda-files ()
18292 "Cycle through the files in `org-agenda-files'.
18293 If the current buffer visits an agenda file, find the next one in the list.
18294 If the current buffer does not, find the first agenda file."
18295 (interactive)
18296 (let* ((fs (org-agenda-files t))
18297 (files (append fs (list (car fs))))
18298 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18299 file)
18300 (unless files (user-error "No agenda files"))
18301 (catch 'exit
18302 (while (setq file (pop files))
18303 (if (equal (file-truename file) tcf)
18304 (when (car files)
18305 (find-file (car files))
18306 (throw 'exit t))))
18307 (find-file (car fs)))
18308 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18310 (defun org-agenda-file-to-front (&optional to-end)
18311 "Move/add the current file to the top of the agenda file list.
18312 If the file is not present in the list, it is added to the front. If it is
18313 present, it is moved there. With optional argument TO-END, add/move to the
18314 end of the list."
18315 (interactive "P")
18316 (let ((org-agenda-skip-unavailable-files nil)
18317 (file-alist (mapcar (lambda (x)
18318 (cons (file-truename x) x))
18319 (org-agenda-files t)))
18320 (ctf (file-truename
18321 (or buffer-file-name
18322 (user-error "Please save the current buffer to a file"))))
18323 x had)
18324 (setq x (assoc ctf file-alist) had x)
18326 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18327 (if to-end
18328 (setq file-alist (append (delq x file-alist) (list x)))
18329 (setq file-alist (cons x (delq x file-alist))))
18330 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18331 (org-install-agenda-files-menu)
18332 (message "File %s to %s of agenda file list"
18333 (if had "moved" "added") (if to-end "end" "front"))))
18335 (defun org-remove-file (&optional file)
18336 "Remove current file from the list of files in variable `org-agenda-files'.
18337 These are the files which are being checked for agenda entries.
18338 Optional argument FILE means use this file instead of the current."
18339 (interactive)
18340 (let* ((org-agenda-skip-unavailable-files nil)
18341 (file (or file buffer-file-name
18342 (user-error "Current buffer does not visit a file")))
18343 (true-file (file-truename file))
18344 (afile (abbreviate-file-name file))
18345 (files (delq nil (mapcar
18346 (lambda (x)
18347 (if (equal true-file
18348 (file-truename x))
18349 nil x))
18350 (org-agenda-files t)))))
18351 (if (not (= (length files) (length (org-agenda-files t))))
18352 (progn
18353 (org-store-new-agenda-file-list files)
18354 (org-install-agenda-files-menu)
18355 (message "Removed file: %s" afile))
18356 (message "File was not in list: %s (not removed)" afile))))
18358 (defun org-file-menu-entry (file)
18359 (vector file (list 'find-file file) t))
18361 (defun org-check-agenda-file (file)
18362 "Make sure FILE exists. If not, ask user what to do."
18363 (when (not (file-exists-p file))
18364 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18365 (abbreviate-file-name file))
18366 (let ((r (downcase (read-char-exclusive))))
18367 (cond
18368 ((equal r ?r)
18369 (org-remove-file file)
18370 (throw 'nextfile t))
18371 (t (user-error "Abort"))))))
18373 (defun org-get-agenda-file-buffer (file)
18374 "Get an agenda buffer visiting FILE.
18375 If the buffer needs to be created, add it to the list of buffers
18376 which might be released later."
18377 (let ((buf (org-find-base-buffer-visiting file)))
18378 (if buf
18379 buf ; just return it
18380 ;; Make a new buffer and remember it
18381 (setq buf (find-file-noselect file))
18382 (if buf (push buf org-agenda-new-buffers))
18383 buf)))
18385 (defun org-release-buffers (blist)
18386 "Release all buffers in list, asking the user for confirmation when needed.
18387 When a buffer is unmodified, it is just killed. When modified, it is saved
18388 \(if the user agrees) and then killed."
18389 (let (buf file)
18390 (while (setq buf (pop blist))
18391 (setq file (buffer-file-name buf))
18392 (when (and (buffer-modified-p buf)
18393 file
18394 (y-or-n-p (format "Save file %s? " file)))
18395 (with-current-buffer buf (save-buffer)))
18396 (kill-buffer buf))))
18398 (defun org-agenda-prepare-buffers (files)
18399 "Create buffers for all agenda files, protect archived trees and comments."
18400 (interactive)
18401 (let ((pa '(:org-archived t))
18402 (pc '(:org-comment t))
18403 (pall '(:org-archived t :org-comment t))
18404 (inhibit-read-only t)
18405 (org-inhibit-startup org-agenda-inhibit-startup)
18406 (rea (concat ":" org-archive-tag ":"))
18407 file re pos)
18408 (setq org-tag-alist-for-agenda nil
18409 org-tag-groups-alist-for-agenda nil)
18410 (save-excursion
18411 (save-restriction
18412 (while (setq file (pop files))
18413 (catch 'nextfile
18414 (if (bufferp file)
18415 (set-buffer file)
18416 (org-check-agenda-file file)
18417 (set-buffer (org-get-agenda-file-buffer file)))
18418 (widen)
18419 (org-set-regexps-and-options-for-tags)
18420 (setq pos (point))
18421 (goto-char (point-min))
18422 (let ((case-fold-search t))
18423 (when (search-forward "#+setupfile" nil t)
18424 ;; Don't set all regexps and options systematically as
18425 ;; this is only run for setting agenda tags from setup
18426 ;; file
18427 (org-set-regexps-and-options)))
18428 (or (memq 'category org-agenda-ignore-properties)
18429 (org-refresh-category-properties))
18430 (or (memq 'stats org-agenda-ignore-properties)
18431 (org-refresh-stats-properties))
18432 (or (memq 'effort org-agenda-ignore-properties)
18433 (org-refresh-effort-properties))
18434 (or (memq 'appt org-agenda-ignore-properties)
18435 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18436 (setq org-todo-keywords-for-agenda
18437 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18438 (setq org-done-keywords-for-agenda
18439 (append org-done-keywords-for-agenda org-done-keywords))
18440 (setq org-todo-keyword-alist-for-agenda
18441 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18442 (setq org-tag-alist-for-agenda
18443 (org-uniquify
18444 (append org-tag-alist-for-agenda
18445 org-tag-alist
18446 org-tag-persistent-alist)))
18447 (if org-group-tags
18448 (setq org-tag-groups-alist-for-agenda
18449 (org-uniquify-alist
18450 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18451 (org-with-silent-modifications
18452 (save-excursion
18453 (remove-text-properties (point-min) (point-max) pall)
18454 (when org-agenda-skip-archived-trees
18455 (goto-char (point-min))
18456 (while (re-search-forward rea nil t)
18457 (if (org-at-heading-p t)
18458 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18459 (goto-char (point-min))
18460 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18461 (while (re-search-forward re nil t)
18462 (when (save-match-data (org-in-commented-heading-p t))
18463 (add-text-properties
18464 (match-beginning 0) (org-end-of-subtree t) pc)))))
18465 (goto-char pos)))))
18466 (setq org-todo-keywords-for-agenda
18467 (org-uniquify org-todo-keywords-for-agenda))
18468 (setq org-todo-keyword-alist-for-agenda
18469 (org-uniquify org-todo-keyword-alist-for-agenda))))
18472 ;;;; CDLaTeX minor mode
18474 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18475 "Keymap for the minor `org-cdlatex-mode'.")
18477 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18478 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18479 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18480 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18481 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18483 (defvar org-cdlatex-texmathp-advice-is-done nil
18484 "Flag remembering if we have applied the advice to texmathp already.")
18486 (define-minor-mode org-cdlatex-mode
18487 "Toggle the minor `org-cdlatex-mode'.
18488 This mode supports entering LaTeX environment and math in LaTeX fragments
18489 in Org-mode.
18490 \\{org-cdlatex-mode-map}"
18491 nil " OCDL" nil
18492 (when org-cdlatex-mode
18493 (require 'cdlatex)
18494 (run-hooks 'cdlatex-mode-hook)
18495 (cdlatex-compute-tables))
18496 (unless org-cdlatex-texmathp-advice-is-done
18497 (setq org-cdlatex-texmathp-advice-is-done t)
18498 (defadvice texmathp (around org-math-always-on activate)
18499 "Always return t in org-mode buffers.
18500 This is because we want to insert math symbols without dollars even outside
18501 the LaTeX math segments. If Orgmode thinks that point is actually inside
18502 an embedded LaTeX fragment, let texmathp do its job.
18503 \\[org-cdlatex-mode-map]"
18504 (interactive)
18505 (let (p)
18506 (cond
18507 ((not (derived-mode-p 'org-mode)) ad-do-it)
18508 ((eq this-command 'cdlatex-math-symbol)
18509 (setq ad-return-value t
18510 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18512 (let ((p (org-inside-LaTeX-fragment-p)))
18513 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18514 (setq ad-return-value t
18515 texmathp-why '("Org-mode embedded math" . 0))
18516 (if p ad-do-it)))))))))
18518 (defun turn-on-org-cdlatex ()
18519 "Unconditionally turn on `org-cdlatex-mode'."
18520 (org-cdlatex-mode 1))
18522 (defun org-try-cdlatex-tab ()
18523 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18524 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18525 - inside a LaTeX fragment, or
18526 - after the first word in a line, where an abbreviation expansion could
18527 insert a LaTeX environment."
18528 (when org-cdlatex-mode
18529 (cond
18530 ;; Before any word on the line: No expansion possible.
18531 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18532 ;; Just after first word on the line: Expand it. Make sure it
18533 ;; cannot happen on headlines, though.
18534 ((save-excursion
18535 (skip-chars-backward "a-zA-Z0-9*")
18536 (skip-chars-backward " \t")
18537 (and (bolp) (not (org-at-heading-p))))
18538 (cdlatex-tab) t)
18539 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18541 (defun org-cdlatex-underscore-caret (&optional arg)
18542 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18543 Revert to the normal definition outside of these fragments."
18544 (interactive "P")
18545 (if (org-inside-LaTeX-fragment-p)
18546 (call-interactively 'cdlatex-sub-superscript)
18547 (let (org-cdlatex-mode)
18548 (call-interactively (key-binding (vector last-input-event))))))
18550 (defun org-cdlatex-math-modify (&optional arg)
18551 "Execute `cdlatex-math-modify' in LaTeX fragments.
18552 Revert to the normal definition outside of these fragments."
18553 (interactive "P")
18554 (if (org-inside-LaTeX-fragment-p)
18555 (call-interactively 'cdlatex-math-modify)
18556 (let (org-cdlatex-mode)
18557 (call-interactively (key-binding (vector last-input-event))))))
18559 (defun org-cdlatex-environment-indent (&optional environment item)
18560 "Execute `cdlatex-environment' and indent the inserted environment."
18561 (interactive)
18562 (cdlatex-environment environment item)
18563 (let ((element (org-element-at-point)))
18564 (org-indent-region (org-element-property :begin element)
18565 (org-element-property :end element))))
18568 ;;;; LaTeX fragments
18570 (defun org-inside-LaTeX-fragment-p ()
18571 "Test if point is inside a LaTeX fragment.
18572 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18573 sequence appearing also before point.
18574 Even though the matchers for math are configurable, this function assumes
18575 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18576 delimiters are skipped when they have been removed by customization.
18577 The return value is nil, or a cons cell with the delimiter and the
18578 position of this delimiter.
18580 This function does a reasonably good job, but can locally be fooled by
18581 for example currency specifications. For example it will assume being in
18582 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18583 fragments that are properly closed, but during editing, we have to live
18584 with the uncertainty caused by missing closing delimiters. This function
18585 looks only before point, not after."
18586 (catch 'exit
18587 (let ((pos (point))
18588 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18589 (lim (progn
18590 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18591 (point)))
18592 dd-on str (start 0) m re)
18593 (goto-char pos)
18594 (when dodollar
18595 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18596 re (nth 1 (assoc "$" org-latex-regexps)))
18597 (while (string-match re str start)
18598 (cond
18599 ((= (match-end 0) (length str))
18600 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18601 ((= (match-end 0) (- (length str) 5))
18602 (throw 'exit nil))
18603 (t (setq start (match-end 0))))))
18604 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18605 (goto-char pos)
18606 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18607 (and (match-beginning 2) (throw 'exit nil))
18608 ;; count $$
18609 (while (re-search-backward "\\$\\$" lim t)
18610 (setq dd-on (not dd-on)))
18611 (goto-char pos)
18612 (if dd-on (cons "$$" m))))))
18614 (defun org-inside-latex-macro-p ()
18615 "Is point inside a LaTeX macro or its arguments?"
18616 (save-match-data
18617 (org-in-regexp
18618 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18620 (defvar org-latex-fragment-image-overlays nil
18621 "List of overlays carrying the images of latex fragments.")
18622 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18624 (defun org-remove-latex-fragment-image-overlays ()
18625 "Remove all overlays with LaTeX fragment images in current buffer."
18626 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18627 (setq org-latex-fragment-image-overlays nil))
18629 (define-obsolete-function-alias
18630 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18631 (defun org-toggle-latex-fragment (&optional subtree)
18632 "Preview the LaTeX fragment at point, or all locally or globally.
18633 If the cursor is in a LaTeX fragment, create the image and overlay
18634 it over the source code. If there is no fragment at point, display
18635 all fragments in the current text, from one headline to the next. With
18636 prefix SUBTREE, display all fragments in the current subtree. With a
18637 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18638 the cursor is before the first headline,
18639 display all fragments in the buffer.
18640 The images can be removed again with \\[org-toggle-latex-fragment]."
18641 (interactive "P")
18642 (unless buffer-file-name
18643 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18644 (if org-latex-fragment-image-overlays
18645 (progn (org-remove-latex-fragment-image-overlays)
18646 (message "LaTeX fragments images removed"))
18647 (when (display-graphic-p)
18648 (org-remove-latex-fragment-image-overlays)
18649 (save-excursion
18650 (save-restriction
18651 (let (beg end at msg)
18652 (cond
18653 ((or (equal subtree '(16))
18654 (not (save-excursion
18655 (re-search-backward org-outline-regexp-bol nil t))))
18656 (setq beg (point-min) end (point-max)
18657 msg "Creating images for buffer...%s"))
18658 ((equal subtree '(4))
18659 (org-back-to-heading)
18660 (setq beg (point) end (org-end-of-subtree t)
18661 msg "Creating images for subtree...%s"))
18663 (if (setq at (org-inside-LaTeX-fragment-p))
18664 (goto-char (max (point-min) (- (cdr at) 2)))
18665 (org-back-to-heading))
18666 (setq beg (point) end (progn (outline-next-heading) (point))
18667 msg (if at "Creating image...%s"
18668 "Creating images for entry...%s"))))
18669 (message msg "")
18670 (narrow-to-region beg end)
18671 (goto-char beg)
18672 (org-format-latex
18673 (concat org-latex-preview-ltxpng-directory
18674 (file-name-sans-extension
18675 (file-name-nondirectory buffer-file-name)))
18676 default-directory 'overlays msg at 'forbuffer
18677 org-latex-create-formula-image-program)
18678 (message msg "done. Use `C-c C-x C-l' to remove images.")))))))
18680 (defun org-format-latex (prefix &optional dir overlays msg at
18681 forbuffer processing-type)
18682 "Replace LaTeX fragments with links to an image, and produce images.
18683 Some of the options can be changed using the variable
18684 `org-format-latex-options'."
18685 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18686 (let* ((prefixnodir (file-name-nondirectory prefix))
18687 (absprefix (expand-file-name prefix dir))
18688 (todir (file-name-directory absprefix))
18689 (opt org-format-latex-options)
18690 (optnew org-format-latex-options)
18691 (matchers (plist-get opt :matchers))
18692 (re-list org-latex-regexps)
18693 (cnt 0) txt hash link beg end re e checkdir
18694 string
18695 m n block-type block linkfile movefile ov)
18696 ;; Check the different regular expressions
18697 (while (setq e (pop re-list))
18698 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18699 block (if block-type "\n\n" ""))
18700 (when (member m matchers)
18701 (goto-char (point-min))
18702 (while (re-search-forward re nil t)
18703 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18704 (or (not overlays)
18705 (not (eq (get-char-property (match-beginning n)
18706 'org-overlay-type)
18707 'org-latex-overlay))))
18708 (cond
18709 ((eq processing-type 'verbatim))
18710 ((eq processing-type 'mathjax)
18711 ;; Prepare for MathJax processing.
18712 (setq string (match-string n))
18713 (when (member m '("$" "$1"))
18714 (save-excursion
18715 (delete-region (match-beginning n) (match-end n))
18716 (goto-char (match-beginning n))
18717 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18718 ((or (eq processing-type 'dvipng)
18719 (eq processing-type 'imagemagick))
18720 ;; Process to an image.
18721 (setq txt (match-string n)
18722 beg (match-beginning n) end (match-end n)
18723 cnt (1+ cnt))
18724 (let ((face (face-at-point))
18725 (fg (plist-get opt :foreground))
18726 (bg (plist-get opt :background))
18727 ;; Ensure full list is printed.
18728 print-length print-level)
18729 (when forbuffer
18730 ;; Get the colors from the face at point.
18731 (goto-char beg)
18732 (when (eq fg 'auto)
18733 (setq fg (face-attribute face :foreground nil 'default)))
18734 (when (eq bg 'auto)
18735 (setq bg (face-attribute face :background nil 'default)))
18736 (setq optnew (copy-sequence opt))
18737 (plist-put optnew :foreground fg)
18738 (plist-put optnew :background bg))
18739 (setq hash (sha1 (prin1-to-string
18740 (list org-format-latex-header
18741 org-latex-default-packages-alist
18742 org-latex-packages-alist
18743 org-format-latex-options
18744 forbuffer txt fg bg)))
18745 linkfile (format "%s_%s.png" prefix hash)
18746 movefile (format "%s_%s.png" absprefix hash)))
18747 (setq link (concat block "[[file:" linkfile "]]" block))
18748 (if msg (message msg cnt))
18749 (goto-char beg)
18750 (unless checkdir ; Ensure the directory exists.
18751 (setq checkdir t)
18752 (or (file-directory-p todir) (make-directory todir t)))
18753 (unless (file-exists-p movefile)
18754 (org-create-formula-image
18755 txt movefile optnew forbuffer processing-type))
18756 (if overlays
18757 (progn
18758 (mapc (lambda (o)
18759 (if (eq (overlay-get o 'org-overlay-type)
18760 'org-latex-overlay)
18761 (delete-overlay o)))
18762 (overlays-in beg end))
18763 (setq ov (make-overlay beg end))
18764 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18765 (if (featurep 'xemacs)
18766 (progn
18767 (overlay-put ov 'invisible t)
18768 (overlay-put
18769 ov 'end-glyph
18770 (make-glyph (vector 'png :file movefile))))
18771 (overlay-put
18772 ov 'display
18773 (list 'image :type 'png :file movefile :ascent 'center)))
18774 (push ov org-latex-fragment-image-overlays)
18775 (goto-char end))
18776 (delete-region beg end)
18777 (insert (org-add-props link
18778 (list 'org-latex-src
18779 (replace-regexp-in-string
18780 "\"" "" txt)
18781 'org-latex-src-embed-type
18782 (if block-type 'paragraph 'character))))))
18783 ((eq processing-type 'mathml)
18784 ;; Process to MathML
18785 (unless (save-match-data (org-format-latex-mathml-available-p))
18786 (user-error "LaTeX to MathML converter not configured"))
18787 (setq txt (match-string n)
18788 beg (match-beginning n) end (match-end n)
18789 cnt (1+ cnt))
18790 (if msg (message msg cnt))
18791 (goto-char beg)
18792 (delete-region beg end)
18793 (insert (org-format-latex-as-mathml
18794 txt block-type prefix dir)))
18796 (error "Unknown conversion type %s for LaTeX fragments"
18797 processing-type)))))))))
18799 (defun org-create-math-formula (latex-frag &optional mathml-file)
18800 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18801 Use `org-latex-to-mathml-convert-command'. If the conversion is
18802 sucessful, return the portion between \"<math...> </math>\"
18803 elements otherwise return nil. When MATHML-FILE is specified,
18804 write the results in to that file. When invoked as an
18805 interactive command, prompt for LATEX-FRAG, with initial value
18806 set to the current active region and echo the results for user
18807 inspection."
18808 (interactive (list (let ((frag (when (org-region-active-p)
18809 (buffer-substring-no-properties
18810 (region-beginning) (region-end)))))
18811 (read-string "LaTeX Fragment: " frag nil frag))))
18812 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18813 (let* ((tmp-in-file (file-relative-name
18814 (make-temp-name (expand-file-name "ltxmathml-in"))))
18815 (ignore (write-region latex-frag nil tmp-in-file))
18816 (tmp-out-file (file-relative-name
18817 (make-temp-name (expand-file-name "ltxmathml-out"))))
18818 (cmd (format-spec
18819 org-latex-to-mathml-convert-command
18820 `((?j . ,(shell-quote-argument
18821 (expand-file-name org-latex-to-mathml-jar-file)))
18822 (?I . ,(shell-quote-argument tmp-in-file))
18823 (?o . ,(shell-quote-argument tmp-out-file)))))
18824 mathml shell-command-output)
18825 (when (org-called-interactively-p 'any)
18826 (unless (org-format-latex-mathml-available-p)
18827 (user-error "LaTeX to MathML converter not configured")))
18828 (message "Running %s" cmd)
18829 (setq shell-command-output (shell-command-to-string cmd))
18830 (setq mathml
18831 (when (file-readable-p tmp-out-file)
18832 (with-current-buffer (find-file-noselect tmp-out-file t)
18833 (goto-char (point-min))
18834 (when (re-search-forward
18835 (concat
18836 (regexp-quote
18837 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18838 "\\(.\\|\n\\)*"
18839 (regexp-quote "</math>")) nil t)
18840 (prog1 (match-string 0) (kill-buffer))))))
18841 (cond
18842 (mathml
18843 (setq mathml
18844 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18845 (when mathml-file
18846 (write-region mathml nil mathml-file))
18847 (when (org-called-interactively-p 'any)
18848 (message mathml)))
18849 ((message "LaTeX to MathML conversion failed")
18850 (message shell-command-output)))
18851 (delete-file tmp-in-file)
18852 (when (file-exists-p tmp-out-file)
18853 (delete-file tmp-out-file))
18854 mathml))
18856 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18857 prefix &optional dir)
18858 "Use `org-create-math-formula' but check local cache first."
18859 (let* ((absprefix (expand-file-name prefix dir))
18860 (print-length nil) (print-level nil)
18861 (formula-id (concat
18862 "formula-"
18863 (sha1
18864 (prin1-to-string
18865 (list latex-frag
18866 org-latex-to-mathml-convert-command)))))
18867 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18868 (formula-cache-dir (file-name-directory formula-cache)))
18870 (unless (file-directory-p formula-cache-dir)
18871 (make-directory formula-cache-dir t))
18873 (unless (file-exists-p formula-cache)
18874 (org-create-math-formula latex-frag formula-cache))
18876 (if (file-exists-p formula-cache)
18877 ;; Successful conversion. Return the link to MathML file.
18878 (org-add-props
18879 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18880 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18881 'org-latex-src-embed-type (if latex-frag-type
18882 'paragraph 'character)))
18883 ;; Failed conversion. Return the LaTeX fragment verbatim
18884 latex-frag)))
18886 (defun org-create-formula-image (string tofile options buffer &optional type)
18887 "Create an image from LaTeX source using dvipng or convert.
18888 This function calls either `org-create-formula-image-with-dvipng'
18889 or `org-create-formula-image-with-imagemagick' depending on the
18890 value of `org-latex-create-formula-image-program' or on the value
18891 of the optional TYPE variable.
18893 Note: ultimately these two function should be combined as they
18894 share a good deal of logic."
18895 (org-check-external-command
18896 "latex" "needed to convert LaTeX fragments to images")
18897 (funcall
18898 (case (or type org-latex-create-formula-image-program)
18899 ('dvipng
18900 (org-check-external-command
18901 "dvipng" "needed to convert LaTeX fragments to images")
18902 'org-create-formula-image-with-dvipng)
18903 ('imagemagick
18904 (org-check-external-command
18905 "convert" "you need to install imagemagick")
18906 'org-create-formula-image-with-imagemagick)
18907 (t (error
18908 "Invalid value of `org-latex-create-formula-image-program'")))
18909 string tofile options buffer))
18911 (declare-function org-export-get-backend "ox" (name))
18912 (declare-function org-export--get-global-options "ox" (&optional backend))
18913 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18914 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18915 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18916 (defun org-create-formula--latex-header ()
18917 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18918 (let ((info (org-combine-plists (org-export--get-global-options
18919 (org-export-get-backend 'latex))
18920 (org-export--get-inbuffer-options
18921 (org-export-get-backend 'latex)))))
18922 (org-latex-guess-babel-language
18923 (org-latex-guess-inputenc
18924 (org-splice-latex-header
18925 org-format-latex-header
18926 org-latex-default-packages-alist
18927 org-latex-packages-alist t
18928 (plist-get info :latex-header)))
18929 info)))
18931 ;; This function borrows from Ganesh Swami's latex2png.el
18932 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18933 "This calls dvipng."
18934 (require 'ox-latex)
18935 (let* ((tmpdir (if (featurep 'xemacs)
18936 (temp-directory)
18937 temporary-file-directory))
18938 (texfilebase (make-temp-name
18939 (expand-file-name "orgtex" tmpdir)))
18940 (texfile (concat texfilebase ".tex"))
18941 (dvifile (concat texfilebase ".dvi"))
18942 (pngfile (concat texfilebase ".png"))
18943 (fnh (if (featurep 'xemacs)
18944 (font-height (face-font 'default))
18945 (face-attribute 'default :height nil)))
18946 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18947 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18948 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18949 "Black"))
18950 (bg (or (plist-get options (if buffer :background :html-background))
18951 "Transparent")))
18952 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18953 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18954 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18955 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18956 (let ((latex-header (org-create-formula--latex-header)))
18957 (with-temp-file texfile
18958 (insert latex-header)
18959 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18960 (let ((dir default-directory))
18961 (ignore-errors
18962 (cd tmpdir)
18963 (call-process "latex" nil nil nil texfile))
18964 (cd dir))
18965 (if (not (file-exists-p dvifile))
18966 (progn (message "Failed to create dvi file from %s" texfile) nil)
18967 (ignore-errors
18968 (if (featurep 'xemacs)
18969 (call-process "dvipng" nil nil nil
18970 "-fg" fg "-bg" bg
18971 "-T" "tight"
18972 "-o" pngfile
18973 dvifile)
18974 (call-process "dvipng" nil nil nil
18975 "-fg" fg "-bg" bg
18976 "-D" dpi
18977 ;;"-x" scale "-y" scale
18978 "-T" "tight"
18979 "-o" pngfile
18980 dvifile)))
18981 (if (not (file-exists-p pngfile))
18982 (if org-format-latex-signal-error
18983 (error "Failed to create png file from %s" texfile)
18984 (message "Failed to create png file from %s" texfile)
18985 nil)
18986 ;; Use the requested file name and clean up
18987 (copy-file pngfile tofile 'replace)
18988 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18989 (if (file-exists-p (concat texfilebase e))
18990 (delete-file (concat texfilebase e))))
18991 pngfile))))
18993 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18994 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18995 "This calls convert, which is included into imagemagick."
18996 (require 'ox-latex)
18997 (let* ((tmpdir (if (featurep 'xemacs)
18998 (temp-directory)
18999 temporary-file-directory))
19000 (texfilebase (make-temp-name
19001 (expand-file-name "orgtex" tmpdir)))
19002 (texfile (concat texfilebase ".tex"))
19003 (pdffile (concat texfilebase ".pdf"))
19004 (pngfile (concat texfilebase ".png"))
19005 (fnh (if (featurep 'xemacs)
19006 (font-height (face-font 'default))
19007 (face-attribute 'default :height nil)))
19008 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19009 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
19010 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19011 "black"))
19012 (bg (or (plist-get options (if buffer :background :html-background))
19013 "white")))
19014 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19015 (setq fg (org-latex-color-format fg)))
19016 (if (eq bg 'default) (setq bg (org-latex-color :background))
19017 (setq bg (org-latex-color-format
19018 (if (string= bg "Transparent") "white" bg))))
19019 (let ((latex-header (org-create-formula--latex-header)))
19020 (with-temp-file texfile
19021 (insert latex-header)
19022 (insert "\n\\begin{document}\n"
19023 "\\definecolor{fg}{rgb}{" fg "}\n"
19024 "\\definecolor{bg}{rgb}{" bg "}\n"
19025 "\n\\pagecolor{bg}\n"
19026 "\n{\\color{fg}\n"
19027 string
19028 "\n}\n"
19029 "\n\\end{document}\n")))
19030 (org-latex-compile texfile t)
19031 (if (not (file-exists-p pdffile))
19032 (progn (message "Failed to create pdf file from %s" texfile) nil)
19033 (ignore-errors
19034 (if (featurep 'xemacs)
19035 (call-process "convert" nil nil nil
19036 "-density" "96"
19037 "-trim"
19038 "-antialias"
19039 pdffile
19040 "-quality" "100"
19041 ;; "-sharpen" "0x1.0"
19042 pngfile)
19043 (call-process "convert" nil nil nil
19044 "-density" dpi
19045 "-trim"
19046 "-antialias"
19047 pdffile
19048 "-quality" "100"
19049 ;; "-sharpen" "0x1.0"
19050 pngfile)))
19051 (if (not (file-exists-p pngfile))
19052 (if org-format-latex-signal-error
19053 (error "Failed to create png file from %s" texfile)
19054 (message "Failed to create png file from %s" texfile)
19055 nil)
19056 ;; Use the requested file name and clean up
19057 (copy-file pngfile tofile 'replace)
19058 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19059 (if (file-exists-p (concat texfilebase e))
19060 (delete-file (concat texfilebase e))))
19061 pngfile))))
19063 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19064 "Fill a LaTeX header template TPL.
19065 In the template, the following place holders will be recognized:
19067 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19068 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19069 [PACKAGES] \\usepackage statements for PKG
19070 [NO-PACKAGES] do not include PKG
19071 [EXTRA] the string EXTRA
19072 [NO-EXTRA] do not include EXTRA
19074 For backward compatibility, if both the positive and the negative place
19075 holder is missing, the positive one (without the \"NO-\") will be
19076 assumed to be present at the end of the template.
19077 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19078 EXTRA is a string.
19079 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19080 (let (rpl (end ""))
19081 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19082 (setq rpl (if (or (match-end 1) (not def-pkg))
19083 "" (org-latex-packages-to-string def-pkg snippets-p t))
19084 tpl (replace-match rpl t t tpl))
19085 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19087 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19088 (setq rpl (if (or (match-end 1) (not pkg))
19089 "" (org-latex-packages-to-string pkg snippets-p t))
19090 tpl (replace-match rpl t t tpl))
19091 (if pkg (setq end
19092 (concat end "\n"
19093 (org-latex-packages-to-string pkg snippets-p)))))
19095 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19096 (setq rpl (if (or (match-end 1) (not extra))
19097 "" (concat extra "\n"))
19098 tpl (replace-match rpl t t tpl))
19099 (if (and extra (string-match "\\S-" extra))
19100 (setq end (concat end "\n" extra))))
19102 (if (string-match "\\S-" end)
19103 (concat tpl "\n" end)
19104 tpl)))
19106 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19107 "Turn an alist of packages into a string with the \\usepackage macros."
19108 (setq pkg (mapconcat (lambda(p)
19109 (cond
19110 ((stringp p) p)
19111 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19112 (format "%% Package %s omitted" (cadr p)))
19113 ((equal "" (car p))
19114 (format "\\usepackage{%s}" (cadr p)))
19116 (format "\\usepackage[%s]{%s}"
19117 (car p) (cadr p)))))
19119 "\n"))
19120 (if newline (concat pkg "\n") pkg))
19122 (defun org-dvipng-color (attr)
19123 "Return a RGB color specification for dvipng."
19124 (apply 'format "rgb %s %s %s"
19125 (mapcar 'org-normalize-color
19126 (if (featurep 'xemacs)
19127 (color-rgb-components
19128 (face-property 'default
19129 (cond ((eq attr :foreground) 'foreground)
19130 ((eq attr :background) 'background))))
19131 (color-values (face-attribute 'default attr nil))))))
19133 (defun org-dvipng-color-format (color-name)
19134 "Convert COLOR-NAME to a RGB color value for dvipng."
19135 (apply 'format "rgb %s %s %s"
19136 (mapcar 'org-normalize-color
19137 (color-values color-name))))
19139 (defun org-latex-color (attr)
19140 "Return a RGB color for the LaTeX color package."
19141 (apply 'format "%s,%s,%s"
19142 (mapcar 'org-normalize-color
19143 (if (featurep 'xemacs)
19144 (color-rgb-components
19145 (face-property 'default
19146 (cond ((eq attr :foreground) 'foreground)
19147 ((eq attr :background) 'background))))
19148 (color-values (face-attribute 'default attr nil))))))
19150 (defun org-latex-color-format (color-name)
19151 "Convert COLOR-NAME to a RGB color value."
19152 (apply 'format "%s,%s,%s"
19153 (mapcar 'org-normalize-color
19154 (color-values color-name))))
19156 (defun org-normalize-color (value)
19157 "Return string to be used as color value for an RGB component."
19158 (format "%g" (/ value 65535.0)))
19162 ;; Image display
19164 (defvar org-inline-image-overlays nil)
19165 (make-variable-buffer-local 'org-inline-image-overlays)
19167 (defun org-toggle-inline-images (&optional include-linked)
19168 "Toggle the display of inline images.
19169 INCLUDE-LINKED is passed to `org-display-inline-images'."
19170 (interactive "P")
19171 (if org-inline-image-overlays
19172 (progn
19173 (org-remove-inline-images)
19174 (message "Inline image display turned off"))
19175 (org-display-inline-images include-linked)
19176 (if (and (org-called-interactively-p)
19177 org-inline-image-overlays)
19178 (message "%d images displayed inline"
19179 (length org-inline-image-overlays))
19180 (message "No images to display inline"))))
19182 (defun org-redisplay-inline-images ()
19183 "Refresh the display of inline images."
19184 (interactive)
19185 (if (not org-inline-image-overlays)
19186 (org-toggle-inline-images)
19187 (org-toggle-inline-images)
19188 (org-toggle-inline-images)))
19190 (defun org-display-inline-images (&optional include-linked refresh beg end)
19191 "Display inline images.
19193 An inline image is a link which follows either of these
19194 conventions:
19196 1. Its path is a file with an extension matching return value
19197 from `image-file-name-regexp' and it has no contents.
19199 2. Its description consists in a single link of the previous
19200 type.
19202 When optional argument INCLUDE-LINKED is non-nil, also links with
19203 a text description part will be inlined. This can be nice for
19204 a quick look at those images, but it does not reflect what
19205 exported files will look like.
19207 When optional argument REFRESH is non-nil, refresh existing
19208 images between BEG and END. This will create new image displays
19209 only if necessary. BEG and END default to the buffer
19210 boundaries."
19211 (interactive "P")
19212 (when (display-graphic-p)
19213 (unless refresh
19214 (org-remove-inline-images)
19215 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19216 (org-with-wide-buffer
19217 (goto-char (or beg (point-min)))
19218 (let ((case-fold-search t)
19219 (file-extension-re (org-image-file-name-regexp)))
19220 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19221 (let ((link (save-match-data (org-element-context))))
19222 ;; Check if we're at an inline image.
19223 (when (and (equal (org-element-property :type link) "file")
19224 (or include-linked
19225 (not (org-element-property :contents-begin link)))
19226 (let ((parent (org-element-property :parent link)))
19227 (or (not (eq (org-element-type parent) 'link))
19228 (not (cdr (org-element-contents parent)))))
19229 (org-string-match-p file-extension-re
19230 (org-element-property :path link)))
19231 (let ((file (expand-file-name (org-element-property :path link))))
19232 (when (file-exists-p file)
19233 (let ((width
19234 ;; Apply `org-image-actual-width' specifications.
19235 (cond
19236 ((not (image-type-available-p 'imagemagick)) nil)
19237 ((eq org-image-actual-width t) nil)
19238 ((listp org-image-actual-width)
19240 ;; First try to find a width among
19241 ;; attributes associated to the paragraph
19242 ;; containing link.
19243 (let ((paragraph
19244 (let ((e link))
19245 (while (and (setq e (org-element-property
19246 :parent e))
19247 (not (eq (org-element-type e)
19248 'paragraph))))
19249 e)))
19250 (when paragraph
19251 (save-excursion
19252 (goto-char (org-element-property :begin paragraph))
19253 (when
19254 (re-search-forward
19255 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19256 (org-element-property
19257 :post-affiliated paragraph)
19259 (string-to-number (match-string 1))))))
19260 ;; Otherwise, fall-back to provided number.
19261 (car org-image-actual-width)))
19262 ((numberp org-image-actual-width)
19263 org-image-actual-width)))
19264 (old (get-char-property-and-overlay
19265 (org-element-property :begin link)
19266 'org-image-overlay)))
19267 (if (and (car-safe old) refresh)
19268 (image-refresh (overlay-get (cdr old) 'display))
19269 (let ((image (create-image file
19270 (and width 'imagemagick)
19272 :width width)))
19273 (when image
19274 (let* ((link
19275 ;; If inline image is the description
19276 ;; of another link, be sure to
19277 ;; consider the latter as the one to
19278 ;; apply the overlay on.
19279 (let ((parent
19280 (org-element-property :parent link)))
19281 (if (eq (org-element-type parent) 'link)
19282 parent
19283 link)))
19284 (ov (make-overlay
19285 (org-element-property :begin link)
19286 (progn
19287 (goto-char
19288 (org-element-property :end link))
19289 (skip-chars-backward " \t")
19290 (point)))))
19291 (overlay-put ov 'display image)
19292 (overlay-put ov 'face 'default)
19293 (overlay-put ov 'org-image-overlay t)
19294 (overlay-put
19295 ov 'modification-hooks
19296 (list 'org-display-inline-remove-overlay))
19297 (push ov org-inline-image-overlays)))))))))))))))
19299 (define-obsolete-function-alias
19300 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19302 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19303 "Remove inline-display overlay if a corresponding region is modified."
19304 (let ((inhibit-modification-hooks t))
19305 (when (and ov after)
19306 (delete ov org-inline-image-overlays)
19307 (delete-overlay ov))))
19309 (defun org-remove-inline-images ()
19310 "Remove inline display of images."
19311 (interactive)
19312 (mapc 'delete-overlay org-inline-image-overlays)
19313 (setq org-inline-image-overlays nil))
19315 ;;;; Key bindings
19317 ;; Outline functions from `outline-mode-prefix-map'
19318 ;; that can be remapped in Org:
19319 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19320 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19321 (define-key org-mode-map [remap outline-forward-same-level]
19322 'org-forward-heading-same-level)
19323 (define-key org-mode-map [remap outline-backward-same-level]
19324 'org-backward-heading-same-level)
19325 (define-key org-mode-map [remap show-branches]
19326 'org-kill-note-or-show-branches)
19327 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19328 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19329 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19331 ;; Outline functions from `outline-mode-prefix-map' that can not
19332 ;; be remapped in Org:
19334 ;; - the column "key binding" shows whether the Outline function is still
19335 ;; available in Org mode on the same key that it has been bound to in
19336 ;; Outline mode:
19337 ;; - "overridden": key used for a different functionality in Org mode
19338 ;; - else: key still bound to the same Outline function in Org mode
19340 ;; | Outline function | key binding | Org replacement |
19341 ;; |------------------------------------+-------------+-----------------------|
19342 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19343 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19344 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19345 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19346 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19347 ;; | `show-entry' | overridden | no replacement |
19348 ;; | `show-children' | `C-c C-i' | visibility cycling |
19349 ;; | `show-branches' | `C-c C-k' | still same function |
19350 ;; | `show-subtree' | overridden | visibility cycling |
19351 ;; | `show-all' | overridden | no replacement |
19352 ;; | `hide-subtree' | overridden | visibility cycling |
19353 ;; | `hide-body' | overridden | no replacement |
19354 ;; | `hide-entry' | overridden | visibility cycling |
19355 ;; | `hide-leaves' | overridden | no replacement |
19356 ;; | `hide-sublevels' | overridden | no replacement |
19357 ;; | `hide-other' | overridden | no replacement |
19359 ;; Make `C-c C-x' a prefix key
19360 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19362 ;; TAB key with modifiers
19363 (org-defkey org-mode-map "\C-i" 'org-cycle)
19364 (org-defkey org-mode-map [(tab)] 'org-cycle)
19365 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19366 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19367 ;; The following line is necessary under Suse GNU/Linux
19368 (unless (featurep 'xemacs)
19369 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19370 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19371 (define-key org-mode-map [backtab] 'org-shifttab)
19373 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19374 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19375 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19377 ;; Cursor keys with modifiers
19378 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19379 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19380 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19381 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19383 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19384 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19385 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19386 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19387 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19388 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19390 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19391 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19392 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19393 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19395 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19396 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19397 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19398 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19400 ;; Babel keys
19401 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19402 (mapc (lambda (pair)
19403 (define-key org-babel-map (car pair) (cdr pair)))
19404 org-babel-key-bindings)
19406 ;;; Extra keys for tty access.
19407 ;; We only set them when really needed because otherwise the
19408 ;; menus don't show the simple keys
19410 (when (or org-use-extra-keys
19411 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19412 (not window-system))
19413 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19414 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19415 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19416 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19417 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19418 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19419 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19420 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19421 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19422 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19423 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19424 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19425 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19426 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19427 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19428 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19429 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19430 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19431 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19432 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19433 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19434 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19435 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19436 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19437 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19438 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19439 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19440 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19442 ;; All the other keys
19444 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19445 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19446 (if (boundp 'narrow-map)
19447 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19448 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19449 (if (boundp 'narrow-map)
19450 (org-defkey narrow-map "b" 'org-narrow-to-block)
19451 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19452 (if (boundp 'narrow-map)
19453 (org-defkey narrow-map "e" 'org-narrow-to-element)
19454 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19455 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19456 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19457 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19458 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19459 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19460 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19461 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19462 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19463 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19464 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19465 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19466 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19467 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19468 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19469 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19470 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19471 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19472 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19473 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19474 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19475 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19476 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19477 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19478 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19479 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19480 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19481 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19482 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19483 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19484 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19485 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19486 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19487 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19488 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19489 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19490 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19491 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19492 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19493 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19494 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19495 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19496 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19497 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19498 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19499 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19500 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19501 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19502 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19503 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19504 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19505 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19506 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19507 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19508 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19509 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19510 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19511 (org-defkey org-mode-map "\C-c^" 'org-sort)
19512 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19513 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19514 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19515 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19516 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19517 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19518 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19519 (org-defkey org-mode-map "\C-m" 'org-return)
19520 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19521 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19522 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19523 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19524 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19525 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19526 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19527 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19528 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19529 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19530 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19531 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19532 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19533 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19534 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19535 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19536 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19537 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19538 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19539 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19540 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19541 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19542 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19543 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19544 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19546 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19547 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19548 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19550 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19551 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19552 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19553 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19554 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19555 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19556 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19557 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19558 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19559 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19560 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19561 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19562 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19563 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19564 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19565 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19566 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19567 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19568 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19569 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19570 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19571 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19572 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19574 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19575 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19576 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19577 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19578 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19580 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19582 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19584 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19585 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19587 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19590 (when (featurep 'xemacs)
19591 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19594 (defconst org-speed-commands-default
19596 ("Outline Navigation")
19597 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19598 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19599 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19600 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19601 ("F" . org-next-block)
19602 ("B" . org-previous-block)
19603 ("u" . (org-speed-move-safe 'outline-up-heading))
19604 ("j" . org-goto)
19605 ("g" . (org-refile t))
19606 ("Outline Visibility")
19607 ("c" . org-cycle)
19608 ("C" . org-shifttab)
19609 (" " . org-display-outline-path)
19610 ("s" . org-narrow-to-subtree)
19611 ("=" . org-columns)
19612 ("Outline Structure Editing")
19613 ("U" . org-metaup)
19614 ("D" . org-metadown)
19615 ("r" . org-metaright)
19616 ("l" . org-metaleft)
19617 ("R" . org-shiftmetaright)
19618 ("L" . org-shiftmetaleft)
19619 ("i" . (progn (forward-char 1) (call-interactively
19620 'org-insert-heading-respect-content)))
19621 ("^" . org-sort)
19622 ("w" . org-refile)
19623 ("a" . org-archive-subtree-default-with-confirmation)
19624 ("@" . org-mark-subtree)
19625 ("#" . org-toggle-comment)
19626 ("Clock Commands")
19627 ("I" . org-clock-in)
19628 ("O" . org-clock-out)
19629 ("Meta Data Editing")
19630 ("t" . org-todo)
19631 ("," . (org-priority))
19632 ("0" . (org-priority ?\ ))
19633 ("1" . (org-priority ?A))
19634 ("2" . (org-priority ?B))
19635 ("3" . (org-priority ?C))
19636 (":" . org-set-tags-command)
19637 ("e" . org-set-effort)
19638 ("E" . org-inc-effort)
19639 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19640 (org-entry-put (point) "APPT_WARNTIME" m)))
19641 ("Agenda Views etc")
19642 ("v" . org-agenda)
19643 ("/" . org-sparse-tree)
19644 ("Misc")
19645 ("o" . org-open-at-point)
19646 ("?" . org-speed-command-help)
19647 ("<" . (org-agenda-set-restriction-lock 'subtree))
19648 (">" . (org-agenda-remove-restriction-lock))
19650 "The default speed commands.")
19652 (defun org-print-speed-command (e)
19653 (if (> (length (car e)) 1)
19654 (progn
19655 (princ "\n")
19656 (princ (car e))
19657 (princ "\n")
19658 (princ (make-string (length (car e)) ?-))
19659 (princ "\n"))
19660 (princ (car e))
19661 (princ " ")
19662 (if (symbolp (cdr e))
19663 (princ (symbol-name (cdr e)))
19664 (prin1 (cdr e)))
19665 (princ "\n")))
19667 (defun org-speed-command-help ()
19668 "Show the available speed commands."
19669 (interactive)
19670 (if (not org-use-speed-commands)
19671 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19672 (with-output-to-temp-buffer "*Help*"
19673 (princ "User-defined Speed commands\n===========================\n")
19674 (mapc 'org-print-speed-command org-speed-commands-user)
19675 (princ "\n")
19676 (princ "Built-in Speed commands\n=======================\n")
19677 (mapc 'org-print-speed-command org-speed-commands-default))
19678 (with-current-buffer "*Help*"
19679 (setq truncate-lines t))))
19681 (defun org-speed-move-safe (cmd)
19682 "Execute CMD, but make sure that the cursor always ends up in a headline.
19683 If not, return to the original position and throw an error."
19684 (interactive)
19685 (let ((pos (point)))
19686 (call-interactively cmd)
19687 (unless (and (bolp) (org-at-heading-p))
19688 (goto-char pos)
19689 (error "Boundary reached while executing %s" cmd))))
19691 (defvar org-self-insert-command-undo-counter 0)
19693 (defvar org-table-auto-blank-field) ; defined in org-table.el
19694 (defvar org-speed-command nil)
19696 (define-obsolete-function-alias
19697 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19699 (defun org-speed-command-activate (keys)
19700 "Hook for activating single-letter speed commands.
19701 `org-speed-commands-default' specifies a minimal command set.
19702 Use `org-speed-commands-user' for further customization."
19703 (when (or (and (bolp) (looking-at org-outline-regexp))
19704 (and (functionp org-use-speed-commands)
19705 (funcall org-use-speed-commands)))
19706 (cdr (assoc keys (append org-speed-commands-user
19707 org-speed-commands-default)))))
19709 (define-obsolete-function-alias
19710 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19712 (defun org-babel-speed-command-activate (keys)
19713 "Hook for activating single-letter code block commands."
19714 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19715 (cdr (assoc keys org-babel-key-bindings))))
19717 (defcustom org-speed-command-hook
19718 '(org-speed-command-default-hook org-babel-speed-command-hook)
19719 "Hook for activating speed commands at strategic locations.
19720 Hook functions are called in sequence until a valid handler is
19721 found.
19723 Each hook takes a single argument, a user-pressed command key
19724 which is also a `self-insert-command' from the global map.
19726 Within the hook, examine the cursor position and the command key
19727 and return nil or a valid handler as appropriate. Handler could
19728 be one of an interactive command, a function, or a form.
19730 Set `org-use-speed-commands' to non-nil value to enable this
19731 hook. The default setting is `org-speed-command-activate'."
19732 :group 'org-structure
19733 :version "24.1"
19734 :type 'hook)
19736 (defun org-self-insert-command (N)
19737 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19738 If the cursor is in a table looking at whitespace, the whitespace is
19739 overwritten, and the table is not marked as requiring realignment."
19740 (interactive "p")
19741 (org-check-before-invisible-edit 'insert)
19742 (cond
19743 ((and org-use-speed-commands
19744 (let ((kv (this-command-keys-vector)))
19745 (setq org-speed-command
19746 (run-hook-with-args-until-success
19747 'org-speed-command-hook
19748 (make-string 1 (aref kv (1- (length kv))))))))
19749 (cond
19750 ((commandp org-speed-command)
19751 (setq this-command org-speed-command)
19752 (call-interactively org-speed-command))
19753 ((functionp org-speed-command)
19754 (funcall org-speed-command))
19755 ((and org-speed-command (listp org-speed-command))
19756 (eval org-speed-command))
19757 (t (let (org-use-speed-commands)
19758 (call-interactively 'org-self-insert-command)))))
19759 ((and
19760 (org-table-p)
19761 (progn
19762 ;; check if we blank the field, and if that triggers align
19763 (and (featurep 'org-table) org-table-auto-blank-field
19764 (member last-command
19765 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas-expand))
19766 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19767 ;; got extra space, this field does not determine column width
19768 (let (org-table-may-need-update) (org-table-blank-field))
19769 ;; no extra space, this field may determine column width
19770 (org-table-blank-field)))
19772 (eq N 1)
19773 (looking-at "[^|\n]* |"))
19774 (let (org-table-may-need-update)
19775 (goto-char (1- (match-end 0)))
19776 (backward-delete-char 1)
19777 (goto-char (match-beginning 0))
19778 (self-insert-command N)))
19780 (setq org-table-may-need-update t)
19781 (self-insert-command N)
19782 (org-fix-tags-on-the-fly)
19783 (if org-self-insert-cluster-for-undo
19784 (if (not (eq last-command 'org-self-insert-command))
19785 (setq org-self-insert-command-undo-counter 1)
19786 (if (>= org-self-insert-command-undo-counter 20)
19787 (setq org-self-insert-command-undo-counter 1)
19788 (and (> org-self-insert-command-undo-counter 0)
19789 buffer-undo-list (listp buffer-undo-list)
19790 (not (cadr buffer-undo-list)) ; remove nil entry
19791 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19792 (setq org-self-insert-command-undo-counter
19793 (1+ org-self-insert-command-undo-counter))))))))
19795 (defun org-check-before-invisible-edit (kind)
19796 "Check is editing if kind KIND would be dangerous with invisible text around.
19797 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19798 ;; First, try to get out of here as quickly as possible, to reduce overhead
19799 (if (and org-catch-invisible-edits
19800 (or (not (boundp 'visible-mode)) (not visible-mode))
19801 (or (get-char-property (point) 'invisible)
19802 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19803 ;; OK, we need to take a closer look
19804 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19805 (invisible-before-point (if (bobp) nil (get-char-property
19806 (1- (point)) 'invisible)))
19807 (border-and-ok-direction
19809 ;; Check if we are acting predictably before invisible text
19810 (and invisible-at-point (not invisible-before-point)
19811 (memq kind '(insert delete-backward)))
19812 ;; Check if we are acting predictably after invisible text
19813 ;; This works not well, and I have turned it off. It seems
19814 ;; better to always show and stop after invisible text.
19815 ;; (and (not invisible-at-point) invisible-before-point
19816 ;; (memq kind '(insert delete)))
19818 (when (or (memq invisible-at-point '(outline org-hide-block t))
19819 (memq invisible-before-point '(outline org-hide-block t)))
19820 (if (eq org-catch-invisible-edits 'error)
19821 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19822 (if (and org-custom-properties-overlays
19823 (y-or-n-p "Display invisible properties in this buffer? "))
19824 (org-toggle-custom-properties-visibility)
19825 ;; Make the area visible
19826 (save-excursion
19827 (if invisible-before-point
19828 (goto-char (previous-single-char-property-change
19829 (point) 'invisible)))
19830 (show-subtree))
19831 (cond
19832 ((eq org-catch-invisible-edits 'show)
19833 ;; That's it, we do the edit after showing
19834 (message
19835 "Unfolding invisible region around point before editing")
19836 (sit-for 1))
19837 ((and (eq org-catch-invisible-edits 'smart)
19838 border-and-ok-direction)
19839 (message "Unfolding invisible region around point before editing"))
19841 ;; Don't do the edit, make the user repeat it in full visibility
19842 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19844 (defun org-fix-tags-on-the-fly ()
19845 (when (and (equal (char-after (point-at-bol)) ?*)
19846 (org-at-heading-p))
19847 (org-align-tags-here org-tags-column)))
19849 (defun org-delete-backward-char (N)
19850 "Like `delete-backward-char', insert whitespace at field end in tables.
19851 When deleting backwards, in tables this function will insert whitespace in
19852 front of the next \"|\" separator, to keep the table aligned. The table will
19853 still be marked for re-alignment if the field did fill the entire column,
19854 because, in this case the deletion might narrow the column."
19855 (interactive "p")
19856 (save-match-data
19857 (org-check-before-invisible-edit 'delete-backward)
19858 (if (and (org-table-p)
19859 (eq N 1)
19860 (string-match "|" (buffer-substring (point-at-bol) (point)))
19861 (looking-at ".*?|"))
19862 (let ((pos (point))
19863 (noalign (looking-at "[^|\n\r]* |"))
19864 (c org-table-may-need-update))
19865 (backward-delete-char N)
19866 (if (not overwrite-mode)
19867 (progn
19868 (skip-chars-forward "^|")
19869 (insert " ")
19870 (goto-char (1- pos))))
19871 ;; noalign: if there were two spaces at the end, this field
19872 ;; does not determine the width of the column.
19873 (if noalign (setq org-table-may-need-update c)))
19874 (backward-delete-char N)
19875 (org-fix-tags-on-the-fly))))
19877 (defun org-delete-char (N)
19878 "Like `delete-char', but insert whitespace at field end in tables.
19879 When deleting characters, in tables this function will insert whitespace in
19880 front of the next \"|\" separator, to keep the table aligned. The table will
19881 still be marked for re-alignment if the field did fill the entire column,
19882 because, in this case the deletion might narrow the column."
19883 (interactive "p")
19884 (save-match-data
19885 (org-check-before-invisible-edit 'delete)
19886 (if (and (org-table-p)
19887 (not (bolp))
19888 (not (= (char-after) ?|))
19889 (eq N 1))
19890 (if (looking-at ".*?|")
19891 (let ((pos (point))
19892 (noalign (looking-at "[^|\n\r]* |"))
19893 (c org-table-may-need-update))
19894 (replace-match
19895 (concat (substring (match-string 0) 1 -1) " |") nil t)
19896 (goto-char pos)
19897 ;; noalign: if there were two spaces at the end, this field
19898 ;; does not determine the width of the column.
19899 (if noalign (setq org-table-may-need-update c)))
19900 (delete-char N))
19901 (delete-char N)
19902 (org-fix-tags-on-the-fly))))
19904 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19905 (put 'org-self-insert-command 'delete-selection
19906 (lambda ()
19907 (not (run-hook-with-args-until-success
19908 'self-insert-uses-region-functions))))
19909 (put 'orgtbl-self-insert-command 'delete-selection
19910 (lambda ()
19911 (not (run-hook-with-args-until-success
19912 'self-insert-uses-region-functions))))
19913 (put 'org-delete-char 'delete-selection 'supersede)
19914 (put 'org-delete-backward-char 'delete-selection 'supersede)
19915 (put 'org-yank 'delete-selection 'yank)
19917 ;; Make `flyspell-mode' delay after some commands
19918 (put 'org-self-insert-command 'flyspell-delayed t)
19919 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19920 (put 'org-delete-char 'flyspell-delayed t)
19921 (put 'org-delete-backward-char 'flyspell-delayed t)
19923 ;; Make pabbrev-mode expand after org-mode commands
19924 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19925 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19927 (defun org-remap (map &rest commands)
19928 "In MAP, remap the functions given in COMMANDS.
19929 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19930 (let (new old)
19931 (while commands
19932 (setq old (pop commands) new (pop commands))
19933 (if (fboundp 'command-remapping)
19934 (org-defkey map (vector 'remap old) new)
19935 (substitute-key-definition old new map global-map)))))
19937 (defun org-transpose-words ()
19938 "Transpose words for Org.
19939 This uses the `org-mode-transpose-word-syntax-table' syntax
19940 table, which interprets characters in `org-emphasis-alist' as
19941 word constituents."
19942 (interactive)
19943 (with-syntax-table org-mode-transpose-word-syntax-table
19944 (call-interactively 'transpose-words)))
19945 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19947 (when (eq org-enable-table-editor 'optimized)
19948 ;; If the user wants maximum table support, we need to hijack
19949 ;; some standard editing functions
19950 (org-remap org-mode-map
19951 'self-insert-command 'org-self-insert-command
19952 'delete-char 'org-delete-char
19953 'delete-backward-char 'org-delete-backward-char)
19954 (org-defkey org-mode-map "|" 'org-force-self-insert))
19956 (defvar org-ctrl-c-ctrl-c-hook nil
19957 "Hook for functions attaching themselves to `C-c C-c'.
19959 This can be used to add additional functionality to the C-c C-c
19960 key which executes context-dependent commands. This hook is run
19961 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19962 run after the last test.
19964 Each function will be called with no arguments. The function
19965 must check if the context is appropriate for it to act. If yes,
19966 it should do its thing and then return a non-nil value. If the
19967 context is wrong, just do nothing and return nil.")
19969 (defvar org-ctrl-c-ctrl-c-final-hook nil
19970 "Hook for functions attaching themselves to `C-c C-c'.
19972 This can be used to add additional functionality to the C-c C-c
19973 key which executes context-dependent commands. This hook is run
19974 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19975 before the first test.
19977 Each function will be called with no arguments. The function
19978 must check if the context is appropriate for it to act. If yes,
19979 it should do its thing and then return a non-nil value. If the
19980 context is wrong, just do nothing and return nil.")
19982 (defvar org-tab-first-hook nil
19983 "Hook for functions to attach themselves to TAB.
19984 See `org-ctrl-c-ctrl-c-hook' for more information.
19985 This hook runs as the first action when TAB is pressed, even before
19986 `org-cycle' messes around with the `outline-regexp' to cater for
19987 inline tasks and plain list item folding.
19988 If any function in this hook returns t, any other actions that
19989 would have been caused by TAB (such as table field motion or visibility
19990 cycling) will not occur.")
19992 (defvar org-tab-after-check-for-table-hook nil
19993 "Hook for functions to attach themselves to TAB.
19994 See `org-ctrl-c-ctrl-c-hook' for more information.
19995 This hook runs after it has been established that the cursor is not in a
19996 table, but before checking if the cursor is in a headline or if global cycling
19997 should be done.
19998 If any function in this hook returns t, not other actions like visibility
19999 cycling will be done.")
20001 (defvar org-tab-after-check-for-cycling-hook nil
20002 "Hook for functions to attach themselves to TAB.
20003 See `org-ctrl-c-ctrl-c-hook' for more information.
20004 This hook runs after it has been established that not table field motion and
20005 not visibility should be done because of current context. This is probably
20006 the place where a package like yasnippets can hook in.")
20008 (defvar org-tab-before-tab-emulation-hook nil
20009 "Hook for functions to attach themselves to TAB.
20010 See `org-ctrl-c-ctrl-c-hook' for more information.
20011 This hook runs after every other options for TAB have been exhausted, but
20012 before indentation and \t insertion takes place.")
20014 (defvar org-metaleft-hook nil
20015 "Hook for functions attaching themselves to `M-left'.
20016 See `org-ctrl-c-ctrl-c-hook' for more information.")
20017 (defvar org-metaright-hook nil
20018 "Hook for functions attaching themselves to `M-right'.
20019 See `org-ctrl-c-ctrl-c-hook' for more information.")
20020 (defvar org-metaup-hook nil
20021 "Hook for functions attaching themselves to `M-up'.
20022 See `org-ctrl-c-ctrl-c-hook' for more information.")
20023 (defvar org-metadown-hook nil
20024 "Hook for functions attaching themselves to `M-down'.
20025 See `org-ctrl-c-ctrl-c-hook' for more information.")
20026 (defvar org-shiftmetaleft-hook nil
20027 "Hook for functions attaching themselves to `M-S-left'.
20028 See `org-ctrl-c-ctrl-c-hook' for more information.")
20029 (defvar org-shiftmetaright-hook nil
20030 "Hook for functions attaching themselves to `M-S-right'.
20031 See `org-ctrl-c-ctrl-c-hook' for more information.")
20032 (defvar org-shiftmetaup-hook nil
20033 "Hook for functions attaching themselves to `M-S-up'.
20034 See `org-ctrl-c-ctrl-c-hook' for more information.")
20035 (defvar org-shiftmetadown-hook nil
20036 "Hook for functions attaching themselves to `M-S-down'.
20037 See `org-ctrl-c-ctrl-c-hook' for more information.")
20038 (defvar org-metareturn-hook nil
20039 "Hook for functions attaching themselves to `M-RET'.
20040 See `org-ctrl-c-ctrl-c-hook' for more information.")
20041 (defvar org-shiftup-hook nil
20042 "Hook for functions attaching themselves to `S-up'.
20043 See `org-ctrl-c-ctrl-c-hook' for more information.")
20044 (defvar org-shiftup-final-hook nil
20045 "Hook for functions attaching themselves to `S-up'.
20046 This one runs after all other options except shift-select have been excluded.
20047 See `org-ctrl-c-ctrl-c-hook' for more information.")
20048 (defvar org-shiftdown-hook nil
20049 "Hook for functions attaching themselves to `S-down'.
20050 See `org-ctrl-c-ctrl-c-hook' for more information.")
20051 (defvar org-shiftdown-final-hook nil
20052 "Hook for functions attaching themselves to `S-down'.
20053 This one runs after all other options except shift-select have been excluded.
20054 See `org-ctrl-c-ctrl-c-hook' for more information.")
20055 (defvar org-shiftleft-hook nil
20056 "Hook for functions attaching themselves to `S-left'.
20057 See `org-ctrl-c-ctrl-c-hook' for more information.")
20058 (defvar org-shiftleft-final-hook nil
20059 "Hook for functions attaching themselves to `S-left'.
20060 This one runs after all other options except shift-select have been excluded.
20061 See `org-ctrl-c-ctrl-c-hook' for more information.")
20062 (defvar org-shiftright-hook nil
20063 "Hook for functions attaching themselves to `S-right'.
20064 See `org-ctrl-c-ctrl-c-hook' for more information.")
20065 (defvar org-shiftright-final-hook nil
20066 "Hook for functions attaching themselves to `S-right'.
20067 This one runs after all other options except shift-select have been excluded.
20068 See `org-ctrl-c-ctrl-c-hook' for more information.")
20070 (defun org-modifier-cursor-error ()
20071 "Throw an error, a modified cursor command was applied in wrong context."
20072 (user-error "This command is active in special context like tables, headlines or items"))
20074 (defun org-shiftselect-error ()
20075 "Throw an error because Shift-Cursor command was applied in wrong context."
20076 (if (and (boundp 'shift-select-mode) shift-select-mode)
20077 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20078 (user-error "This command works only in special context like headlines or timestamps")))
20080 (defun org-call-for-shift-select (cmd)
20081 (let ((this-command-keys-shift-translated t))
20082 (call-interactively cmd)))
20084 (defun org-shifttab (&optional arg)
20085 "Global visibility cycling or move to previous table field.
20086 Call `org-table-previous-field' within a table.
20087 When ARG is nil, cycle globally through visibility states.
20088 When ARG is a numeric prefix, show contents of this level."
20089 (interactive "P")
20090 (cond
20091 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20092 ((integerp arg)
20093 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20094 (message "Content view to level: %d" arg)
20095 (org-content (prefix-numeric-value arg2))
20096 (org-cycle-show-empty-lines t)
20097 (setq org-cycle-global-status 'overview)))
20098 (t (call-interactively 'org-global-cycle))))
20100 (defun org-shiftmetaleft ()
20101 "Promote subtree or delete table column.
20102 Calls `org-promote-subtree', `org-outdent-item-tree', or
20103 `org-table-delete-column', depending on context. See the
20104 individual commands for more information."
20105 (interactive)
20106 (cond
20107 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20108 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20109 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20110 ((if (not (org-region-active-p)) (org-at-item-p)
20111 (save-excursion (goto-char (region-beginning))
20112 (org-at-item-p)))
20113 (call-interactively 'org-outdent-item-tree))
20114 (t (org-modifier-cursor-error))))
20116 (defun org-shiftmetaright ()
20117 "Demote subtree or insert table column.
20118 Calls `org-demote-subtree', `org-indent-item-tree', or
20119 `org-table-insert-column', depending on context. See the
20120 individual commands for more information."
20121 (interactive)
20122 (cond
20123 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20124 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20125 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20126 ((if (not (org-region-active-p)) (org-at-item-p)
20127 (save-excursion (goto-char (region-beginning))
20128 (org-at-item-p)))
20129 (call-interactively 'org-indent-item-tree))
20130 (t (org-modifier-cursor-error))))
20132 (defun org-shiftmetaup (&optional arg)
20133 "Drag the line at point up.
20134 In a table, kill the current row.
20135 On a clock timestamp, update the value of the timestamp like `S-<up>'
20136 but also adjust the previous clocked item in the clock history.
20137 Everywhere else, drag the line at point up."
20138 (interactive "P")
20139 (cond
20140 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20141 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20142 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20143 (call-interactively 'org-timestamp-up)))
20144 (t (call-interactively 'org-drag-line-backward))))
20146 (defun org-shiftmetadown (&optional arg)
20147 "Drag the line at point down.
20148 In a table, insert an empty row at the current line.
20149 On a clock timestamp, update the value of the timestamp like `S-<down>'
20150 but also adjust the previous clocked item in the clock history.
20151 Everywhere else, drag the line at point down."
20152 (interactive "P")
20153 (cond
20154 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20155 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20156 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20157 (call-interactively 'org-timestamp-down)))
20158 (t (call-interactively 'org-drag-line-forward))))
20160 (defsubst org-hidden-tree-error ()
20161 (user-error
20162 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20164 (defun org-metaleft (&optional arg)
20165 "Promote heading or move table column to left.
20166 Calls `org-do-promote' or `org-table-move-column', depending on context.
20167 With no specific context, calls the Emacs default `backward-word'.
20168 See the individual commands for more information."
20169 (interactive "P")
20170 (cond
20171 ((run-hook-with-args-until-success 'org-metaleft-hook))
20172 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20173 ((org-with-limited-levels
20174 (or (org-at-heading-p)
20175 (and (org-region-active-p)
20176 (save-excursion
20177 (goto-char (region-beginning))
20178 (org-at-heading-p)))))
20179 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20180 (call-interactively 'org-do-promote))
20181 ;; At an inline task.
20182 ((org-at-heading-p)
20183 (call-interactively 'org-inlinetask-promote))
20184 ((or (org-at-item-p)
20185 (and (org-region-active-p)
20186 (save-excursion
20187 (goto-char (region-beginning))
20188 (org-at-item-p))))
20189 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20190 (call-interactively 'org-outdent-item))
20191 (t (call-interactively 'backward-word))))
20193 (defun org-metaright (&optional arg)
20194 "Demote a subtree, a list item or move table column to right.
20195 In front of a drawer or a block keyword, indent it correctly.
20196 With no specific context, calls the Emacs default `forward-word'.
20197 See the individual commands for more information."
20198 (interactive "P")
20199 (cond
20200 ((run-hook-with-args-until-success 'org-metaright-hook))
20201 ((org-at-table-p) (call-interactively 'org-table-move-column))
20202 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20203 ((org-at-block-p) (call-interactively 'org-indent-block))
20204 ((org-with-limited-levels
20205 (or (org-at-heading-p)
20206 (and (org-region-active-p)
20207 (save-excursion
20208 (goto-char (region-beginning))
20209 (org-at-heading-p)))))
20210 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20211 (call-interactively 'org-do-demote))
20212 ;; At an inline task.
20213 ((org-at-heading-p)
20214 (call-interactively 'org-inlinetask-demote))
20215 ((or (org-at-item-p)
20216 (and (org-region-active-p)
20217 (save-excursion
20218 (goto-char (region-beginning))
20219 (org-at-item-p))))
20220 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20221 (call-interactively 'org-indent-item))
20222 (t (call-interactively 'forward-word))))
20224 (defun org-check-for-hidden (what)
20225 "Check if there are hidden headlines/items in the current visual line.
20226 WHAT can be either `headlines' or `items'. If the current line is
20227 an outline or item heading and it has a folded subtree below it,
20228 this function returns t, nil otherwise."
20229 (let ((re (cond
20230 ((eq what 'headlines) org-outline-regexp-bol)
20231 ((eq what 'items) (org-item-beginning-re))
20232 (t (error "This should not happen"))))
20233 beg end)
20234 (save-excursion
20235 (catch 'exit
20236 (unless (org-region-active-p)
20237 (setq beg (point-at-bol))
20238 (beginning-of-line 2)
20239 (while (and (not (eobp)) ;; this is like `next-line'
20240 (get-char-property (1- (point)) 'invisible))
20241 (beginning-of-line 2))
20242 (setq end (point))
20243 (goto-char beg)
20244 (goto-char (point-at-eol))
20245 (setq end (max end (point)))
20246 (while (re-search-forward re end t)
20247 (if (get-char-property (match-beginning 0) 'invisible)
20248 (throw 'exit t))))
20249 nil))))
20251 (defun org-metaup (&optional arg)
20252 "Move subtree up or move table row up.
20253 Calls `org-move-subtree-up' or `org-table-move-row' or
20254 `org-move-item-up', depending on context. See the individual commands
20255 for more information."
20256 (interactive "P")
20257 (cond
20258 ((run-hook-with-args-until-success 'org-metaup-hook))
20259 ((org-region-active-p)
20260 (let* ((a (min (region-beginning) (region-end)))
20261 (b (1- (max (region-beginning) (region-end))))
20262 (c (save-excursion (goto-char a)
20263 (move-beginning-of-line 0)))
20264 (d (save-excursion (goto-char a)
20265 (move-end-of-line 0) (point))))
20266 (transpose-regions a b c d)
20267 (goto-char c)))
20268 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20269 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20270 ((org-at-item-p) (call-interactively 'org-move-item-up))
20271 (t (org-drag-element-backward))))
20273 (defun org-metadown (&optional arg)
20274 "Move subtree down or move table row down.
20275 Calls `org-move-subtree-down' or `org-table-move-row' or
20276 `org-move-item-down', depending on context. See the individual
20277 commands for more information."
20278 (interactive "P")
20279 (cond
20280 ((run-hook-with-args-until-success 'org-metadown-hook))
20281 ((org-region-active-p)
20282 (let* ((a (min (region-beginning) (region-end)))
20283 (b (max (region-beginning) (region-end)))
20284 (c (save-excursion (goto-char b)
20285 (move-beginning-of-line 1)))
20286 (d (save-excursion (goto-char b)
20287 (move-end-of-line 1) (1+ (point)))))
20288 (transpose-regions a b c d)
20289 (goto-char d)))
20290 ((org-at-table-p) (call-interactively 'org-table-move-row))
20291 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20292 ((org-at-item-p) (call-interactively 'org-move-item-down))
20293 (t (org-drag-element-forward))))
20295 (defun org-shiftup (&optional arg)
20296 "Increase item in timestamp or increase priority of current headline.
20297 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20298 depending on context. See the individual commands for more information."
20299 (interactive "P")
20300 (cond
20301 ((run-hook-with-args-until-success 'org-shiftup-hook))
20302 ((and org-support-shift-select (org-region-active-p))
20303 (org-call-for-shift-select 'previous-line))
20304 ((org-at-timestamp-p t)
20305 (call-interactively (if org-edit-timestamp-down-means-later
20306 'org-timestamp-down 'org-timestamp-up)))
20307 ((and (not (eq org-support-shift-select 'always))
20308 org-enable-priority-commands
20309 (org-at-heading-p))
20310 (call-interactively 'org-priority-up))
20311 ((and (not org-support-shift-select) (org-at-item-p))
20312 (call-interactively 'org-previous-item))
20313 ((org-clocktable-try-shift 'up arg))
20314 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20315 (org-support-shift-select
20316 (org-call-for-shift-select 'previous-line))
20317 (t (org-shiftselect-error))))
20319 (defun org-shiftdown (&optional arg)
20320 "Decrease item in timestamp or decrease priority of current headline.
20321 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20322 depending on context. See the individual commands for more information."
20323 (interactive "P")
20324 (cond
20325 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20326 ((and org-support-shift-select (org-region-active-p))
20327 (org-call-for-shift-select 'next-line))
20328 ((org-at-timestamp-p t)
20329 (call-interactively (if org-edit-timestamp-down-means-later
20330 'org-timestamp-up 'org-timestamp-down)))
20331 ((and (not (eq org-support-shift-select 'always))
20332 org-enable-priority-commands
20333 (org-at-heading-p))
20334 (call-interactively 'org-priority-down))
20335 ((and (not org-support-shift-select) (org-at-item-p))
20336 (call-interactively 'org-next-item))
20337 ((org-clocktable-try-shift 'down arg))
20338 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20339 (org-support-shift-select
20340 (org-call-for-shift-select 'next-line))
20341 (t (org-shiftselect-error))))
20343 (defun org-shiftright (&optional arg)
20344 "Cycle the thing at point or in the current line, depending on context.
20345 Depending on context, this does one of the following:
20347 - switch a timestamp at point one day into the future
20348 - on a headline, switch to the next TODO keyword.
20349 - on an item, switch entire list to the next bullet type
20350 - on a property line, switch to the next allowed value
20351 - on a clocktable definition line, move time block into the future"
20352 (interactive "P")
20353 (cond
20354 ((run-hook-with-args-until-success 'org-shiftright-hook))
20355 ((and org-support-shift-select (org-region-active-p))
20356 (org-call-for-shift-select 'forward-char))
20357 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20358 ((and (not (eq org-support-shift-select 'always))
20359 (org-at-heading-p))
20360 (let ((org-inhibit-logging
20361 (not org-treat-S-cursor-todo-selection-as-state-change))
20362 (org-inhibit-blocking
20363 (not org-treat-S-cursor-todo-selection-as-state-change)))
20364 (org-call-with-arg 'org-todo 'right)))
20365 ((or (and org-support-shift-select
20366 (not (eq org-support-shift-select 'always))
20367 (org-at-item-bullet-p))
20368 (and (not org-support-shift-select) (org-at-item-p)))
20369 (org-call-with-arg 'org-cycle-list-bullet nil))
20370 ((and (not (eq org-support-shift-select 'always))
20371 (org-at-property-p))
20372 (call-interactively 'org-property-next-allowed-value))
20373 ((org-clocktable-try-shift 'right arg))
20374 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20375 (org-support-shift-select
20376 (org-call-for-shift-select 'forward-char))
20377 (t (org-shiftselect-error))))
20379 (defun org-shiftleft (&optional arg)
20380 "Cycle the thing at point or in the current line, depending on context.
20381 Depending on context, this does one of the following:
20383 - switch a timestamp at point one day into the past
20384 - on a headline, switch to the previous TODO keyword.
20385 - on an item, switch entire list to the previous bullet type
20386 - on a property line, switch to the previous allowed value
20387 - on a clocktable definition line, move time block into the past"
20388 (interactive "P")
20389 (cond
20390 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20391 ((and org-support-shift-select (org-region-active-p))
20392 (org-call-for-shift-select 'backward-char))
20393 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20394 ((and (not (eq org-support-shift-select 'always))
20395 (org-at-heading-p))
20396 (let ((org-inhibit-logging
20397 (not org-treat-S-cursor-todo-selection-as-state-change))
20398 (org-inhibit-blocking
20399 (not org-treat-S-cursor-todo-selection-as-state-change)))
20400 (org-call-with-arg 'org-todo 'left)))
20401 ((or (and org-support-shift-select
20402 (not (eq org-support-shift-select 'always))
20403 (org-at-item-bullet-p))
20404 (and (not org-support-shift-select) (org-at-item-p)))
20405 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20406 ((and (not (eq org-support-shift-select 'always))
20407 (org-at-property-p))
20408 (call-interactively 'org-property-previous-allowed-value))
20409 ((org-clocktable-try-shift 'left arg))
20410 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20411 (org-support-shift-select
20412 (org-call-for-shift-select 'backward-char))
20413 (t (org-shiftselect-error))))
20415 (defun org-shiftcontrolright ()
20416 "Switch to next TODO set."
20417 (interactive)
20418 (cond
20419 ((and org-support-shift-select (org-region-active-p))
20420 (org-call-for-shift-select 'forward-word))
20421 ((and (not (eq org-support-shift-select 'always))
20422 (org-at-heading-p))
20423 (org-call-with-arg 'org-todo 'nextset))
20424 (org-support-shift-select
20425 (org-call-for-shift-select 'forward-word))
20426 (t (org-shiftselect-error))))
20428 (defun org-shiftcontrolleft ()
20429 "Switch to previous TODO set."
20430 (interactive)
20431 (cond
20432 ((and org-support-shift-select (org-region-active-p))
20433 (org-call-for-shift-select 'backward-word))
20434 ((and (not (eq org-support-shift-select 'always))
20435 (org-at-heading-p))
20436 (org-call-with-arg 'org-todo 'previousset))
20437 (org-support-shift-select
20438 (org-call-for-shift-select 'backward-word))
20439 (t (org-shiftselect-error))))
20441 (defun org-shiftcontrolup (&optional n)
20442 "Change timestamps synchronously up in CLOCK log lines.
20443 Optional argument N tells to change by that many units."
20444 (interactive "P")
20445 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20446 (let (org-support-shift-select)
20447 (org-clock-timestamps-up n))
20448 (user-error "Not at a clock log")))
20450 (defun org-shiftcontroldown (&optional n)
20451 "Change timestamps synchronously down in CLOCK log lines.
20452 Optional argument N tells to change by that many units."
20453 (interactive "P")
20454 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20455 (let (org-support-shift-select)
20456 (org-clock-timestamps-down n))
20457 (user-error "Not at a clock log")))
20459 (defun org-increase-number-at-point (&optional inc)
20460 "Increment the number at point.
20461 With an optional prefix numeric argument INC, increment using
20462 this numeric value."
20463 (interactive "p")
20464 (if (not (number-at-point))
20465 (user-error "Not on a number")
20466 (unless inc (setq inc 1))
20467 (let ((pos (point))
20468 (beg (skip-chars-backward "-+^/*0-9eE."))
20469 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20470 (setq nap (buffer-substring-no-properties
20471 (+ pos beg) (+ pos beg end)))
20472 (delete-region (+ pos beg) (+ pos beg end))
20473 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20474 (when (org-at-table-p)
20475 (org-table-align)
20476 (org-table-end-of-field 1))))
20478 (defun org-decrease-number-at-point (&optional inc)
20479 "Decrement the number at point.
20480 With an optional prefix numeric argument INC, decrement using
20481 this numeric value."
20482 (interactive "p")
20483 (org-increase-number-at-point (- inc)))
20485 (defun org-ctrl-c-ret ()
20486 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20487 (interactive)
20488 (cond
20489 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20490 (t (call-interactively 'org-insert-heading))))
20492 (defun org-find-visible ()
20493 (let ((s (point)))
20494 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20495 (get-char-property s 'invisible)))
20497 (defun org-find-invisible ()
20498 (let ((s (point)))
20499 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20500 (not (get-char-property s 'invisible))))
20503 (defun org-copy-visible (beg end)
20504 "Copy the visible parts of the region."
20505 (interactive "r")
20506 (let (snippets s)
20507 (save-excursion
20508 (save-restriction
20509 (narrow-to-region beg end)
20510 (setq s (goto-char (point-min)))
20511 (while (not (= (point) (point-max)))
20512 (goto-char (org-find-invisible))
20513 (push (buffer-substring s (point)) snippets)
20514 (setq s (goto-char (org-find-visible))))))
20515 (kill-new (apply 'concat (nreverse snippets)))))
20517 (defun org-copy-special ()
20518 "Copy region in table or copy current subtree.
20519 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20520 See the individual commands for more information."
20521 (interactive)
20522 (call-interactively
20523 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20525 (defun org-cut-special ()
20526 "Cut region in table or cut current subtree.
20527 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20528 See the individual commands for more information."
20529 (interactive)
20530 (call-interactively
20531 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20533 (defun org-paste-special (arg)
20534 "Paste rectangular region into table, or past subtree relative to level.
20535 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20536 See the individual commands for more information."
20537 (interactive "P")
20538 (if (org-at-table-p)
20539 (org-table-paste-rectangle)
20540 (org-paste-subtree arg)))
20542 (defsubst org-in-fixed-width-region-p ()
20543 "Is point in a fixed-width region?"
20544 (save-match-data
20545 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20547 (defun org-edit-special (&optional arg)
20548 "Call a special editor for the element at point.
20549 When at a table, call the formula editor with `org-table-edit-formulas'.
20550 When in a source code block, call `org-edit-src-code'.
20551 When in a fixed-width region, call `org-edit-fixed-width-region'.
20552 When at an #+INCLUDE keyword, visit the included file.
20553 On a link, call `ffap' to visit the link at point.
20554 Otherwise, return a user error."
20555 (interactive "P")
20556 (let ((element (org-element-at-point)))
20557 (assert (not buffer-read-only) nil
20558 "Buffer is read-only: %s" (buffer-name))
20559 (case (org-element-type element)
20560 (src-block
20561 (if (not arg) (org-edit-src-code)
20562 (let* ((info (org-babel-get-src-block-info))
20563 (lang (nth 0 info))
20564 (params (nth 2 info))
20565 (session (cdr (assq :session params))))
20566 (if (not session) (org-edit-src-code)
20567 ;; At a src-block with a session and function called with
20568 ;; an ARG: switch to the buffer related to the inferior
20569 ;; process.
20570 (switch-to-buffer
20571 (funcall (intern (concat "org-babel-prep-session:" lang))
20572 session params))))))
20573 (keyword
20574 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20575 (org-open-link-from-string
20576 (format "[[%s]]"
20577 (expand-file-name
20578 (let ((value (org-element-property :value element)))
20579 (cond ((not (org-string-nw-p value))
20580 (user-error "No file to edit"))
20581 ((string-match "\\`\"\\(.*?\\)\"" value)
20582 (match-string 1 value))
20583 ((string-match "\\`[^ \t\"]\\S-*" value)
20584 (match-string 0 value))
20585 (t (user-error "No valid file specified")))))))
20586 (user-error "No special environment to edit here")))
20587 (table
20588 (if (eq (org-element-property :type element) 'table.el)
20589 (org-edit-src-code)
20590 (call-interactively 'org-table-edit-formulas)))
20591 ;; Only Org tables contain `table-row' type elements.
20592 (table-row (call-interactively 'org-table-edit-formulas))
20593 ((example-block export-block) (org-edit-src-code))
20594 (fixed-width (org-edit-fixed-width-region))
20595 (otherwise
20596 ;; No notable element at point. Though, we may be at a link,
20597 ;; which is an object. Thus, scan deeper.
20598 (if (eq (org-element-type (org-element-context element)) 'link)
20599 (call-interactively 'ffap)
20600 (user-error "No special environment to edit here"))))))
20602 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20603 (defun org-ctrl-c-ctrl-c (&optional arg)
20604 "Set tags in headline, or update according to changed information at point.
20606 This command does many different things, depending on context:
20608 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20609 this is what we do.
20611 - If the cursor is on a statistics cookie, update it.
20613 - If the cursor is in a headline, prompt for tags and insert them
20614 into the current line, aligned to `org-tags-column'. When called
20615 with prefix arg, realign all tags in the current buffer.
20617 - If the cursor is in one of the special #+KEYWORD lines, this
20618 triggers scanning the buffer for these lines and updating the
20619 information.
20621 - If the cursor is inside a table, realign the table. This command
20622 works even if the automatic table editor has been turned off.
20624 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20625 the entire table.
20627 - If the cursor is at a footnote reference or definition, jump to
20628 the corresponding definition or references, respectively.
20630 - If the cursor is a the beginning of a dynamic block, update it.
20632 - If the current buffer is a capture buffer, close note and file it.
20634 - If the cursor is on a <<<target>>>, update radio targets and
20635 corresponding links in this buffer.
20637 - If the cursor is on a numbered item in a plain list, renumber the
20638 ordered list.
20640 - If the cursor is on a checkbox, toggle it.
20642 - If the cursor is on a code block, evaluate it. The variable
20643 `org-confirm-babel-evaluate' can be used to control prompting
20644 before code block evaluation, by default every code block
20645 evaluation requires confirmation. Code block evaluation can be
20646 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20647 (interactive "P")
20648 (cond
20649 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20650 org-occur-highlights)
20651 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20652 (org-remove-occur-highlights)
20653 (message "Temporary highlights/overlays removed from current buffer"))
20654 ((and (local-variable-p 'org-finish-function (current-buffer))
20655 (fboundp org-finish-function))
20656 (funcall org-finish-function))
20657 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20659 (let* ((context (org-element-context)) (type (org-element-type context)))
20660 ;; Test if point is within a blank line.
20661 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20662 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20663 (user-error "C-c C-c can do nothing useful at this location"))
20664 (case type
20665 ;; When at a link, act according to the parent instead.
20666 (link (setq context (org-element-property :parent context))
20667 (setq type (org-element-type context)))
20668 ;; Unsupported object types: refer to the first supported
20669 ;; element or object containing it.
20670 ((bold code entity export-snippet inline-babel-call inline-src-block
20671 italic latex-fragment line-break macro strike-through subscript
20672 superscript underline verbatim)
20673 (while (and (setq context (org-element-property :parent context))
20674 (not (memq (setq type (org-element-type context))
20675 '(radio-target paragraph verse-block
20676 table-cell)))))))
20677 ;; For convenience: at the first line of a paragraph on the
20678 ;; same line as an item, apply function on that item instead.
20679 (when (eq type 'paragraph)
20680 (let ((parent (org-element-property :parent context)))
20681 (when (and (eq (org-element-type parent) 'item)
20682 (= (point-at-bol) (org-element-property :begin parent)))
20683 (setq context parent type 'item))))
20684 ;; Act according to type of element or object at point.
20685 (case type
20686 (clock (org-clock-update-time-maybe))
20687 (dynamic-block
20688 (save-excursion
20689 (goto-char (org-element-property :post-affiliated context))
20690 (org-update-dblock)))
20691 (footnote-definition
20692 (goto-char (org-element-property :post-affiliated context))
20693 (call-interactively 'org-footnote-action))
20694 (footnote-reference (call-interactively 'org-footnote-action))
20695 ((headline inlinetask)
20696 (save-excursion (goto-char (org-element-property :begin context))
20697 (call-interactively 'org-set-tags)))
20698 (item
20699 ;; At an item: a double C-u set checkbox to "[-]"
20700 ;; unconditionally, whereas a single one will toggle its
20701 ;; presence. Without an universal argument, if the item
20702 ;; has a checkbox, toggle it. Otherwise repair the list.
20703 (let* ((box (org-element-property :checkbox context))
20704 (struct (org-element-property :structure context))
20705 (old-struct (copy-tree struct))
20706 (parents (org-list-parents-alist struct))
20707 (prevs (org-list-prevs-alist struct))
20708 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20709 (org-list-set-checkbox
20710 (org-element-property :begin context) struct
20711 (cond ((equal arg '(16)) "[-]")
20712 ((and (not box) (equal arg '(4))) "[ ]")
20713 ((or (not box) (equal arg '(4))) nil)
20714 ((eq box 'on) "[ ]")
20715 (t "[X]")))
20716 ;; Mimic `org-list-write-struct' but with grabbing
20717 ;; a return value from `org-list-struct-fix-box'.
20718 (org-list-struct-fix-ind struct parents 2)
20719 (org-list-struct-fix-item-end struct)
20720 (org-list-struct-fix-bul struct prevs)
20721 (org-list-struct-fix-ind struct parents)
20722 (let ((block-item
20723 (org-list-struct-fix-box struct parents prevs orderedp)))
20724 (if (and box (equal struct old-struct))
20725 (if (equal arg '(16))
20726 (message "Checkboxes already reset")
20727 (user-error "Cannot toggle this checkbox: %s"
20728 (if (eq box 'on)
20729 "all subitems checked"
20730 "unchecked subitems")))
20731 (org-list-struct-apply-struct struct old-struct)
20732 (org-update-checkbox-count-maybe))
20733 (when block-item
20734 (message "Checkboxes were removed due to empty box at line %d"
20735 (org-current-line block-item))))))
20736 (keyword
20737 (let ((org-inhibit-startup-visibility-stuff t)
20738 (org-startup-align-all-tables nil))
20739 (when (boundp 'org-table-coordinate-overlays)
20740 (mapc 'delete-overlay org-table-coordinate-overlays)
20741 (setq org-table-coordinate-overlays nil))
20742 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20743 (message "Local setup has been refreshed"))
20744 (plain-list
20745 ;; At a plain list, with a double C-u argument, set
20746 ;; checkboxes of each item to "[-]", whereas a single one
20747 ;; will toggle their presence according to the state of the
20748 ;; first item in the list. Without an argument, repair the
20749 ;; list.
20750 (let* ((begin (org-element-property :contents-begin context))
20751 (beginm (move-marker (make-marker) begin))
20752 (struct (org-element-property :structure context))
20753 (old-struct (copy-tree struct))
20754 (first-box (save-excursion
20755 (goto-char begin)
20756 (looking-at org-list-full-item-re)
20757 (match-string-no-properties 3)))
20758 (new-box (cond ((equal arg '(16)) "[-]")
20759 ((equal arg '(4)) (unless first-box "[ ]"))
20760 ((equal first-box "[X]") "[ ]")
20761 (t "[X]"))))
20762 (cond
20763 (arg
20764 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20765 (org-list-get-all-items
20766 begin struct (org-list-prevs-alist struct))))
20767 ((and first-box (eq (point) begin))
20768 ;; For convenience, when point is at bol on the first
20769 ;; item of the list and no argument is provided, simply
20770 ;; toggle checkbox of that item, if any.
20771 (org-list-set-checkbox begin struct new-box)))
20772 (org-list-write-struct
20773 struct (org-list-parents-alist struct) old-struct)
20774 (org-update-checkbox-count-maybe)
20775 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20776 ((property-drawer node-property)
20777 (call-interactively 'org-property-action))
20778 ((radio-target target)
20779 (call-interactively 'org-update-radio-target-regexp))
20780 (statistics-cookie
20781 (call-interactively 'org-update-statistics-cookies))
20782 ((table table-cell table-row)
20783 ;; At a table, recalculate every field and align it. Also
20784 ;; send the table if necessary. If the table has
20785 ;; a `table.el' type, just give up. At a table row or
20786 ;; cell, maybe recalculate line but always align table.
20787 (if (eq (org-element-property :type context) 'table.el)
20788 (message "Use C-c ' to edit table.el tables")
20789 (let ((org-enable-table-editor t))
20790 (if (or (eq type 'table)
20791 ;; Check if point is at a TBLFM line.
20792 (and (eq type 'table-row)
20793 (= (point) (org-element-property :end context))))
20794 (save-excursion
20795 (if (org-at-TBLFM-p)
20796 (progn (require 'org-table)
20797 (org-table-calc-current-TBLFM))
20798 (goto-char (org-element-property :contents-begin context))
20799 (org-call-with-arg 'org-table-recalculate (or arg t))
20800 (orgtbl-send-table 'maybe)))
20801 (org-table-maybe-eval-formula)
20802 (cond (arg (call-interactively 'org-table-recalculate))
20803 ((org-table-maybe-recalculate-line))
20804 (t (org-table-align)))))))
20805 (timestamp (org-timestamp-change 0 'day))
20806 (otherwise
20807 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20808 (user-error
20809 "C-c C-c can do nothing useful at this location")))))))))
20811 (defun org-mode-restart ()
20812 (interactive)
20813 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20814 (funcall major-mode)
20815 (hack-local-variables)
20816 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20817 (org-indent-mode -1)))
20818 (message "%s restarted" major-mode))
20820 (defun org-kill-note-or-show-branches ()
20821 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20822 (interactive)
20823 (if (not org-finish-function)
20824 (progn
20825 (hide-subtree)
20826 (call-interactively 'show-branches))
20827 (let ((org-note-abort t))
20828 (funcall org-finish-function))))
20830 (defun org-open-line (n)
20831 "Insert a new row in tables, call `open-line' elsewhere.
20832 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20833 (interactive "*p")
20834 (cond
20835 ((not org-special-ctrl-o)
20836 (open-line n))
20837 ((org-at-table-p)
20838 (org-table-insert-row))
20840 (open-line n))))
20842 (defun org-return (&optional indent)
20843 "Goto next table row or insert a newline.
20844 Calls `org-table-next-row' or `newline', depending on context.
20845 See the individual commands for more information."
20846 (interactive)
20847 (let (org-ts-what)
20848 (cond
20849 ((or (bobp) (org-in-src-block-p))
20850 (if indent (newline-and-indent) (newline)))
20851 ((org-at-table-p)
20852 (org-table-justify-field-maybe)
20853 (call-interactively 'org-table-next-row))
20854 ;; when `newline-and-indent' is called within a list, make sure
20855 ;; text moved stays inside the item.
20856 ((and (org-in-item-p) indent)
20857 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20858 (progn
20859 (save-match-data (newline))
20860 (org-indent-line-to (length (match-string 0))))
20861 (let ((ind (org-get-indentation)))
20862 (newline)
20863 (if (org-looking-back org-list-end-re)
20864 (org-indent-line)
20865 (org-indent-line-to ind)))))
20866 ((and org-return-follows-link
20867 (org-at-timestamp-p t)
20868 (not (eq org-ts-what 'after)))
20869 (org-follow-timestamp-link))
20870 ((and org-return-follows-link
20871 (let ((tprop (get-text-property (point) 'face)))
20872 (or (eq tprop 'org-link)
20873 (and (listp tprop) (memq 'org-link tprop)))))
20874 (call-interactively 'org-open-at-point))
20875 ((and (org-at-heading-p)
20876 (looking-at
20877 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20878 (org-show-entry)
20879 (end-of-line 1)
20880 (newline))
20881 (t (if indent (newline-and-indent) (newline))))))
20883 (defun org-return-indent ()
20884 "Goto next table row or insert a newline and indent.
20885 Calls `org-table-next-row' or `newline-and-indent', depending on
20886 context. See the individual commands for more information."
20887 (interactive)
20888 (org-return t))
20890 (defun org-ctrl-c-star ()
20891 "Compute table, or change heading status of lines.
20892 Calls `org-table-recalculate' or `org-toggle-heading',
20893 depending on context."
20894 (interactive)
20895 (cond
20896 ((org-at-table-p)
20897 (call-interactively 'org-table-recalculate))
20899 ;; Convert all lines in region to list items
20900 (call-interactively 'org-toggle-heading))))
20902 (defun org-ctrl-c-minus ()
20903 "Insert separator line in table or modify bullet status of line.
20904 Also turns a plain line or a region of lines into list items.
20905 Calls `org-table-insert-hline', `org-toggle-item', or
20906 `org-cycle-list-bullet', depending on context."
20907 (interactive)
20908 (cond
20909 ((org-at-table-p)
20910 (call-interactively 'org-table-insert-hline))
20911 ((org-region-active-p)
20912 (call-interactively 'org-toggle-item))
20913 ((org-in-item-p)
20914 (call-interactively 'org-cycle-list-bullet))
20916 (call-interactively 'org-toggle-item))))
20918 (defun org-toggle-item (arg)
20919 "Convert headings or normal lines to items, items to normal lines.
20920 If there is no active region, only the current line is considered.
20922 If the first non blank line in the region is a headline, convert
20923 all headlines to items, shifting text accordingly.
20925 If it is an item, convert all items to normal lines.
20927 If it is normal text, change region into a list of items.
20928 With a prefix argument ARG, change the region in a single item."
20929 (interactive "P")
20930 (let ((shift-text
20931 (function
20932 ;; Shift text in current section to IND, from point to END.
20933 ;; The function leaves point to END line.
20934 (lambda (ind end)
20935 (let ((min-i 1000) (end (copy-marker end)))
20936 ;; First determine the minimum indentation (MIN-I) of
20937 ;; the text.
20938 (save-excursion
20939 (catch 'exit
20940 (while (< (point) end)
20941 (let ((i (org-get-indentation)))
20942 (cond
20943 ;; Skip blank lines and inline tasks.
20944 ((looking-at "^[ \t]*$"))
20945 ((looking-at org-outline-regexp-bol))
20946 ;; We can't find less than 0 indentation.
20947 ((zerop i) (throw 'exit (setq min-i 0)))
20948 ((< i min-i) (setq min-i i))))
20949 (forward-line))))
20950 ;; Then indent each line so that a line indented to
20951 ;; MIN-I becomes indented to IND. Ignore blank lines
20952 ;; and inline tasks in the process.
20953 (let ((delta (- ind min-i)))
20954 (while (< (point) end)
20955 (unless (or (looking-at "^[ \t]*$")
20956 (looking-at org-outline-regexp-bol))
20957 (org-indent-line-to (+ (org-get-indentation) delta)))
20958 (forward-line)))))))
20959 (skip-blanks
20960 (function
20961 ;; Return beginning of first non-blank line, starting from
20962 ;; line at POS.
20963 (lambda (pos)
20964 (save-excursion
20965 (goto-char pos)
20966 (skip-chars-forward " \r\t\n")
20967 (point-at-bol)))))
20968 beg end)
20969 ;; Determine boundaries of changes.
20970 (if (org-region-active-p)
20971 (setq beg (funcall skip-blanks (region-beginning))
20972 end (copy-marker (region-end)))
20973 (setq beg (funcall skip-blanks (point-at-bol))
20974 end (copy-marker (point-at-eol))))
20975 ;; Depending on the starting line, choose an action on the text
20976 ;; between BEG and END.
20977 (org-with-limited-levels
20978 (save-excursion
20979 (goto-char beg)
20980 (cond
20981 ;; Case 1. Start at an item: de-itemize. Note that it only
20982 ;; happens when a region is active: `org-ctrl-c-minus'
20983 ;; would call `org-cycle-list-bullet' otherwise.
20984 ((org-at-item-p)
20985 (while (< (point) end)
20986 (when (org-at-item-p)
20987 (skip-chars-forward " \t")
20988 (delete-region (point) (match-end 0)))
20989 (forward-line)))
20990 ;; Case 2. Start at an heading: convert to items.
20991 ((org-at-heading-p)
20992 (let* ((bul (org-list-bullet-string "-"))
20993 (bul-len (length bul))
20994 (done (org-entry-is-done-p))
20995 (todo (org-entry-is-todo-p))
20996 ;; Indentation of the first heading. It should be
20997 ;; relative to the indentation of its parent, if any.
20998 (start-ind (save-excursion
20999 (cond
21000 ((not org-adapt-indentation) 0)
21001 ((not (outline-previous-heading)) 0)
21002 (t (length (match-string 0))))))
21003 ;; Level of first heading. Further headings will be
21004 ;; compared to it to determine hierarchy in the list.
21005 (ref-level (org-reduced-level (org-outline-level))))
21006 (when (or done todo) (org-todo ""))
21007 (while (< (point) end)
21008 (let* ((level (org-reduced-level (org-outline-level)))
21009 (delta (max 0 (- level ref-level))))
21010 ;; If current headline is less indented than the first
21011 ;; one, set it as reference, in order to preserve
21012 ;; subtrees.
21013 (when (< level ref-level) (setq ref-level level))
21014 (replace-match bul t t)
21015 (org-indent-line-to (+ start-ind (* delta bul-len)))
21016 (when (or done todo)
21017 (let* ((struct (org-list-struct))
21018 (old (copy-tree struct)))
21019 (org-list-set-checkbox (line-beginning-position)
21020 struct
21021 (if done "[X]" "[ ]"))
21022 (org-list-write-struct struct
21023 (org-list-parents-alist struct)
21024 old)))
21025 ;; Ensure all text down to END (or SECTION-END) belongs
21026 ;; to the newly created item.
21027 (let ((section-end (save-excursion
21028 (or (outline-next-heading) (point)))))
21029 (forward-line)
21030 (funcall shift-text
21031 (+ start-ind (* (1+ delta) bul-len))
21032 (min end section-end)))))))
21033 ;; Case 3. Normal line with ARG: make the first line of region
21034 ;; an item, and shift indentation of others lines to
21035 ;; set them as item's body.
21036 (arg (let* ((bul (org-list-bullet-string "-"))
21037 (bul-len (length bul))
21038 (ref-ind (org-get-indentation)))
21039 (skip-chars-forward " \t")
21040 (insert bul)
21041 (forward-line)
21042 (while (< (point) end)
21043 ;; Ensure that lines less indented than first one
21044 ;; still get included in item body.
21045 (funcall shift-text
21046 (+ ref-ind bul-len)
21047 (min end (save-excursion (or (outline-next-heading)
21048 (point)))))
21049 (forward-line))))
21050 ;; Case 4. Normal line without ARG: turn each non-item line
21051 ;; into an item.
21053 (while (< (point) end)
21054 (unless (or (org-at-heading-p) (org-at-item-p))
21055 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21056 (replace-match
21057 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21058 (forward-line))))))))
21060 (defun org-toggle-heading (&optional nstars)
21061 "Convert headings to normal text, or items or text to headings.
21062 If there is no active region, only convert the current line.
21064 With a \\[universal-argument] prefix, convert the whole list at
21065 point into heading.
21067 In a region:
21069 - If the first non blank line is a headline, remove the stars
21070 from all headlines in the region.
21072 - If it is a normal line, turn each and every normal line (i.e.,
21073 not an heading or an item) in the region into headings. If you
21074 want to convert only the first line of this region, use one
21075 universal prefix argument.
21077 - If it is a plain list item, turn all plain list items into headings.
21079 When converting a line into a heading, the number of stars is chosen
21080 such that the lines become children of the current entry. However,
21081 when a numeric prefix argument is given, its value determines the
21082 number of stars to add."
21083 (interactive "P")
21084 (let ((skip-blanks
21085 (function
21086 ;; Return beginning of first non-blank line, starting from
21087 ;; line at POS.
21088 (lambda (pos)
21089 (save-excursion
21090 (goto-char pos)
21091 (while (org-at-comment-p) (forward-line))
21092 (skip-chars-forward " \r\t\n")
21093 (point-at-bol)))))
21094 beg end toggled)
21095 ;; Determine boundaries of changes. If a universal prefix has
21096 ;; been given, put the list in a region. If region ends at a bol,
21097 ;; do not consider the last line to be in the region.
21099 (when (and current-prefix-arg (org-at-item-p))
21100 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21101 (org-mark-element))
21103 (if (org-region-active-p)
21104 (setq beg (funcall skip-blanks (region-beginning))
21105 end (copy-marker (save-excursion
21106 (goto-char (region-end))
21107 (if (bolp) (point) (point-at-eol)))))
21108 (setq beg (funcall skip-blanks (point-at-bol))
21109 end (copy-marker (point-at-eol))))
21110 ;; Ensure inline tasks don't count as headings.
21111 (org-with-limited-levels
21112 (save-excursion
21113 (goto-char beg)
21114 (cond
21115 ;; Case 1. Started at an heading: de-star headings.
21116 ((org-at-heading-p)
21117 (while (< (point) end)
21118 (when (org-at-heading-p t)
21119 (looking-at org-outline-regexp) (replace-match "")
21120 (setq toggled t))
21121 (forward-line)))
21122 ;; Case 2. Started at an item: change items into headlines.
21123 ;; One star will be added by `org-list-to-subtree'.
21124 ((org-at-item-p)
21125 (let* ((stars (make-string
21126 ;; subtract the star that will be added again by
21127 ;; `org-list-to-subtree'
21128 (if (numberp nstars) (1- nstars)
21129 (or (org-current-level) 0))
21130 ?*))
21131 (add-stars
21132 (cond (nstars "") ; stars from prefix only
21133 ((equal stars "") "") ; before first heading
21134 (org-odd-levels-only "*") ; inside heading, odd
21135 (t "")))) ; inside heading, oddeven
21136 (while (< (point) end)
21137 (when (org-at-item-p)
21138 ;; Pay attention to cases when region ends before list.
21139 (let* ((struct (org-list-struct))
21140 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21141 (save-restriction
21142 (narrow-to-region (point) list-end)
21143 (insert
21144 (org-list-to-subtree
21145 (org-list-parse-list t)
21146 '(:istart (concat stars add-stars (funcall get-stars depth))
21147 :icount (concat stars add-stars (funcall get-stars depth)))))))
21148 (setq toggled t))
21149 (forward-line))))
21150 ;; Case 3. Started at normal text: make every line an heading,
21151 ;; skipping headlines and items.
21152 (t (let* ((stars
21153 (make-string
21154 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21155 (add-stars
21156 (cond (nstars "") ; stars from prefix only
21157 ((equal stars "") "*") ; before first heading
21158 (org-odd-levels-only "**") ; inside heading, odd
21159 (t "*"))) ; inside heading, oddeven
21160 (rpl (concat stars add-stars " "))
21161 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21162 (while (< (point) (if (equal nstars '(4)) lend end))
21163 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21164 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21165 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21166 (forward-line)))))))
21167 (unless toggled (message "Cannot toggle heading from here"))))
21169 (defun org-meta-return (&optional arg)
21170 "Insert a new heading or wrap a region in a table.
21171 Calls `org-insert-heading' or `org-table-wrap-region', depending
21172 on context. See the individual commands for more information."
21173 (interactive "P")
21174 (org-check-before-invisible-edit 'insert)
21175 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21176 (let* ((element (org-element-at-point))
21177 (type (org-element-type element)))
21178 (when (eq type 'table-row)
21179 (setq element (org-element-property :parent element))
21180 (setq type 'table))
21181 (if (and (eq type 'table)
21182 (eq (org-element-property :type element) 'org)
21183 (>= (point) (org-element-property :contents-begin element))
21184 (< (point) (org-element-property :contents-end element)))
21185 (call-interactively 'org-table-wrap-region)
21186 (call-interactively 'org-insert-heading)))))
21188 ;;; Menu entries
21190 (defsubst org-in-subtree-not-table-p ()
21191 "Are we in a subtree and not in a table?"
21192 (and (not (org-before-first-heading-p))
21193 (not (org-at-table-p))))
21195 ;; Define the Org-mode menus
21196 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21197 '("Tbl"
21198 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21199 ["Next Field" org-cycle (org-at-table-p)]
21200 ["Previous Field" org-shifttab (org-at-table-p)]
21201 ["Next Row" org-return (org-at-table-p)]
21202 "--"
21203 ["Blank Field" org-table-blank-field (org-at-table-p)]
21204 ["Edit Field" org-table-edit-field (org-at-table-p)]
21205 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21206 "--"
21207 ("Column"
21208 ["Move Column Left" org-metaleft (org-at-table-p)]
21209 ["Move Column Right" org-metaright (org-at-table-p)]
21210 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21211 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21212 ("Row"
21213 ["Move Row Up" org-metaup (org-at-table-p)]
21214 ["Move Row Down" org-metadown (org-at-table-p)]
21215 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21216 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21217 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21218 "--"
21219 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21220 ("Rectangle"
21221 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21222 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21223 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21224 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21225 "--"
21226 ("Calculate"
21227 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21228 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21229 ["Edit Formulas" org-edit-special (org-at-table-p)]
21230 "--"
21231 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21232 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21233 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21234 "--"
21235 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21236 "--"
21237 ["Sum Column/Rectangle" org-table-sum
21238 (or (org-at-table-p) (org-region-active-p))]
21239 ["Which Column?" org-table-current-column (org-at-table-p)])
21240 ["Debug Formulas"
21241 org-table-toggle-formula-debugger
21242 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21243 ["Show Col/Row Numbers"
21244 org-table-toggle-coordinate-overlays
21245 :style toggle
21246 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21247 "--"
21248 ["Create" org-table-create (and (not (org-at-table-p))
21249 org-enable-table-editor)]
21250 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21251 ["Import from File" org-table-import (not (org-at-table-p))]
21252 ["Export to File" org-table-export (org-at-table-p)]
21253 "--"
21254 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21255 "--"
21256 ("Plot"
21257 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21258 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21260 (easy-menu-define org-org-menu org-mode-map "Org menu"
21261 '("Org"
21262 ("Show/Hide"
21263 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21264 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21265 ["Sparse Tree..." org-sparse-tree t]
21266 ["Reveal Context" org-reveal t]
21267 ["Show All" show-all t]
21268 "--"
21269 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21270 "--"
21271 ["New Heading" org-insert-heading t]
21272 ("Navigate Headings"
21273 ["Up" outline-up-heading t]
21274 ["Next" outline-next-visible-heading t]
21275 ["Previous" outline-previous-visible-heading t]
21276 ["Next Same Level" outline-forward-same-level t]
21277 ["Previous Same Level" outline-backward-same-level t]
21278 "--"
21279 ["Jump" org-goto t])
21280 ("Edit Structure"
21281 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21282 "--"
21283 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21284 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21285 "--"
21286 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21287 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21288 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21289 "--"
21290 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21291 "--"
21292 ["Copy visible text" org-copy-visible t]
21293 "--"
21294 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21295 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21296 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21297 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21298 "--"
21299 ["Sort Region/Children" org-sort t]
21300 "--"
21301 ["Convert to odd levels" org-convert-to-odd-levels t]
21302 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21303 ("Editing"
21304 ["Emphasis..." org-emphasize t]
21305 ["Edit Source Example" org-edit-special t]
21306 "--"
21307 ["Footnote new/jump" org-footnote-action t]
21308 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21309 ("Archive"
21310 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21311 "--"
21312 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21313 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21314 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21316 "--"
21317 ("Hyperlinks"
21318 ["Store Link (Global)" org-store-link t]
21319 ["Find existing link to here" org-occur-link-in-agenda-files t]
21320 ["Insert Link" org-insert-link t]
21321 ["Follow Link" org-open-at-point t]
21322 "--"
21323 ["Next link" org-next-link t]
21324 ["Previous link" org-previous-link t]
21325 "--"
21326 ["Descriptive Links"
21327 org-toggle-link-display
21328 :style radio
21329 :selected org-descriptive-links
21331 ["Literal Links"
21332 org-toggle-link-display
21333 :style radio
21334 :selected (not org-descriptive-links)])
21335 "--"
21336 ("TODO Lists"
21337 ["TODO/DONE/-" org-todo t]
21338 ("Select keyword"
21339 ["Next keyword" org-shiftright (org-at-heading-p)]
21340 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21341 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21342 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21343 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21344 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21345 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21346 "--"
21347 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21348 :selected org-enforce-todo-dependencies :style toggle :active t]
21349 "Settings for tree at point"
21350 ["Do Children sequentially" org-toggle-ordered-property :style radio
21351 :selected (org-entry-get nil "ORDERED")
21352 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21353 ["Do Children parallel" org-toggle-ordered-property :style radio
21354 :selected (not (org-entry-get nil "ORDERED"))
21355 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21356 "--"
21357 ["Set Priority" org-priority t]
21358 ["Priority Up" org-shiftup t]
21359 ["Priority Down" org-shiftdown t]
21360 "--"
21361 ["Get news from all feeds" org-feed-update-all t]
21362 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21363 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21364 ("TAGS and Properties"
21365 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21366 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21367 "--"
21368 ["Set property" org-set-property (not (org-before-first-heading-p))]
21369 ["Column view of properties" org-columns t]
21370 ["Insert Column View DBlock" org-insert-columns-dblock t])
21371 ("Dates and Scheduling"
21372 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21373 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21374 ("Change Date"
21375 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21376 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21377 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21378 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21379 ["Compute Time Range" org-evaluate-time-range t]
21380 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21381 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21382 "--"
21383 ["Custom time format" org-toggle-time-stamp-overlays
21384 :style radio :selected org-display-custom-times]
21385 "--"
21386 ["Goto Calendar" org-goto-calendar t]
21387 ["Date from Calendar" org-date-from-calendar t]
21388 "--"
21389 ["Start/Restart Timer" org-timer-start t]
21390 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21391 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21392 ["Insert Timer String" org-timer t]
21393 ["Insert Timer Item" org-timer-item t])
21394 ("Logging work"
21395 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21396 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21397 ["Clock out" org-clock-out t]
21398 ["Clock cancel" org-clock-cancel t]
21399 "--"
21400 ["Mark as default task" org-clock-mark-default-task t]
21401 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21402 ["Goto running clock" org-clock-goto t]
21403 "--"
21404 ["Display times" org-clock-display t]
21405 ["Create clock table" org-clock-report t]
21406 "--"
21407 ["Record DONE time"
21408 (progn (setq org-log-done (not org-log-done))
21409 (message "Switching to %s will %s record a timestamp"
21410 (car org-done-keywords)
21411 (if org-log-done "automatically" "not")))
21412 :style toggle :selected org-log-done])
21413 "--"
21414 ["Agenda Command..." org-agenda t]
21415 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21416 ("File List for Agenda")
21417 ("Special views current file"
21418 ["TODO Tree" org-show-todo-tree t]
21419 ["Check Deadlines" org-check-deadlines t]
21420 ["Timeline" org-timeline t]
21421 ["Tags/Property tree" org-match-sparse-tree t])
21422 "--"
21423 ["Export/Publish..." org-export-dispatch t]
21424 ("LaTeX"
21425 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21426 :selected org-cdlatex-mode]
21427 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21428 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21429 ["Modify math symbol" org-cdlatex-math-modify
21430 (org-inside-LaTeX-fragment-p)]
21431 ["Insert citation" org-reftex-citation t]
21432 "--"
21433 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21434 "--"
21435 ("MobileOrg"
21436 ["Push Files and Views" org-mobile-push t]
21437 ["Get Captured and Flagged" org-mobile-pull t]
21438 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21439 "--"
21440 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21441 "--"
21442 ("Documentation"
21443 ["Show Version" org-version t]
21444 ["Info Documentation" org-info t])
21445 ("Customize"
21446 ["Browse Org Group" org-customize t]
21447 "--"
21448 ["Expand This Menu" org-create-customize-menu
21449 (fboundp 'customize-menu-create)])
21450 ["Send bug report" org-submit-bug-report t]
21451 "--"
21452 ("Refresh/Reload"
21453 ["Refresh setup current buffer" org-mode-restart t]
21454 ["Reload Org (after update)" org-reload t]
21455 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21458 (defun org-info (&optional node)
21459 "Read documentation for Org-mode in the info system.
21460 With optional NODE, go directly to that node."
21461 (interactive)
21462 (info (format "(org)%s" (or node ""))))
21464 ;;;###autoload
21465 (defun org-submit-bug-report ()
21466 "Submit a bug report on Org-mode via mail.
21468 Don't hesitate to report any problems or inaccurate documentation.
21470 If you don't have setup sending mail from (X)Emacs, please copy the
21471 output buffer into your mail program, as it gives us important
21472 information about your Org-mode version and configuration."
21473 (interactive)
21474 (require 'reporter)
21475 (org-load-modules-maybe)
21476 (org-require-autoloaded-modules)
21477 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21478 (reporter-submit-bug-report
21479 "emacs-orgmode@gnu.org"
21480 (org-version nil 'full)
21481 (let (list)
21482 (save-window-excursion
21483 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21484 (delete-other-windows)
21485 (erase-buffer)
21486 (insert "You are about to submit a bug report to the Org-mode mailing list.
21488 We would like to add your full Org-mode and Outline configuration to the
21489 bug report. This greatly simplifies the work of the maintainer and
21490 other experts on the mailing list.
21492 HOWEVER, some variables you have customized may contain private
21493 information. The names of customers, colleagues, or friends, might
21494 appear in the form of file names, tags, todo states, or search strings.
21495 If you answer yes to the prompt, you might want to check and remove
21496 such private information before sending the email.")
21497 (add-text-properties (point-min) (point-max) '(face org-warning))
21498 (when (yes-or-no-p "Include your Org-mode configuration ")
21499 (mapatoms
21500 (lambda (v)
21501 (and (boundp v)
21502 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21503 (or (and (symbol-value v)
21504 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21505 (and
21506 (get v 'custom-type) (get v 'standard-value)
21507 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21508 (push v list)))))
21509 (kill-buffer (get-buffer "*Warn about privacy*"))
21510 list))
21511 nil nil
21512 "Remember to cover the basics, that is, what you expected to happen and
21513 what in fact did happen. You don't know how to make a good report? See
21515 http://orgmode.org/manual/Feedback.html#Feedback
21517 Your bug report will be posted to the Org-mode mailing list.
21518 ------------------------------------------------------------------------")
21519 (save-excursion
21520 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21521 (replace-match "\\1Bug: \\3 [\\2]")))))
21524 (defun org-install-agenda-files-menu ()
21525 (let ((bl (buffer-list)))
21526 (save-excursion
21527 (while bl
21528 (set-buffer (pop bl))
21529 (if (derived-mode-p 'org-mode) (setq bl nil)))
21530 (when (derived-mode-p 'org-mode)
21531 (easy-menu-change
21532 '("Org") "File List for Agenda"
21533 (append
21534 (list
21535 ["Edit File List" (org-edit-agenda-file-list) t]
21536 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21537 ["Remove Current File from List" org-remove-file t]
21538 ["Cycle through agenda files" org-cycle-agenda-files t]
21539 ["Occur in all agenda files" org-occur-in-agenda-files t]
21540 "--")
21541 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21543 ;;;; Documentation
21545 (defun org-require-autoloaded-modules ()
21546 (interactive)
21547 (mapc 'require
21548 '(org-agenda org-archive org-attach org-clock org-colview org-id
21549 org-table org-timer)))
21551 ;;;###autoload
21552 (defun org-reload (&optional uncompiled)
21553 "Reload all org lisp files.
21554 With prefix arg UNCOMPILED, load the uncompiled versions."
21555 (interactive "P")
21556 (require 'loadhist)
21557 (let* ((org-dir (org-find-library-dir "org"))
21558 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21559 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21560 (remove-re (mapconcat 'identity
21561 (mapcar (lambda (f) (concat "^" f "$"))
21562 (list (if (featurep 'xemacs)
21563 "org-colview"
21564 "org-colview-xemacs")
21565 "org" "org-loaddefs" "org-version"))
21566 "\\|"))
21567 (feats (delete-dups
21568 (mapcar 'file-name-sans-extension
21569 (mapcar 'file-name-nondirectory
21570 (delq nil
21571 (mapcar 'feature-file
21572 features))))))
21573 (lfeat (append
21574 (sort
21575 (setq feats
21576 (delq nil (mapcar
21577 (lambda (f)
21578 (if (and (string-match feature-re f)
21579 (not (string-match remove-re f)))
21580 f nil))
21581 feats)))
21582 'string-lessp)
21583 (list "org-version" "org")))
21584 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21585 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21586 load-uncore load-misses)
21587 (setq load-misses
21588 (delq 't
21589 (mapcar (lambda (f)
21590 (or (org-load-noerror-mustsuffix (concat org-dir f))
21591 (and (string= org-dir contrib-dir)
21592 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21593 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21594 (add-to-list 'load-uncore f 'append)
21597 lfeat)))
21598 (if load-uncore
21599 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21600 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21601 (if load-misses
21602 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21603 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21604 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21606 ;;;###autoload
21607 (defun org-customize ()
21608 "Call the customize function with org as argument."
21609 (interactive)
21610 (org-load-modules-maybe)
21611 (org-require-autoloaded-modules)
21612 (customize-browse 'org))
21614 (defun org-create-customize-menu ()
21615 "Create a full customization menu for Org-mode, insert it into the menu."
21616 (interactive)
21617 (org-load-modules-maybe)
21618 (org-require-autoloaded-modules)
21619 (if (fboundp 'customize-menu-create)
21620 (progn
21621 (easy-menu-change
21622 '("Org") "Customize"
21623 `(["Browse Org group" org-customize t]
21624 "--"
21625 ,(customize-menu-create 'org)
21626 ["Set" Custom-set t]
21627 ["Save" Custom-save t]
21628 ["Reset to Current" Custom-reset-current t]
21629 ["Reset to Saved" Custom-reset-saved t]
21630 ["Reset to Standard Settings" Custom-reset-standard t]))
21631 (message "\"Org\"-menu now contains full customization menu"))
21632 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21634 ;;;; Miscellaneous stuff
21636 ;;; Generally useful functions
21638 (defsubst org-get-at-eol (property n)
21639 "Get text property PROPERTY at the end of line less N characters."
21640 (get-text-property (- (point-at-eol) n) property))
21642 (defun org-find-text-property-in-string (prop s)
21643 "Return the first non-nil value of property PROP in string S."
21644 (or (get-text-property 0 prop s)
21645 (get-text-property (or (next-single-property-change 0 prop s) 0)
21646 prop s)))
21648 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21649 "Display the given MESSAGE as a warning."
21650 (if (fboundp 'display-warning)
21651 (display-warning 'org message
21652 (if (featurep 'xemacs) 'warning :warning))
21653 (let ((buf (get-buffer-create "*Org warnings*")))
21654 (with-current-buffer buf
21655 (goto-char (point-max))
21656 (insert "Warning (Org): " message)
21657 (unless (bolp)
21658 (newline)))
21659 (display-buffer buf)
21660 (sit-for 0))))
21662 (defun org-eval (form)
21663 "Eval FORM and return result."
21664 (condition-case error
21665 (eval form)
21666 (error (format "%%![Error: %s]" error))))
21668 (defun org-in-clocktable-p ()
21669 "Check if the cursor is in a clocktable."
21670 (let ((pos (point)) start)
21671 (save-excursion
21672 (end-of-line 1)
21673 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21674 (setq start (match-beginning 0))
21675 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21676 (>= (match-end 0) pos)
21677 start))))
21679 (defun org-in-verbatim-emphasis ()
21680 (save-match-data
21681 (and (org-in-regexp org-emph-re 2)
21682 (>= (point) (match-beginning 3))
21683 (<= (point) (match-end 4))
21684 (member (match-string 3) '("=" "~")))))
21686 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21687 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21688 (if (and marker (marker-buffer marker)
21689 (buffer-live-p (marker-buffer marker)))
21690 (progn
21691 (org-pop-to-buffer-same-window (marker-buffer marker))
21692 (if (or (> marker (point-max)) (< marker (point-min)))
21693 (widen))
21694 (goto-char marker)
21695 (org-show-context 'org-goto))
21696 (if bookmark
21697 (bookmark-jump bookmark)
21698 (error "Cannot find location"))))
21700 (defun org-quote-csv-field (s)
21701 "Quote field for inclusion in CSV material."
21702 (if (string-match "[\",]" s)
21703 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21706 (defun org-force-self-insert (N)
21707 "Needed to enforce self-insert under remapping."
21708 (interactive "p")
21709 (self-insert-command N))
21711 (defun org-string-width (s)
21712 "Compute width of string, ignoring invisible characters.
21713 This ignores character with invisibility property `org-link', and also
21714 characters with property `org-cwidth', because these will become invisible
21715 upon the next fontification round."
21716 (let (b l)
21717 (when (or (eq t buffer-invisibility-spec)
21718 (assq 'org-link buffer-invisibility-spec))
21719 (while (setq b (text-property-any 0 (length s)
21720 'invisible 'org-link s))
21721 (setq s (concat (substring s 0 b)
21722 (substring s (or (next-single-property-change
21723 b 'invisible s) (length s)))))))
21724 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21725 (setq s (concat (substring s 0 b)
21726 (substring s (or (next-single-property-change
21727 b 'org-cwidth s) (length s))))))
21728 (setq l (string-width s) b -1)
21729 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21730 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21733 (defun org-shorten-string (s maxlength)
21734 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21735 If the string is shorter or has length MAXLENGTH, just return the
21736 original string. If it is longer, the functions finds a space in the
21737 string, breaks this string off at that locations and adds three dots
21738 as ellipsis. Including the ellipsis, the string will not be longer
21739 than MAXLENGTH. If finding a good breaking point in the string does
21740 not work, the string is just chopped off in the middle of a word
21741 if necessary."
21742 (if (<= (length s) maxlength)
21744 (let* ((n (max (- maxlength 4) 1))
21745 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21746 (if (string-match re s)
21747 (concat (match-string 1 s) "...")
21748 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21750 (defun org-get-indentation (&optional line)
21751 "Get the indentation of the current line, interpreting tabs.
21752 When LINE is given, assume it represents a line and compute its indentation."
21753 (if line
21754 (if (string-match "^ *" (org-remove-tabs line))
21755 (match-end 0))
21756 (save-excursion
21757 (beginning-of-line 1)
21758 (skip-chars-forward " \t")
21759 (current-column))))
21761 (defun org-get-string-indentation (s)
21762 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21763 (let ((n -1) (i 0) (w tab-width) c)
21764 (catch 'exit
21765 (while (< (setq n (1+ n)) (length s))
21766 (setq c (aref s n))
21767 (cond ((= c ?\ ) (setq i (1+ i)))
21768 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21769 (t (throw 'exit t)))))
21772 (defun org-remove-tabs (s &optional width)
21773 "Replace tabulators in S with spaces.
21774 Assumes that s is a single line, starting in column 0."
21775 (setq width (or width tab-width))
21776 (while (string-match "\t" s)
21777 (setq s (replace-match
21778 (make-string
21779 (- (* width (/ (+ (match-beginning 0) width) width))
21780 (match-beginning 0)) ?\ )
21781 t t s)))
21784 (defun org-fix-indentation (line ind)
21785 "Fix indentation in LINE.
21786 IND is a cons cell with target and minimum indentation.
21787 If the current indentation in LINE is smaller than the minimum,
21788 leave it alone. If it is larger than ind, set it to the target."
21789 (let* ((l (org-remove-tabs line))
21790 (i (org-get-indentation l))
21791 (i1 (car ind)) (i2 (cdr ind)))
21792 (if (>= i i2) (setq l (substring line i2)))
21793 (if (> i1 0)
21794 (concat (make-string i1 ?\ ) l)
21795 l)))
21797 (defun org-remove-indentation (code &optional n)
21798 "Remove the maximum common indentation from the lines in CODE.
21799 N may optionally be the number of spaces to remove."
21800 (with-temp-buffer
21801 (insert code)
21802 (org-do-remove-indentation n)
21803 (buffer-string)))
21805 (defun org-do-remove-indentation (&optional n)
21806 "Remove the maximum common indentation from the buffer."
21807 (untabify (point-min) (point-max))
21808 (let ((min 10000) re)
21809 (if n
21810 (setq min n)
21811 (goto-char (point-min))
21812 (while (re-search-forward "^ *[^ \n]" nil t)
21813 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21814 (unless (or (= min 0) (= min 10000))
21815 (setq re (format "^ \\{%d\\}" min))
21816 (goto-char (point-min))
21817 (while (re-search-forward re nil t)
21818 (replace-match "")
21819 (end-of-line 1))
21820 min)))
21822 (defun org-fill-template (template alist)
21823 "Find each %key of ALIST in TEMPLATE and replace it."
21824 (let ((case-fold-search nil)
21825 entry key value)
21826 (setq alist (sort (copy-sequence alist)
21827 (lambda (a b) (< (length (car a)) (length (car b))))))
21828 (while (setq entry (pop alist))
21829 (setq template
21830 (replace-regexp-in-string
21831 (concat "%" (regexp-quote (car entry)))
21832 (or (cdr entry) "") template t t)))
21833 template))
21835 (defun org-base-buffer (buffer)
21836 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21837 (if (not buffer)
21838 buffer
21839 (or (buffer-base-buffer buffer)
21840 buffer)))
21842 (defun org-wrap (string &optional width lines)
21843 "Wrap string to either a number of lines, or a width in characters.
21844 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21845 that costs. If there is a word longer than WIDTH, the text is actually
21846 wrapped to the length of that word.
21847 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21848 many lines, whatever width that takes.
21849 The return value is a list of lines, without newlines at the end."
21850 (let* ((words (org-split-string string "[ \t\n]+"))
21851 (maxword (apply 'max (mapcar 'org-string-width words)))
21852 w ll)
21853 (cond (width
21854 (org-do-wrap words (max maxword width)))
21855 (lines
21856 (setq w maxword)
21857 (setq ll (org-do-wrap words maxword))
21858 (if (<= (length ll) lines)
21860 (setq ll words)
21861 (while (> (length ll) lines)
21862 (setq w (1+ w))
21863 (setq ll (org-do-wrap words w)))
21864 ll))
21865 (t (error "Cannot wrap this")))))
21867 (defun org-do-wrap (words width)
21868 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21869 (let (lines line)
21870 (while words
21871 (setq line (pop words))
21872 (while (and words (< (+ (length line) (length (car words))) width))
21873 (setq line (concat line " " (pop words))))
21874 (setq lines (push line lines)))
21875 (nreverse lines)))
21877 (defun org-split-string (string &optional separators)
21878 "Splits STRING into substrings at SEPARATORS.
21879 No empty strings are returned if there are matches at the beginning
21880 and end of string."
21881 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21882 (start 0)
21883 notfirst
21884 (list nil))
21885 (while (and (string-match rexp string
21886 (if (and notfirst
21887 (= start (match-beginning 0))
21888 (< start (length string)))
21889 (1+ start) start))
21890 (< (match-beginning 0) (length string)))
21891 (setq notfirst t)
21892 (or (eq (match-beginning 0) 0)
21893 (and (eq (match-beginning 0) (match-end 0))
21894 (eq (match-beginning 0) start))
21895 (setq list
21896 (cons (substring string start (match-beginning 0))
21897 list)))
21898 (setq start (match-end 0)))
21899 (or (eq start (length string))
21900 (setq list
21901 (cons (substring string start)
21902 list)))
21903 (nreverse list)))
21905 (defun org-quote-vert (s)
21906 "Replace \"|\" with \"\\vert\"."
21907 (while (string-match "|" s)
21908 (setq s (replace-match "\\vert" t t s)))
21911 (defun org-uuidgen-p (s)
21912 "Is S an ID created by UUIDGEN?"
21913 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21915 (defun org-in-src-block-p (&optional inside)
21916 "Whether point is in a code source block.
21917 When INSIDE is non-nil, don't consider we are within a src block
21918 when point is at #+BEGIN_SRC or #+END_SRC."
21919 (let ((case-fold-search t) ov)
21920 (or (and (eq (get-char-property (point) 'src-block) t))
21921 (and (not inside)
21922 (save-match-data
21923 (save-excursion
21924 (beginning-of-line)
21925 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21927 (defun org-context ()
21928 "Return a list of contexts of the current cursor position.
21929 If several contexts apply, all are returned.
21930 Each context entry is a list with a symbol naming the context, and
21931 two positions indicating start and end of the context. Possible
21932 contexts are:
21934 :headline anywhere in a headline
21935 :headline-stars on the leading stars in a headline
21936 :todo-keyword on a TODO keyword (including DONE) in a headline
21937 :tags on the TAGS in a headline
21938 :priority on the priority cookie in a headline
21939 :item on the first line of a plain list item
21940 :item-bullet on the bullet/number of a plain list item
21941 :checkbox on the checkbox in a plain list item
21942 :table in an org-mode table
21943 :table-special on a special filed in a table
21944 :table-table in a table.el table
21945 :clocktable in a clocktable
21946 :src-block in a source block
21947 :link on a hyperlink
21948 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21949 :target on a <<target>>
21950 :radio-target on a <<<radio-target>>>
21951 :latex-fragment on a LaTeX fragment
21952 :latex-preview on a LaTeX fragment with overlaid preview image
21954 This function expects the position to be visible because it uses font-lock
21955 faces as a help to recognize the following contexts: :table-special, :link,
21956 and :keyword."
21957 (let* ((f (get-text-property (point) 'face))
21958 (faces (if (listp f) f (list f)))
21959 (case-fold-search t)
21960 (p (point)) clist o)
21961 ;; First the large context
21962 (cond
21963 ((org-at-heading-p t)
21964 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21965 (when (progn
21966 (beginning-of-line 1)
21967 (looking-at org-todo-line-tags-regexp))
21968 (push (org-point-in-group p 1 :headline-stars) clist)
21969 (push (org-point-in-group p 2 :todo-keyword) clist)
21970 (push (org-point-in-group p 4 :tags) clist))
21971 (goto-char p)
21972 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21973 (if (looking-at "\\[#[A-Z0-9]\\]")
21974 (push (org-point-in-group p 0 :priority) clist)))
21976 ((org-at-item-p)
21977 (push (org-point-in-group p 2 :item-bullet) clist)
21978 (push (list :item (point-at-bol)
21979 (save-excursion (org-end-of-item) (point)))
21980 clist)
21981 (and (org-at-item-checkbox-p)
21982 (push (org-point-in-group p 0 :checkbox) clist)))
21984 ((org-at-table-p)
21985 (push (list :table (org-table-begin) (org-table-end)) clist)
21986 (if (memq 'org-formula faces)
21987 (push (list :table-special
21988 (previous-single-property-change p 'face)
21989 (next-single-property-change p 'face)) clist)))
21990 ((org-at-table-p 'any)
21991 (push (list :table-table) clist)))
21992 (goto-char p)
21994 (let ((case-fold-search t))
21995 ;; New the "medium" contexts: clocktables, source blocks
21996 (cond ((org-in-clocktable-p)
21997 (push (list :clocktable
21998 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21999 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22000 (match-beginning 1))
22001 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22002 (match-end 0))) clist))
22003 ((org-in-src-block-p)
22004 (push (list :src-block
22005 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22006 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22007 (match-beginning 1))
22008 (and (search-forward "#+END_SRC" nil t)
22009 (match-beginning 0))) clist))))
22010 (goto-char p)
22012 ;; Now the small context
22013 (cond
22014 ((org-at-timestamp-p)
22015 (push (org-point-in-group p 0 :timestamp) clist))
22016 ((memq 'org-link faces)
22017 (push (list :link
22018 (previous-single-property-change p 'face)
22019 (next-single-property-change p 'face)) clist))
22020 ((memq 'org-special-keyword faces)
22021 (push (list :keyword
22022 (previous-single-property-change p 'face)
22023 (next-single-property-change p 'face)) clist))
22024 ((org-at-target-p)
22025 (push (org-point-in-group p 0 :target) clist)
22026 (goto-char (1- (match-beginning 0)))
22027 (if (looking-at org-radio-target-regexp)
22028 (push (org-point-in-group p 0 :radio-target) clist))
22029 (goto-char p))
22030 ((setq o (car (delq nil
22031 (mapcar
22032 (lambda (x)
22033 (if (memq x org-latex-fragment-image-overlays) x))
22034 (overlays-at (point))))))
22035 (push (list :latex-fragment
22036 (overlay-start o) (overlay-end o)) clist)
22037 (push (list :latex-preview
22038 (overlay-start o) (overlay-end o)) clist))
22039 ((org-inside-LaTeX-fragment-p)
22040 ;; FIXME: positions wrong.
22041 (push (list :latex-fragment (point) (point)) clist)))
22043 (setq clist (nreverse (delq nil clist)))
22044 clist))
22046 ;; FIXME: Compare with at-regexp-p Do we need both?
22047 (defun org-in-regexp (re &optional nlines visually)
22048 "Check if point is inside a match of regexp.
22049 Normally only the current line is checked, but you can include NLINES extra
22050 lines both before and after point into the search.
22051 If VISUALLY is set, require that the cursor is not after the match but
22052 really on, so that the block visually is on the match."
22053 (catch 'exit
22054 (let ((pos (point))
22055 (eol (point-at-eol (+ 1 (or nlines 0))))
22056 (inc (if visually 1 0)))
22057 (save-excursion
22058 (beginning-of-line (- 1 (or nlines 0)))
22059 (while (re-search-forward re eol t)
22060 (if (and (<= (match-beginning 0) pos)
22061 (>= (+ inc (match-end 0)) pos))
22062 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22064 (defun org-at-regexp-p (regexp)
22065 "Is point inside a match of REGEXP in the current line?"
22066 (catch 'exit
22067 (save-excursion
22068 (let ((pos (point)) (end (point-at-eol)))
22069 (beginning-of-line 1)
22070 (while (re-search-forward regexp end t)
22071 (if (and (<= (match-beginning 0) pos)
22072 (>= (match-end 0) pos))
22073 (throw 'exit t)))
22074 nil))))
22076 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22077 "Non-nil when point is between matches of START-RE and END-RE.
22079 Also return a non-nil value when point is on one of the matches.
22081 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22082 buffer positions. Default values are the positions of headlines
22083 surrounding the point.
22085 The functions returns a cons cell whose car (resp. cdr) is the
22086 position before START-RE (resp. after END-RE)."
22087 (save-match-data
22088 (let ((pos (point))
22089 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22090 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22091 beg end)
22092 (save-excursion
22093 ;; Point is on a block when on START-RE or if START-RE can be
22094 ;; found before it...
22095 (and (or (org-at-regexp-p start-re)
22096 (re-search-backward start-re limit-up t))
22097 (setq beg (match-beginning 0))
22098 ;; ... and END-RE after it...
22099 (goto-char (match-end 0))
22100 (re-search-forward end-re limit-down t)
22101 (> (setq end (match-end 0)) pos)
22102 ;; ... without another START-RE in-between.
22103 (goto-char (match-beginning 0))
22104 (not (re-search-backward start-re (1+ beg) t))
22105 ;; Return value.
22106 (cons beg end))))))
22108 (defun org-in-block-p (names)
22109 "Non-nil when point belongs to a block whose name belongs to NAMES.
22111 NAMES is a list of strings containing names of blocks.
22113 Return first block name matched, or nil. Beware that in case of
22114 nested blocks, the returned name may not belong to the closest
22115 block from point."
22116 (save-match-data
22117 (catch 'exit
22118 (let ((case-fold-search t)
22119 (lim-up (save-excursion (outline-previous-heading)))
22120 (lim-down (save-excursion (outline-next-heading))))
22121 (mapc (lambda (name)
22122 (let ((n (regexp-quote name)))
22123 (when (org-between-regexps-p
22124 (concat "^[ \t]*#\\+begin_" n)
22125 (concat "^[ \t]*#\\+end_" n)
22126 lim-up lim-down)
22127 (throw 'exit n))))
22128 names))
22129 nil)))
22131 (defun org-in-drawer-p ()
22132 "Non-nil if point is within a drawer.
22133 If point is within a drawer, return it, as parsed data."
22134 (let ((element (save-match-data (org-element-at-point))))
22135 (while (and element (not (memq (org-element-type element)
22136 '(drawer property-drawer))))
22137 (setq element (org-element-property :parent element)))
22138 element))
22140 (defun org-occur-in-agenda-files (regexp &optional nlines)
22141 "Call `multi-occur' with buffers for all agenda files."
22142 (interactive "sOrg-files matching: \np")
22143 (let* ((files (org-agenda-files))
22144 (tnames (mapcar 'file-truename files))
22145 (extra org-agenda-text-search-extra-files)
22147 (when (eq (car extra) 'agenda-archives)
22148 (setq extra (cdr extra))
22149 (setq files (org-add-archive-files files)))
22150 (while (setq f (pop extra))
22151 (unless (member (file-truename f) tnames)
22152 (add-to-list 'files f 'append)
22153 (add-to-list 'tnames (file-truename f) 'append)))
22154 (multi-occur
22155 (mapcar (lambda (x)
22156 (with-current-buffer
22157 (or (get-file-buffer x) (find-file-noselect x))
22158 (widen)
22159 (current-buffer)))
22160 files)
22161 regexp)))
22163 (if (boundp 'occur-mode-find-occurrence-hook)
22164 ;; Emacs 23
22165 (add-hook 'occur-mode-find-occurrence-hook
22166 (lambda ()
22167 (when (derived-mode-p 'org-mode)
22168 (org-reveal))))
22169 ;; Emacs 22
22170 (defadvice occur-mode-goto-occurrence
22171 (after org-occur-reveal activate)
22172 (and (derived-mode-p 'org-mode) (org-reveal)))
22173 (defadvice occur-mode-goto-occurrence-other-window
22174 (after org-occur-reveal activate)
22175 (and (derived-mode-p 'org-mode) (org-reveal)))
22176 (defadvice occur-mode-display-occurrence
22177 (after org-occur-reveal activate)
22178 (when (derived-mode-p 'org-mode)
22179 (let ((pos (occur-mode-find-occurrence)))
22180 (with-current-buffer (marker-buffer pos)
22181 (save-excursion
22182 (goto-char pos)
22183 (org-reveal)))))))
22185 (defun org-occur-link-in-agenda-files ()
22186 "Create a link and search for it in the agendas.
22187 The link is not stored in `org-stored-links', it is just created
22188 for the search purpose."
22189 (interactive)
22190 (let ((link (condition-case nil
22191 (org-store-link nil)
22192 (error "Unable to create a link to here"))))
22193 (org-occur-in-agenda-files (regexp-quote link))))
22195 (defun org-reverse-string (string)
22196 "Return the reverse of STRING."
22197 (apply 'string (reverse (string-to-list string))))
22199 ;; defsubst org-uniquify must be defined before first use
22201 (defun org-uniquify-alist (alist)
22202 "Merge elements of ALIST with the same key.
22204 For example, in this alist:
22206 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22207 => '((a 1 3) (b 2))
22209 merge (a 1) and (a 3) into (a 1 3).
22211 The function returns the new ALIST."
22212 (let (rtn)
22213 (mapc
22214 (lambda (e)
22215 (let (n)
22216 (if (not (assoc (car e) rtn))
22217 (push e rtn)
22218 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22219 (setq rtn (assq-delete-all (car e) rtn))
22220 (push n rtn))))
22221 alist)
22222 rtn))
22224 (defun org-delete-all (elts list)
22225 "Remove all elements in ELTS from LIST."
22226 (while elts
22227 (setq list (delete (pop elts) list)))
22228 list)
22230 (defun org-count (cl-item cl-seq)
22231 "Count the number of occurrences of ITEM in SEQ.
22232 Taken from `count' in cl-seq.el with all keyword arguments removed."
22233 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22234 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22235 (while (< cl-start cl-end)
22236 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22237 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22238 (setq cl-start (1+ cl-start)))
22239 cl-count))
22241 (defun org-remove-if (predicate seq)
22242 "Remove everything from SEQ that fulfills PREDICATE."
22243 (let (res e)
22244 (while seq
22245 (setq e (pop seq))
22246 (if (not (funcall predicate e)) (push e res)))
22247 (nreverse res)))
22249 (defun org-remove-if-not (predicate seq)
22250 "Remove everything from SEQ that does not fulfill PREDICATE."
22251 (let (res e)
22252 (while seq
22253 (setq e (pop seq))
22254 (if (funcall predicate e) (push e res)))
22255 (nreverse res)))
22257 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22258 "Reduce two-argument FUNCTION across SEQ.
22259 Taken from `reduce' in cl-seq.el with all keyword arguments but
22260 \":initial-value\" removed."
22261 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22262 (cadr (memq :initial-value cl-keys)))
22263 (cl-seq (pop cl-seq))
22264 (t (funcall cl-func)))))
22265 (while cl-seq
22266 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22267 cl-accum))
22269 (defun org-every (pred seq)
22270 "Return true if PREDICATE is true of every element of SEQ.
22271 Adapted from `every' in cl.el."
22272 (catch 'org-every
22273 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22276 (defun org-some (pred seq)
22277 "Return true if PREDICATE is true of any element of SEQ.
22278 Adapted from `some' in cl.el."
22279 (catch 'org-some
22280 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22281 nil))
22283 (defun org-back-over-empty-lines ()
22284 "Move backwards over whitespace, to the beginning of the first empty line.
22285 Returns the number of empty lines passed."
22286 (let ((pos (point)))
22287 (if (cdr (assoc 'heading org-blank-before-new-entry))
22288 (skip-chars-backward " \t\n\r")
22289 (unless (eobp)
22290 (forward-line -1)))
22291 (beginning-of-line 2)
22292 (goto-char (min (point) pos))
22293 (count-lines (point) pos)))
22295 (defun org-skip-whitespace ()
22296 (skip-chars-forward " \t\n\r"))
22298 (defun org-point-in-group (point group &optional context)
22299 "Check if POINT is in match-group GROUP.
22300 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22301 match. If the match group does not exist or point is not inside it,
22302 return nil."
22303 (and (match-beginning group)
22304 (>= point (match-beginning group))
22305 (<= point (match-end group))
22306 (if context
22307 (list context (match-beginning group) (match-end group))
22308 t)))
22310 (defun org-switch-to-buffer-other-window (&rest args)
22311 "Switch to buffer in a second window on the current frame.
22312 In particular, do not allow pop-up frames.
22313 Returns the newly created buffer."
22314 (org-no-popups
22315 (apply 'switch-to-buffer-other-window args)))
22317 (defun org-combine-plists (&rest plists)
22318 "Create a single property list from all plists in PLISTS.
22319 The process starts by copying the first list, and then setting properties
22320 from the other lists. Settings in the last list are the most significant
22321 ones and overrule settings in the other lists."
22322 (let ((rtn (copy-sequence (pop plists)))
22323 p v ls)
22324 (while plists
22325 (setq ls (pop plists))
22326 (while ls
22327 (setq p (pop ls) v (pop ls))
22328 (setq rtn (plist-put rtn p v))))
22329 rtn))
22331 (defun org-replace-escapes (string table)
22332 "Replace %-escapes in STRING with values in TABLE.
22333 TABLE is an association list with keys like \"%a\" and string values.
22334 The sequences in STRING may contain normal field width and padding information,
22335 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22336 so values can contain further %-escapes if they are define later in TABLE."
22337 (let ((tbl (copy-alist table))
22338 (case-fold-search nil)
22339 (pchg 0)
22340 e re rpl)
22341 (while (setq e (pop tbl))
22342 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22343 (when (and (cdr e) (string-match re (cdr e)))
22344 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22345 (safe "SREF"))
22346 (add-text-properties 0 3 (list 'sref sref) safe)
22347 (setcdr e (replace-match safe t t (cdr e)))))
22348 (while (string-match re string)
22349 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22350 (cdr e)))
22351 (setq string (replace-match rpl t t string))))
22352 (while (setq pchg (next-property-change pchg string))
22353 (let ((sref (get-text-property pchg 'sref string)))
22354 (when (and sref (string-match "SREF" string pchg))
22355 (setq string (replace-match sref t t string)))))
22356 string))
22358 (defun org-sublist (list start end)
22359 "Return a section of LIST, from START to END.
22360 Counting starts at 1."
22361 (let (rtn (c start))
22362 (setq list (nthcdr (1- start) list))
22363 (while (and list (<= c end))
22364 (push (pop list) rtn)
22365 (setq c (1+ c)))
22366 (nreverse rtn)))
22368 (defun org-find-base-buffer-visiting (file)
22369 "Like `find-buffer-visiting' but always return the base buffer and
22370 not an indirect buffer."
22371 (let ((buf (or (get-file-buffer file)
22372 (find-buffer-visiting file))))
22373 (if buf
22374 (or (buffer-base-buffer buf) buf)
22375 nil)))
22377 (defun org-image-file-name-regexp (&optional extensions)
22378 "Return regexp matching the file names of images.
22379 If EXTENSIONS is given, only match these."
22380 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22381 (image-file-name-regexp)
22382 (let ((image-file-name-extensions
22383 (or extensions
22384 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22385 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22386 (concat "\\."
22387 (regexp-opt (nconc (mapcar 'upcase
22388 image-file-name-extensions)
22389 image-file-name-extensions)
22391 "\\'"))))
22393 (defun org-file-image-p (file &optional extensions)
22394 "Return non-nil if FILE is an image."
22395 (save-match-data
22396 (string-match (org-image-file-name-regexp extensions) file)))
22398 (defun org-get-cursor-date (&optional with-time)
22399 "Return the date at cursor in as a time.
22400 This works in the calendar and in the agenda, anywhere else it just
22401 returns the current time.
22402 If WITH-TIME is non-nil, returns the time of the event at point (in
22403 the agenda) or the current time of the day."
22404 (let (date day defd tp tm hod mod)
22405 (when with-time
22406 (setq tp (get-text-property (point) 'time))
22407 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22408 (setq hod (string-to-number (match-string 1 tp))
22409 mod (string-to-number (match-string 2 tp))))
22410 (or tp (setq hod (nth 2 (decode-time (current-time)))
22411 mod (nth 1 (decode-time (current-time))))))
22412 (cond
22413 ((eq major-mode 'calendar-mode)
22414 (setq date (calendar-cursor-to-date)
22415 defd (encode-time 0 (or mod 0) (or hod 0)
22416 (nth 1 date) (nth 0 date) (nth 2 date))))
22417 ((eq major-mode 'org-agenda-mode)
22418 (setq day (get-text-property (point) 'day))
22419 (if day
22420 (setq date (calendar-gregorian-from-absolute day)
22421 defd (encode-time 0 (or mod 0) (or hod 0)
22422 (nth 1 date) (nth 0 date) (nth 2 date))))))
22423 (or defd (current-time))))
22425 (defun org-mark-subtree (&optional up)
22426 "Mark the current subtree.
22427 This puts point at the start of the current subtree, and mark at
22428 the end. If a numeric prefix UP is given, move up into the
22429 hierarchy of headlines by UP levels before marking the subtree."
22430 (interactive "P")
22431 (org-with-limited-levels
22432 (cond ((org-at-heading-p) (beginning-of-line))
22433 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22434 (t (outline-previous-visible-heading 1))))
22435 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22436 (if (org-called-interactively-p 'any)
22437 (call-interactively 'org-mark-element)
22438 (org-mark-element)))
22441 ;;; Indentation
22443 (defun org--get-expected-indentation (element contentsp)
22444 "Expected indentation column for current line, according to ELEMENT.
22445 ELEMENT is an element containing point. CONTENTSP is non-nil
22446 when indentation is to be computed according to contents of
22447 ELEMENT."
22448 (let ((type (org-element-type element))
22449 (start (org-element-property :begin element)))
22450 (org-with-wide-buffer
22451 (cond
22452 (contentsp
22453 (case type
22454 (footnote-definition 0)
22455 ((headline inlinetask nil)
22456 (if (not org-adapt-indentation) 0
22457 (let ((level (org-current-level)))
22458 (if level (1+ level) 0))))
22459 (item
22460 (org-list-item-body-column
22461 (org-element-property :post-affiliated element)))
22462 (plain-list
22463 (save-excursion
22464 (goto-char (org-element-property :post-affiliated element))
22465 (org-get-indentation)))
22466 (otherwise
22467 (goto-char start)
22468 (org-get-indentation))))
22469 ((memq type '(headline inlinetask nil))
22470 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22471 (org--get-expected-indentation element t)
22473 ((eq type 'footnote-definition) 0)
22474 ;; First paragraph of a footnote definition or an item.
22475 ;; Indent like parent.
22476 ((< (line-beginning-position) start)
22477 (org--get-expected-indentation
22478 (org-element-property :parent element) t))
22479 ;; At first line: indent according to previous sibling, if any,
22480 ;; ignoring footnote definitions and inline tasks, or parent's
22481 ;; contents.
22482 ((= (line-beginning-position) start)
22483 (catch 'exit
22484 (while t
22485 (if (= (point-min) start) (throw 'exit 0)
22486 (goto-char (1- start))
22487 (let* ((previous (org-element-at-point))
22488 (parent previous))
22489 (while (and parent (<= (org-element-property :end parent) start))
22490 (setq previous parent
22491 parent (org-element-property :parent parent)))
22492 (cond
22493 ((not previous) (throw 'exit 0))
22494 ((> (org-element-property :end previous) start)
22495 (throw 'exit (org--get-expected-indentation previous t)))
22496 ((memq (org-element-type previous)
22497 '(footnote-definition inlinetask))
22498 (setq start (org-element-property :begin previous)))
22499 (t (goto-char (org-element-property :begin previous))
22500 (throw 'exit
22501 (if (bolp) (org-get-indentation)
22502 ;; At first paragraph in an item or
22503 ;; a footnote definition.
22504 (org--get-expected-indentation
22505 (org-element-property :parent previous) t))))))))))
22506 ;; Otherwise, move to the first non-blank line above.
22508 (beginning-of-line)
22509 (let ((pos (point)))
22510 (skip-chars-backward " \r\t\n")
22511 (cond
22512 ;; Two blank lines end a footnote definition or a plain
22513 ;; list. When we indent an empty line after them, the
22514 ;; containing list or footnote definition is over, so it
22515 ;; qualifies as a previous sibling. Therefore, we indent
22516 ;; like its first line.
22517 ((and (memq type '(footnote-definition plain-list))
22518 (> (count-lines (point) pos) 2))
22519 (goto-char start)
22520 (org-get-indentation))
22521 ;; Line above is the first one of a paragraph at the
22522 ;; beginning of an item or a footnote definition. Indent
22523 ;; like parent.
22524 ((< (line-beginning-position) start)
22525 (org--get-expected-indentation
22526 (org-element-property :parent element) t))
22527 ;; POS is after contents in a greater element. Indent like
22528 ;; the beginning of the element.
22530 ;; As a special case, if point is at the end of a footnote
22531 ;; definition or an item, indent like the very last element
22532 ;; within.
22533 ((let ((cend (org-element-property :contents-end element)))
22534 (and cend (<= cend pos)))
22535 (if (memq type '(footnote-definition item plain-list))
22536 (org--get-expected-indentation (org-element-at-point) nil)
22537 (goto-char start)
22538 (org-get-indentation)))
22539 ;; In any other case, indent like the current line.
22540 (t (org-get-indentation)))))))))
22542 (defun org--align-node-property ()
22543 "Align node property at point.
22544 Alignment is done according to `org-property-format', which see."
22545 (when (save-excursion
22546 (beginning-of-line)
22547 (looking-at org-property-re))
22548 (replace-match
22549 (concat (match-string 4)
22550 (org-trim
22551 (format org-property-format (match-string 1) (match-string 3))))
22552 t t)))
22554 (defun org-indent-line ()
22555 "Indent line depending on context.
22557 Indentation is done according to the following rules:
22559 - Footnote definitions, headlines and inline tasks have to
22560 start at column 0.
22562 - On the very first line of an element, consider, in order, the
22563 next rules until one matches:
22565 1. If there's a sibling element before, ignoring footnote
22566 definitions and inline tasks, indent like its first line.
22568 2. If element has a parent, indent like its contents. More
22569 precisely, if parent is an item, indent after the
22570 description part, if any, or the bullet (see
22571 ``org-list-description-max-indent'). Else, indent like
22572 parent's first line.
22574 3. Otherwise, indent relatively to current level, if
22575 `org-adapt-indentation' is non-nil, or to left margin.
22577 - On a blank line at the end of a plain list, an item, or
22578 a footnote definition, indent like the very last element
22579 within.
22581 - In the code part of a source block, use language major mode
22582 to indent current line if `org-src-tab-acts-natively' is
22583 non-nil. If it is nil, do nothing.
22585 - Otherwise, indent like the first non-blank line above.
22587 The function doesn't indent an item as it could break the whole
22588 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22589 \\[org-shiftmetaright].
22591 Also align node properties according to `org-property-format'."
22592 (interactive)
22593 (cond
22594 (orgstruct-is-++
22595 (let ((indent-line-function
22596 (cadadr (assq 'indent-line-function org-fb-vars))))
22597 (indent-according-to-mode)))
22598 ((org-at-heading-p) 'noindent)
22600 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22601 (type (org-element-type element)))
22602 (cond ((and (memq type '(plain-list item))
22603 (= (line-beginning-position)
22604 (org-element-property :post-affiliated element)))
22605 'noindent)
22606 ((and (eq type 'src-block)
22607 org-src-tab-acts-natively
22608 (> (line-beginning-position)
22609 (org-element-property :post-affiliated element))
22610 (< (line-beginning-position)
22611 (org-with-wide-buffer
22612 (goto-char (org-element-property :end element))
22613 (skip-chars-backward " \r\t\n")
22614 (line-beginning-position))))
22615 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22616 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22618 (let ((column (org--get-expected-indentation element nil)))
22619 ;; Preserve current column.
22620 (if (<= (current-column) (current-indentation))
22621 (org-indent-line-to column)
22622 (save-excursion (org-indent-line-to column))))
22623 ;; Align node property. Also preserve current column.
22624 (when (eq type 'node-property)
22625 (let ((column (current-column)))
22626 (org--align-node-property)
22627 (org-move-to-column column)))))))))
22629 (defun org-indent-region (start end)
22630 "Indent each non-blank line in the region.
22631 Called from a program, START and END specify the region to
22632 indent. The function will not indent contents of example blocks,
22633 verse blocks and export blocks as leading white spaces are
22634 assumed to be significant there."
22635 (interactive "r")
22636 (save-excursion
22637 (goto-char start)
22638 (skip-chars-forward " \r\t\n")
22639 (unless (eobp) (beginning-of-line))
22640 (let ((indent-to
22641 (lambda (ind pos)
22642 ;; Set IND as indentation for all lines between point and
22643 ;; POS or END, whichever comes first. Blank lines are
22644 ;; ignored. Leave point after POS once done.
22645 (let ((limit (copy-marker (min end pos))))
22646 (while (< (point) limit)
22647 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22648 (forward-line))
22649 (set-marker limit nil))))
22650 (end (copy-marker end)))
22651 (while (< (point) end)
22652 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22653 (let* ((element (org-element-at-point))
22654 (type (org-element-type element))
22655 (element-end (copy-marker (org-element-property :end element)))
22656 (ind (org--get-expected-indentation element nil)))
22657 (cond
22658 ((or (memq type '(paragraph table table-row))
22659 (not (or (org-element-property :contents-begin element)
22660 (memq type
22661 '(example-block export-block src-block)))))
22662 ;; Elements here are indented as a single block. Also
22663 ;; align node properties.
22664 (when (eq type 'node-property)
22665 (org--align-node-property)
22666 (beginning-of-line))
22667 (funcall indent-to ind element-end))
22669 ;; Elements in this category consist of three parts:
22670 ;; before the contents, the contents, and after the
22671 ;; contents. The contents are treated specially,
22672 ;; according to the element type, or not indented at
22673 ;; all. Other parts are indented as a single block.
22674 (let* ((post (copy-marker
22675 (org-element-property :post-affiliated element)))
22676 (cbeg
22677 (copy-marker
22678 (cond
22679 ((not (org-element-property :contents-begin element))
22680 ;; Fake contents for source blocks.
22681 (org-with-wide-buffer
22682 (goto-char post)
22683 (forward-line)
22684 (point)))
22685 ((memq type '(footnote-definition item plain-list))
22686 ;; Contents in these elements could start on
22687 ;; the same line as the beginning of the
22688 ;; element. Make sure we start indenting
22689 ;; from the second line.
22690 (org-with-wide-buffer
22691 (goto-char post)
22692 (end-of-line)
22693 (skip-chars-forward " \r\t\n")
22694 (if (eobp) (point) (line-beginning-position))))
22695 (t (org-element-property :contents-begin element)))))
22696 (cend (copy-marker
22697 (or (org-element-property :contents-end element)
22698 ;; Fake contents for source blocks.
22699 (org-with-wide-buffer
22700 (goto-char element-end)
22701 (skip-chars-backward " \r\t\n")
22702 (line-beginning-position))))))
22703 ;; Do not change items indentation individually as it
22704 ;; might break the list as a whole. On the other
22705 ;; hand, when at a plain list, indent it as a whole.
22706 (cond ((eq type 'plain-list)
22707 (let ((offset (- ind (org-get-indentation))))
22708 (unless (zerop offset)
22709 (indent-rigidly (org-element-property :begin element)
22710 (org-element-property :end element)
22711 offset))
22712 (goto-char cbeg)))
22713 ((eq type 'item) (goto-char cbeg))
22714 (t (funcall indent-to ind cbeg)))
22715 (when (< (point) end)
22716 (case type
22717 ((example-block export-block verse-block))
22718 (src-block
22719 ;; In a source block, indent source code
22720 ;; according to language major mode, but only if
22721 ;; `org-src-tab-acts-natively' is non-nil.
22722 (when (and (< (point) end) org-src-tab-acts-natively)
22723 (ignore-errors
22724 (let (org-src-strip-leading-and-trailing-blank-lines
22725 ;; Region boundaries in edit buffer.
22726 (start (1+ (- (point) cbeg)))
22727 (end (- (min cend end) cbeg)))
22728 (org-babel-do-in-edit-buffer
22729 (indent-region start end))))))
22730 (t (org-indent-region (point) (min cend end))))
22731 (goto-char (min cend end))
22732 (when (< (point) end) (funcall indent-to ind element-end)))
22733 (set-marker post nil)
22734 (set-marker cbeg nil)
22735 (set-marker cend nil))))
22736 (set-marker element-end nil))))
22737 (set-marker end nil))))
22739 (defun org-indent-drawer ()
22740 "Indent the drawer at point."
22741 (interactive)
22742 (unless (save-excursion
22743 (beginning-of-line)
22744 (org-looking-at-p org-drawer-regexp))
22745 (user-error "Not at a drawer"))
22746 (let ((element (org-element-at-point)))
22747 (unless (memq (org-element-type element) '(drawer property-drawer))
22748 (user-error "Not at a drawer"))
22749 (org-with-wide-buffer
22750 (org-indent-region (org-element-property :begin element)
22751 (org-element-property :end element))))
22752 (message "Drawer at point indented"))
22754 (defun org-indent-block ()
22755 "Indent the block at point."
22756 (interactive)
22757 (unless (save-excursion
22758 (beginning-of-line)
22759 (let ((case-fold-search t))
22760 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22761 (user-error "Not at a block"))
22762 (let ((element (org-element-at-point)))
22763 (unless (memq (org-element-type element)
22764 '(comment-block center-block dynamic-block example-block
22765 export-block quote-block special-block
22766 src-block verse-block))
22767 (user-error "Not at a block"))
22768 (org-with-wide-buffer
22769 (org-indent-region (org-element-property :begin element)
22770 (org-element-property :end element))))
22771 (message "Block at point indented"))
22774 ;;; Filling
22776 ;; We use our own fill-paragraph and auto-fill functions.
22778 ;; `org-fill-paragraph' relies on adaptive filling and context
22779 ;; checking. Appropriate `fill-prefix' is computed with
22780 ;; `org-adaptive-fill-function'.
22782 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22783 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22784 ;; `org-adaptive-fill-function' value. Internally,
22785 ;; `org-comment-line-break-function' breaks the line.
22787 ;; `org-setup-filling' installs filling and auto-filling related
22788 ;; variables during `org-mode' initialization.
22790 (defvar org-element-paragraph-separate) ; org-element.el
22791 (defun org-setup-filling ()
22792 (require 'org-element)
22793 ;; Prevent auto-fill from inserting unwanted new items.
22794 (when (boundp 'fill-nobreak-predicate)
22795 (org-set-local
22796 'fill-nobreak-predicate
22797 (org-uniquify
22798 (append fill-nobreak-predicate
22799 '(org-fill-line-break-nobreak-p
22800 org-fill-paragraph-with-timestamp-nobreak-p)))))
22801 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22802 (org-set-local 'paragraph-start paragraph-ending)
22803 (org-set-local 'paragraph-separate paragraph-ending))
22804 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22805 (org-set-local 'auto-fill-inhibit-regexp nil)
22806 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22807 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22808 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22810 (defun org-fill-line-break-nobreak-p ()
22811 "Non-nil when a new line at point would create an Org line break."
22812 (save-excursion
22813 (skip-chars-backward "[ \t]")
22814 (skip-chars-backward "\\\\")
22815 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22817 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22818 "Non-nil when a new line at point would split a timestamp."
22819 (and (org-at-timestamp-p t)
22820 (not (looking-at org-ts-regexp-both))))
22822 (declare-function message-in-body-p "message" ())
22823 (defvar orgtbl-line-start-regexp) ; From org-table.el
22824 (defun org-adaptive-fill-function ()
22825 "Compute a fill prefix for the current line.
22826 Return fill prefix, as a string, or nil if current line isn't
22827 meant to be filled. For convenience, if `adaptive-fill-regexp'
22828 matches in paragraphs or comments, use it."
22829 (catch 'exit
22830 (when (derived-mode-p 'message-mode)
22831 (save-excursion
22832 (beginning-of-line)
22833 (cond ((or (not (message-in-body-p))
22834 (looking-at orgtbl-line-start-regexp))
22835 (throw 'exit nil))
22836 ((looking-at message-cite-prefix-regexp)
22837 (throw 'exit (match-string-no-properties 0)))
22838 ((looking-at org-outline-regexp)
22839 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22840 (org-with-wide-buffer
22841 (unless (org-at-heading-p)
22842 (let* ((p (line-beginning-position))
22843 (element (save-excursion
22844 (beginning-of-line)
22845 (org-element-at-point)))
22846 (type (org-element-type element))
22847 (post-affiliated (org-element-property :post-affiliated element)))
22848 (unless (< p post-affiliated)
22849 (case type
22850 (comment
22851 (save-excursion
22852 (beginning-of-line)
22853 (looking-at "[ \t]*")
22854 (concat (match-string 0) "# ")))
22855 (footnote-definition "")
22856 ((item plain-list)
22857 (make-string (org-list-item-body-column post-affiliated) ?\s))
22858 (paragraph
22859 ;; Fill prefix is usually the same as the current line,
22860 ;; unless the paragraph is at the beginning of an item.
22861 (let ((parent (org-element-property :parent element)))
22862 (save-excursion
22863 (beginning-of-line)
22864 (cond ((eq (org-element-type parent) 'item)
22865 (make-string (org-list-item-body-column
22866 (org-element-property :begin parent))
22867 ?\s))
22868 ((and adaptive-fill-regexp
22869 ;; Locally disable
22870 ;; `adaptive-fill-function' to let
22871 ;; `fill-context-prefix' handle
22872 ;; `adaptive-fill-regexp' variable.
22873 (let (adaptive-fill-function)
22874 (fill-context-prefix
22875 post-affiliated
22876 (org-element-property :end element)))))
22877 ((looking-at "[ \t]+") (match-string 0))
22878 (t "")))))
22879 (comment-block
22880 ;; Only fill contents if P is within block boundaries.
22881 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22882 (forward-line)
22883 (point)))
22884 (cend (save-excursion
22885 (goto-char (org-element-property :end element))
22886 (skip-chars-backward " \r\t\n")
22887 (line-beginning-position))))
22888 (when (and (>= p cbeg) (< p cend))
22889 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22890 (match-string 0)
22891 "")))))))))))
22893 (declare-function message-goto-body "message" ())
22894 (defvar message-cite-prefix-regexp) ; From message.el
22895 (defun org-fill-paragraph (&optional justify)
22896 "Fill element at point, when applicable.
22898 This function only applies to comment blocks, comments, example
22899 blocks and paragraphs. Also, as a special case, re-align table
22900 when point is at one.
22902 If JUSTIFY is non-nil (interactively, with prefix argument),
22903 justify as well. If `sentence-end-double-space' is non-nil, then
22904 period followed by one space does not end a sentence, so don't
22905 break a line there. The variable `fill-column' controls the
22906 width for filling.
22908 For convenience, when point is at a plain list, an item or
22909 a footnote definition, try to fill the first paragraph within."
22910 (interactive)
22911 (if (and (derived-mode-p 'message-mode)
22912 (or (not (message-in-body-p))
22913 (save-excursion (move-beginning-of-line 1)
22914 (looking-at message-cite-prefix-regexp))))
22915 ;; First ensure filling is correct in message-mode.
22916 (let ((fill-paragraph-function
22917 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22918 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22919 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22920 (paragraph-separate
22921 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22922 (fill-paragraph nil))
22923 (with-syntax-table org-mode-transpose-word-syntax-table
22924 ;; Move to end of line in order to get the first paragraph
22925 ;; within a plain list or a footnote definition.
22926 (let ((element (save-excursion
22927 (end-of-line)
22928 (or (ignore-errors (org-element-at-point))
22929 (user-error "An element cannot be parsed line %d"
22930 (line-number-at-pos (point)))))))
22931 ;; First check if point is in a blank line at the beginning of
22932 ;; the buffer. In that case, ignore filling.
22933 (case (org-element-type element)
22934 ;; Use major mode filling function is src blocks.
22935 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22936 ;; Align Org tables, leave table.el tables as-is.
22937 (table-row (org-table-align) t)
22938 (table
22939 (when (eq (org-element-property :type element) 'org)
22940 (save-excursion
22941 (goto-char (org-element-property :post-affiliated element))
22942 (org-table-align)))
22944 (paragraph
22945 ;; Paragraphs may contain `line-break' type objects.
22946 (let ((beg (max (point-min)
22947 (org-element-property :contents-begin element)))
22948 (end (min (point-max)
22949 (org-element-property :contents-end element))))
22950 ;; Do nothing if point is at an affiliated keyword.
22951 (if (< (line-end-position) beg) t
22952 (when (derived-mode-p 'message-mode)
22953 ;; In `message-mode', do not fill following citation
22954 ;; in current paragraph nor text before message body.
22955 (let ((body-start (save-excursion (message-goto-body))))
22956 (when body-start (setq beg (max body-start beg))))
22957 (when (save-excursion
22958 (re-search-forward
22959 (concat "^" message-cite-prefix-regexp) end t))
22960 (setq end (match-beginning 0))))
22961 ;; Fill paragraph, taking line breaks into account.
22962 (save-excursion
22963 (goto-char beg)
22964 (let ((cuts (list beg)))
22965 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22966 (when (eq 'line-break
22967 (org-element-type
22968 (save-excursion (backward-char)
22969 (org-element-context))))
22970 (push (point) cuts)))
22971 (dolist (c (delq end cuts))
22972 (fill-region-as-paragraph c end justify)
22973 (setq end c))))
22974 t)))
22975 ;; Contents of `comment-block' type elements should be
22976 ;; filled as plain text, but only if point is within block
22977 ;; markers.
22978 (comment-block
22979 (let* ((case-fold-search t)
22980 (beg (save-excursion
22981 (goto-char (org-element-property :begin element))
22982 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22983 (forward-line)
22984 (point)))
22985 (end (save-excursion
22986 (goto-char (org-element-property :end element))
22987 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22988 (line-beginning-position))))
22989 (if (or (< (point) beg) (> (point) end)) t
22990 (fill-region-as-paragraph
22991 (save-excursion (end-of-line)
22992 (re-search-backward "^[ \t]*$" beg 'move)
22993 (line-beginning-position))
22994 (save-excursion (beginning-of-line)
22995 (re-search-forward "^[ \t]*$" end 'move)
22996 (line-beginning-position))
22997 justify))))
22998 ;; Fill comments.
22999 (comment
23000 (let ((begin (org-element-property :post-affiliated element))
23001 (end (org-element-property :end element)))
23002 (when (and (>= (point) begin) (<= (point) end))
23003 (let ((begin (save-excursion
23004 (end-of-line)
23005 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23006 (progn (forward-line) (point))
23007 begin)))
23008 (end (save-excursion
23009 (end-of-line)
23010 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23011 (1- (line-beginning-position))
23012 (skip-chars-backward " \r\t\n")
23013 (line-end-position)))))
23014 ;; Do not fill comments when at a blank line.
23015 (when (> end begin)
23016 (let ((fill-prefix
23017 (save-excursion
23018 (beginning-of-line)
23019 (looking-at "[ \t]*#")
23020 (let ((comment-prefix (match-string 0)))
23021 (goto-char (match-end 0))
23022 (if (looking-at adaptive-fill-regexp)
23023 (concat comment-prefix (match-string 0))
23024 (concat comment-prefix " "))))))
23025 (save-excursion
23026 (fill-region-as-paragraph begin end justify))))))
23028 ;; Ignore every other element.
23029 (otherwise t))))))
23031 (defun org-auto-fill-function ()
23032 "Auto-fill function."
23033 ;; Check if auto-filling is meaningful.
23034 (let ((fc (current-fill-column)))
23035 (when (and fc (> (current-column) fc))
23036 (let* ((fill-prefix (org-adaptive-fill-function))
23037 ;; Enforce empty fill prefix, if required. Otherwise, it
23038 ;; will be computed again.
23039 (adaptive-fill-mode (not (equal fill-prefix ""))))
23040 (when fill-prefix (do-auto-fill))))))
23042 (defun org-comment-line-break-function (&optional soft)
23043 "Break line at point and indent, continuing comment if within one.
23044 The inserted newline is marked hard if variable
23045 `use-hard-newlines' is true, unless optional argument SOFT is
23046 non-nil."
23047 (if soft (insert-and-inherit ?\n) (newline 1))
23048 (save-excursion (forward-char -1) (delete-horizontal-space))
23049 (delete-horizontal-space)
23050 (indent-to-left-margin)
23051 (insert-before-markers-and-inherit fill-prefix))
23054 ;;; Fixed Width Areas
23056 (defun org-toggle-fixed-width ()
23057 "Toggle fixed-width markup.
23059 Add or remove fixed-width markup on current line, whenever it
23060 makes sense. Return an error otherwise.
23062 If a region is active and if it contains only fixed-width areas
23063 or blank lines, remove all fixed-width markup in it. If the
23064 region contains anything else, convert all non-fixed-width lines
23065 to fixed-width ones.
23067 Blank lines at the end of the region are ignored unless the
23068 region only contains such lines."
23069 (interactive)
23070 (if (not (org-region-active-p))
23071 ;; No region:
23073 ;; Remove fixed width marker only in a fixed-with element.
23075 ;; Add fixed width maker in paragraphs, in blank lines after
23076 ;; elements or at the beginning of a headline or an inlinetask,
23077 ;; and before any one-line elements (e.g., a clock).
23078 (progn
23079 (beginning-of-line)
23080 (let* ((element (org-element-at-point))
23081 (type (org-element-type element)))
23082 (cond
23083 ((and (eq type 'fixed-width)
23084 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23085 (replace-match
23086 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23087 ((and (memq type '(babel-call clock comment diary-sexp headline
23088 horizontal-rule keyword paragraph
23089 planning))
23090 (<= (org-element-property :post-affiliated element) (point)))
23091 (skip-chars-forward " \t")
23092 (insert ": "))
23093 ((and (org-looking-at-p "[ \t]*$")
23094 (or (eq type 'inlinetask)
23095 (save-excursion
23096 (skip-chars-forward " \r\t\n")
23097 (<= (org-element-property :end element) (point)))))
23098 (delete-region (point) (line-end-position))
23099 (org-indent-line)
23100 (insert ": "))
23101 (t (user-error "Cannot insert a fixed-width line here")))))
23102 ;; Region active.
23103 (let* ((begin (save-excursion
23104 (goto-char (region-beginning))
23105 (line-beginning-position)))
23106 (end (copy-marker
23107 (save-excursion
23108 (goto-char (region-end))
23109 (unless (eolp) (beginning-of-line))
23110 (if (save-excursion (re-search-backward "\\S-" begin t))
23111 (progn (skip-chars-backward " \r\t\n") (point))
23112 (point)))))
23113 (all-fixed-width-p
23114 (catch 'not-all-p
23115 (save-excursion
23116 (goto-char begin)
23117 (skip-chars-forward " \r\t\n")
23118 (when (eobp) (throw 'not-all-p nil))
23119 (while (< (point) end)
23120 (let ((element (org-element-at-point)))
23121 (if (eq (org-element-type element) 'fixed-width)
23122 (goto-char (org-element-property :end element))
23123 (throw 'not-all-p nil))))
23124 t))))
23125 (if all-fixed-width-p
23126 (save-excursion
23127 (goto-char begin)
23128 (while (< (point) end)
23129 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23130 (replace-match
23131 "" nil nil nil
23132 (if (= (line-end-position) (match-end 0)) 0 1)))
23133 (forward-line)))
23134 (let ((min-ind (point-max)))
23135 ;; Find minimum indentation across all lines.
23136 (save-excursion
23137 (goto-char begin)
23138 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23139 (setq min-ind 0)
23140 (catch 'zerop
23141 (while (< (point) end)
23142 (unless (org-looking-at-p "[ \t]*$")
23143 (let ((ind (org-get-indentation)))
23144 (setq min-ind (min min-ind ind))
23145 (when (zerop ind) (throw 'zerop t))))
23146 (forward-line)))))
23147 ;; Loop over all lines and add fixed-width markup everywhere
23148 ;; but in fixed-width lines.
23149 (save-excursion
23150 (goto-char begin)
23151 (while (< (point) end)
23152 (cond
23153 ((org-at-heading-p)
23154 (insert ": ")
23155 (forward-line)
23156 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23157 (insert ":")
23158 (forward-line)))
23159 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23160 (let* ((element (org-element-at-point))
23161 (element-end (org-element-property :end element)))
23162 (if (eq (org-element-type element) 'fixed-width)
23163 (progn (goto-char element-end)
23164 (skip-chars-backward " \r\t\n")
23165 (forward-line))
23166 (let ((limit (min end element-end)))
23167 (while (< (point) limit)
23168 (org-move-to-column min-ind t)
23169 (insert ": ")
23170 (forward-line))))))
23172 (org-move-to-column min-ind t)
23173 (insert ": ")
23174 (forward-line)))))))
23175 (set-marker end nil))))
23178 ;;; Comments
23180 ;; Org comments syntax is quite complex. It requires the entire line
23181 ;; to be just a comment. Also, even with the right syntax at the
23182 ;; beginning of line, some some elements (i.e. verse-block or
23183 ;; example-block) don't accept comments. Usual Emacs comment commands
23184 ;; cannot cope with those requirements. Therefore, Org replaces them.
23186 ;; Org still relies on `comment-dwim', but cannot trust
23187 ;; `comment-only-p'. So, `comment-region-function' and
23188 ;; `uncomment-region-function' both point
23189 ;; to`org-comment-or-uncomment-region'. Eventually,
23190 ;; `org-insert-comment' takes care of insertion of comments at the
23191 ;; beginning of line.
23193 ;; `org-setup-comments-handling' install comments related variables
23194 ;; during `org-mode' initialization.
23196 (defun org-setup-comments-handling ()
23197 (interactive)
23198 (org-set-local 'comment-use-syntax nil)
23199 (org-set-local 'comment-start "# ")
23200 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23201 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23202 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23203 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23205 (defun org-insert-comment ()
23206 "Insert an empty comment above current line.
23207 If the line is empty, insert comment at its beginning. When
23208 point is within a source block, comment according to the related
23209 major mode."
23210 (if (let ((element (org-element-at-point)))
23211 (and (eq (org-element-type element) 'src-block)
23212 (< (save-excursion
23213 (goto-char (org-element-property :post-affiliated element))
23214 (line-end-position))
23215 (point))
23216 (> (save-excursion
23217 (goto-char (org-element-property :end element))
23218 (skip-chars-backward " \r\t\n")
23219 (line-beginning-position))
23220 (point))))
23221 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23222 (beginning-of-line)
23223 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23224 (open-line 1))
23225 (org-indent-line)
23226 (insert "# ")))
23228 (defvar comment-empty-lines) ; From newcomment.el.
23229 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23230 "Comment or uncomment each non-blank line in the region.
23231 Uncomment each non-blank line between BEG and END if it only
23232 contains commented lines. Otherwise, comment them. If region is
23233 strictly within a source block, use appropriate comment syntax."
23234 (if (let ((element (org-element-at-point)))
23235 (and (eq (org-element-type element) 'src-block)
23236 (< (save-excursion
23237 (goto-char (org-element-property :post-affiliated element))
23238 (line-end-position))
23239 beg)
23240 (>= (save-excursion
23241 (goto-char (org-element-property :end element))
23242 (skip-chars-backward " \r\t\n")
23243 (line-beginning-position))
23244 end)))
23245 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23246 (save-restriction
23247 ;; Restrict region
23248 (narrow-to-region (save-excursion (goto-char beg)
23249 (skip-chars-forward " \r\t\n" end)
23250 (line-beginning-position))
23251 (save-excursion (goto-char end)
23252 (skip-chars-backward " \r\t\n" beg)
23253 (line-end-position)))
23254 (let ((uncommentp
23255 ;; UNCOMMENTP is non-nil when every non blank line between
23256 ;; BEG and END is a comment.
23257 (save-excursion
23258 (goto-char (point-min))
23259 (while (and (not (eobp))
23260 (let ((element (org-element-at-point)))
23261 (and (eq (org-element-type element) 'comment)
23262 (goto-char (min (point-max)
23263 (org-element-property
23264 :end element)))))))
23265 (eobp))))
23266 (if uncommentp
23267 ;; Only blank lines and comments in region: uncomment it.
23268 (save-excursion
23269 (goto-char (point-min))
23270 (while (not (eobp))
23271 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23272 (replace-match "" nil nil nil 1))
23273 (forward-line)))
23274 ;; Comment each line in region.
23275 (let ((min-indent (point-max)))
23276 ;; First find the minimum indentation across all lines.
23277 (save-excursion
23278 (goto-char (point-min))
23279 (while (and (not (eobp)) (not (zerop min-indent)))
23280 (unless (looking-at "[ \t]*$")
23281 (setq min-indent (min min-indent (current-indentation))))
23282 (forward-line)))
23283 ;; Then loop over all lines.
23284 (save-excursion
23285 (goto-char (point-min))
23286 (while (not (eobp))
23287 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23288 ;; Don't get fooled by invisible text (e.g. link path)
23289 ;; when moving to column MIN-INDENT.
23290 (let ((buffer-invisibility-spec nil))
23291 (org-move-to-column min-indent t))
23292 (insert comment-start))
23293 (forward-line)))))))))
23295 (defun org-comment-dwim (arg)
23296 "Call `comment-dwim' within a source edit buffer if needed."
23297 (interactive "*P")
23298 (if (org-in-src-block-p)
23299 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23300 (call-interactively 'comment-dwim)))
23303 ;;; Planning
23305 ;; This section contains tools to operate on timestamp objects, as
23306 ;; returned by, e.g. `org-element-context'.
23308 (defun org-timestamp-has-time-p (timestamp)
23309 "Non-nil when TIMESTAMP has a time specified."
23310 (org-element-property :hour-start timestamp))
23312 (defun org-timestamp-format (timestamp format &optional end utc)
23313 "Format a TIMESTAMP element into a string.
23315 FORMAT is a format specifier to be passed to
23316 `format-time-string'.
23318 When optional argument END is non-nil, use end of date-range or
23319 time-range, if possible.
23321 When optional argument UTC is non-nil, time will be expressed as
23322 Universal Time."
23323 (format-time-string
23324 format
23325 (apply 'encode-time
23326 (cons 0
23327 (mapcar
23328 (lambda (prop) (or (org-element-property prop timestamp) 0))
23329 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23330 '(:minute-start :hour-start :day-start :month-start
23331 :year-start)))))
23332 utc))
23334 (defun org-timestamp-split-range (timestamp &optional end)
23335 "Extract a timestamp object from a date or time range.
23337 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23338 the end of the range. Otherwise, extract its start.
23340 Return a new timestamp object sharing the same parent as
23341 TIMESTAMP."
23342 (let ((type (org-element-property :type timestamp)))
23343 (if (memq type '(active inactive diary)) timestamp
23344 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23345 ;; Set new type.
23346 (org-element-put-property
23347 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23348 ;; Copy start properties over end properties if END is
23349 ;; non-nil. Otherwise, copy end properties over `start' ones.
23350 (let ((p-alist '((:minute-start . :minute-end)
23351 (:hour-start . :hour-end)
23352 (:day-start . :day-end)
23353 (:month-start . :month-end)
23354 (:year-start . :year-end))))
23355 (dolist (p-cell p-alist)
23356 (org-element-put-property
23357 split-ts
23358 (funcall (if end 'car 'cdr) p-cell)
23359 (org-element-property
23360 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23361 ;; Eventually refresh `:raw-value'.
23362 (org-element-put-property split-ts :raw-value nil)
23363 (org-element-put-property
23364 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23366 (defun org-timestamp-translate (timestamp &optional boundary)
23367 "Apply `org-translate-time' on a TIMESTAMP object.
23368 When optional argument BOUNDARY is non-nil, it is either the
23369 symbol `start' or `end'. In this case, only translate the
23370 starting or ending part of TIMESTAMP if it is a date or time
23371 range. Otherwise, translate both parts."
23372 (if (and (not boundary)
23373 (memq (org-element-property :type timestamp)
23374 '(active-range inactive-range)))
23375 (concat
23376 (org-translate-time
23377 (org-element-property :raw-value
23378 (org-timestamp-split-range timestamp)))
23379 "--"
23380 (org-translate-time
23381 (org-element-property :raw-value
23382 (org-timestamp-split-range timestamp t))))
23383 (org-translate-time
23384 (org-element-property
23385 :raw-value
23386 (if (not boundary) timestamp
23387 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23391 ;;; Other stuff.
23393 (defun org-reftex-citation ()
23394 "Use reftex-citation to insert a citation into the buffer.
23395 This looks for a line like
23397 #+BIBLIOGRAPHY: foo plain option:-d
23399 and derives from it that foo.bib is the bibliography file relevant
23400 for this document. It then installs the necessary environment for RefTeX
23401 to work in this buffer and calls `reftex-citation' to insert a citation
23402 into the buffer.
23404 Export of such citations to both LaTeX and HTML is handled by the contributed
23405 package ox-bibtex by Taru Karttunen."
23406 (interactive)
23407 (let ((reftex-docstruct-symbol 'rds)
23408 (reftex-cite-format "\\cite{%l}")
23409 rds bib)
23410 (save-excursion
23411 (save-restriction
23412 (widen)
23413 (let ((case-fold-search t)
23414 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23415 (if (not (save-excursion
23416 (or (re-search-forward re nil t)
23417 (re-search-backward re nil t))))
23418 (user-error "No bibliography defined in file")
23419 (setq bib (concat (match-string 1) ".bib")
23420 rds (list (list 'bib bib)))))))
23421 (call-interactively 'reftex-citation)))
23423 ;;;; Functions extending outline functionality
23425 (defun org-beginning-of-line (&optional arg)
23426 "Go to the beginning of the current line. If that is invisible, continue
23427 to a visible line beginning. This makes the function of C-a more intuitive.
23428 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23429 first attempt, and only move to after the tags when the cursor is already
23430 beyond the end of the headline."
23431 (interactive "P")
23432 (let ((pos (point))
23433 (special (if (consp org-special-ctrl-a/e)
23434 (car org-special-ctrl-a/e)
23435 org-special-ctrl-a/e))
23436 deactivate-mark refpos)
23437 (if (org-bound-and-true-p visual-line-mode)
23438 (beginning-of-visual-line 1)
23439 (beginning-of-line 1))
23440 (if (and arg (fboundp 'move-beginning-of-line))
23441 (call-interactively 'move-beginning-of-line)
23442 (if (bobp)
23444 (backward-char 1)
23445 (if (org-truely-invisible-p)
23446 (while (and (not (bobp)) (org-truely-invisible-p))
23447 (backward-char 1)
23448 (beginning-of-line 1))
23449 (forward-char 1))))
23450 (when special
23451 (cond
23452 ((and (looking-at org-complex-heading-regexp)
23453 (= (char-after (match-end 1)) ?\ ))
23454 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23455 (point-at-eol)))
23456 (goto-char
23457 (if (eq special t)
23458 (cond ((> pos refpos) refpos)
23459 ((= pos (point)) refpos)
23460 (t (point)))
23461 (cond ((> pos (point)) (point))
23462 ((not (eq last-command this-command)) (point))
23463 (t refpos)))))
23464 ((org-at-item-p)
23465 ;; Being at an item and not looking at an the item means point
23466 ;; was previously moved to beginning of a visual line, which
23467 ;; doesn't contain the item. Therefore, do nothing special,
23468 ;; just stay here.
23469 (when (looking-at org-list-full-item-re)
23470 ;; Set special position at first white space character after
23471 ;; bullet, and check-box, if any.
23472 (let ((after-bullet
23473 (let ((box (match-end 3)))
23474 (if (not box) (match-end 1)
23475 (let ((after (char-after box)))
23476 (if (and after (= after ? )) (1+ box) box))))))
23477 ;; Special case: Move point to special position when
23478 ;; currently after it or at beginning of line.
23479 (if (eq special t)
23480 (when (or (> pos after-bullet) (= (point) pos))
23481 (goto-char after-bullet))
23482 ;; Reversed case: Move point to special position when
23483 ;; point was already at beginning of line and command is
23484 ;; repeated.
23485 (when (and (= (point) pos) (eq last-command this-command))
23486 (goto-char after-bullet))))))))
23487 (org-no-warnings
23488 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23489 (setq disable-point-adjustment
23490 (or (not (invisible-p (point)))
23491 (not (invisible-p (max (point-min) (1- (point))))))))
23493 (defun org-end-of-line (&optional arg)
23494 "Go to the end of the line.
23495 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23496 tags on the first attempt, and only move to after the tags when
23497 the cursor is already beyond the end of the headline."
23498 (interactive "P")
23499 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23500 org-special-ctrl-a/e))
23501 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23502 'end-of-visual-line)
23503 ((fboundp 'move-end-of-line) 'move-end-of-line)
23504 (t 'end-of-line)))
23505 deactivate-mark)
23506 (if (or (not special) arg) (call-interactively move-fun)
23507 (let* ((element (save-excursion (beginning-of-line)
23508 (org-element-at-point)))
23509 (type (org-element-type element)))
23510 (cond
23511 ((memq type '(headline inlinetask))
23512 (let ((pos (point)))
23513 (beginning-of-line 1)
23514 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23515 (if (eq special t)
23516 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23517 (goto-char (match-beginning 1))
23518 (goto-char (match-end 0)))
23519 (if (or (< pos (match-end 0))
23520 (not (eq this-command last-command)))
23521 (goto-char (match-end 0))
23522 (goto-char (match-beginning 1))))
23523 (call-interactively move-fun))))
23524 ((outline-invisible-p (line-end-position))
23525 ;; If element is hidden, `move-end-of-line' would put point
23526 ;; after it. Use `end-of-line' to stay on current line.
23527 (call-interactively 'end-of-line))
23528 (t (call-interactively move-fun)))))
23529 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23530 (setq disable-point-adjustment
23531 (or (not (invisible-p (point)))
23532 (not (invisible-p (max (point-min) (1- (point))))))))
23534 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23535 (define-key org-mode-map "\C-e" 'org-end-of-line)
23537 (defun org-backward-sentence (&optional arg)
23538 "Go to beginning of sentence, or beginning of table field.
23539 This will call `backward-sentence' or `org-table-beginning-of-field',
23540 depending on context."
23541 (interactive "P")
23542 (cond
23543 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23544 (t (call-interactively 'backward-sentence))))
23546 (defun org-forward-sentence (&optional arg)
23547 "Go to end of sentence, or end of table field.
23548 This will call `forward-sentence' or `org-table-end-of-field',
23549 depending on context."
23550 (interactive "P")
23551 (cond
23552 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23553 (t (call-interactively 'forward-sentence))))
23555 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23556 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23558 (defun org-kill-line (&optional arg)
23559 "Kill line, to tags or end of line."
23560 (interactive "P")
23561 (cond
23562 ((or (not org-special-ctrl-k)
23563 (bolp)
23564 (not (org-at-heading-p)))
23565 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23566 org-ctrl-k-protect-subtree)
23567 (if (or (eq org-ctrl-k-protect-subtree 'error)
23568 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23569 (user-error "C-k aborted as it would kill a hidden subtree")))
23570 (call-interactively
23571 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23572 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23573 (kill-region (point) (match-beginning 1))
23574 (org-set-tags nil t))
23575 (t (kill-region (point) (point-at-eol)))))
23577 (define-key org-mode-map "\C-k" 'org-kill-line)
23579 (defun org-yank (&optional arg)
23580 "Yank. If the kill is a subtree, treat it specially.
23581 This command will look at the current kill and check if is a single
23582 subtree, or a series of subtrees[1]. If it passes the test, and if the
23583 cursor is at the beginning of a line or after the stars of a currently
23584 empty headline, then the yank is handled specially. How exactly depends
23585 on the value of the following variables, both set by default.
23587 `org-yank-folded-subtrees'
23588 When set, the subtree(s) will be folded after insertion, but only
23589 if doing so would now swallow text after the yanked text.
23591 `org-yank-adjusted-subtrees'
23592 When set, the subtree will be promoted or demoted in order to
23593 fit into the local outline tree structure, which means that the
23594 level will be adjusted so that it becomes the smaller one of the
23595 two *visible* surrounding headings.
23597 Any prefix to this command will cause `yank' to be called directly with
23598 no special treatment. In particular, a simple \\[universal-argument] prefix \
23599 will just
23600 plainly yank the text as it is.
23602 \[1] The test checks if the first non-white line is a heading
23603 and if there are no other headings with fewer stars."
23604 (interactive "P")
23605 (org-yank-generic 'yank arg))
23607 (defun org-yank-generic (command arg)
23608 "Perform some yank-like command.
23610 This function implements the behavior described in the `org-yank'
23611 documentation. However, it has been generalized to work for any
23612 interactive command with similar behavior."
23614 ;; pretend to be command COMMAND
23615 (setq this-command command)
23617 (if arg
23618 (call-interactively command)
23620 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23621 (and (org-kill-is-subtree-p)
23622 (or (bolp)
23623 (and (looking-at "[ \t]*$")
23624 (string-match
23625 "\\`\\*+\\'"
23626 (buffer-substring (point-at-bol) (point)))))))
23627 swallowp)
23628 (cond
23629 ((and subtreep org-yank-folded-subtrees)
23630 (let ((beg (point))
23631 end)
23632 (if (and subtreep org-yank-adjusted-subtrees)
23633 (org-paste-subtree nil nil 'for-yank)
23634 (call-interactively command))
23636 (setq end (point))
23637 (goto-char beg)
23638 (when (and (bolp) subtreep
23639 (not (setq swallowp
23640 (org-yank-folding-would-swallow-text beg end))))
23641 (org-with-limited-levels
23642 (or (looking-at org-outline-regexp)
23643 (re-search-forward org-outline-regexp-bol end t))
23644 (while (and (< (point) end) (looking-at org-outline-regexp))
23645 (hide-subtree)
23646 (org-cycle-show-empty-lines 'folded)
23647 (condition-case nil
23648 (outline-forward-same-level 1)
23649 (error (goto-char end))))))
23650 (when swallowp
23651 (message
23652 "Inserted text not folded because that would swallow text"))
23654 (goto-char end)
23655 (skip-chars-forward " \t\n\r")
23656 (beginning-of-line 1)
23657 (push-mark beg 'nomsg)))
23658 ((and subtreep org-yank-adjusted-subtrees)
23659 (let ((beg (point-at-bol)))
23660 (org-paste-subtree nil nil 'for-yank)
23661 (push-mark beg 'nomsg)))
23663 (call-interactively command))))))
23665 (defun org-yank-folding-would-swallow-text (beg end)
23666 "Would hide-subtree at BEG swallow any text after END?"
23667 (let (level)
23668 (org-with-limited-levels
23669 (save-excursion
23670 (goto-char beg)
23671 (when (or (looking-at org-outline-regexp)
23672 (re-search-forward org-outline-regexp-bol end t))
23673 (setq level (org-outline-level)))
23674 (goto-char end)
23675 (skip-chars-forward " \t\r\n\v\f")
23676 (if (or (eobp)
23677 (and (bolp) (looking-at org-outline-regexp)
23678 (<= (org-outline-level) level)))
23679 nil ; Nothing would be swallowed
23680 t))))) ; something would swallow
23682 (define-key org-mode-map "\C-y" 'org-yank)
23684 (defun org-truely-invisible-p ()
23685 "Check if point is at a character currently not visible.
23686 This version does not only check the character property, but also
23687 `visible-mode'."
23688 ;; Early versions of noutline don't have `outline-invisible-p'.
23689 (if (org-bound-and-true-p visible-mode)
23691 (outline-invisible-p)))
23693 (defun org-invisible-p2 ()
23694 "Check if point is at a character currently not visible."
23695 (save-excursion
23696 (if (and (eolp) (not (bobp))) (backward-char 1))
23697 ;; Early versions of noutline don't have `outline-invisible-p'.
23698 (outline-invisible-p)))
23700 (defun org-back-to-heading (&optional invisible-ok)
23701 "Call `outline-back-to-heading', but provide a better error message."
23702 (condition-case nil
23703 (outline-back-to-heading invisible-ok)
23704 (error (error "Before first headline at position %d in buffer %s"
23705 (point) (current-buffer)))))
23707 (defun org-before-first-heading-p ()
23708 "Before first heading?"
23709 (save-excursion
23710 (end-of-line)
23711 (null (re-search-backward org-outline-regexp-bol nil t))))
23713 (defun org-at-heading-p (&optional ignored)
23714 (outline-on-heading-p t))
23715 ;; Compatibility alias with Org versions < 7.8.03
23716 (defalias 'org-on-heading-p 'org-at-heading-p)
23718 (defun org-in-commented-heading-p (&optional no-inheritance)
23719 "Non-nil if point is under a commented heading.
23720 This function also checks ancestors of the current headline,
23721 unless optional argument NO-INHERITANCE is non-nil."
23722 (cond
23723 ((org-before-first-heading-p) nil)
23724 ((let ((headline (nth 4 (org-heading-components))))
23725 (and headline
23726 (let ((case-fold-search nil))
23727 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23728 headline)))))
23729 (no-inheritance nil)
23731 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23733 (defun org-at-comment-p nil
23734 "Is cursor in a commented line?"
23735 (save-excursion
23736 (save-match-data
23737 (beginning-of-line)
23738 (looking-at "^[ \t]*# "))))
23740 (defun org-at-drawer-p nil
23741 "Is cursor at a drawer keyword?"
23742 (save-excursion
23743 (move-beginning-of-line 1)
23744 (looking-at org-drawer-regexp)))
23746 (defun org-at-block-p nil
23747 "Is cursor at a block keyword?"
23748 (save-excursion
23749 (move-beginning-of-line 1)
23750 (looking-at org-block-regexp)))
23752 (defun org-point-at-end-of-empty-headline ()
23753 "If point is at the end of an empty headline, return t, else nil.
23754 If the heading only contains a TODO keyword, it is still still considered
23755 empty."
23756 (and (looking-at "[ \t]*$")
23757 (when org-todo-line-regexp
23758 (save-excursion
23759 (beginning-of-line 1)
23760 (let ((case-fold-search nil))
23761 (looking-at org-todo-line-regexp)
23762 (string= (match-string 3) ""))))))
23764 (defun org-at-heading-or-item-p ()
23765 (or (org-at-heading-p) (org-at-item-p)))
23767 (defun org-at-target-p ()
23768 (or (org-in-regexp org-radio-target-regexp)
23769 (org-in-regexp org-target-regexp)))
23770 ;; Compatibility alias with Org versions < 7.8.03
23771 (defalias 'org-on-target-p 'org-at-target-p)
23773 (defun org-up-heading-all (arg)
23774 "Move to the heading line of which the present line is a subheading.
23775 This function considers both visible and invisible heading lines.
23776 With argument, move up ARG levels."
23777 (if (fboundp 'outline-up-heading-all)
23778 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23779 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23781 (defun org-up-heading-safe ()
23782 "Move to the heading line of which the present line is a subheading.
23783 This version will not throw an error. It will return the level of the
23784 headline found, or nil if no higher level is found.
23786 Also, this function will be a lot faster than `outline-up-heading',
23787 because it relies on stars being the outline starters. This can really
23788 make a significant difference in outlines with very many siblings."
23789 (when (ignore-errors (org-back-to-heading t))
23790 (let ((level-up (1- (funcall outline-level))))
23791 (and (> level-up 0)
23792 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23793 (funcall outline-level)))))
23795 (defun org-first-sibling-p ()
23796 "Is this heading the first child of its parents?"
23797 (interactive)
23798 (let ((re org-outline-regexp-bol)
23799 level l)
23800 (unless (org-at-heading-p t)
23801 (user-error "Not at a heading"))
23802 (setq level (funcall outline-level))
23803 (save-excursion
23804 (if (not (re-search-backward re nil t))
23806 (setq l (funcall outline-level))
23807 (< l level)))))
23809 (defun org-goto-sibling (&optional previous)
23810 "Goto the next sibling, even if it is invisible.
23811 When PREVIOUS is set, go to the previous sibling instead. Returns t
23812 when a sibling was found. When none is found, return nil and don't
23813 move point."
23814 (let ((fun (if previous 're-search-backward 're-search-forward))
23815 (pos (point))
23816 (re org-outline-regexp-bol)
23817 level l)
23818 (when (ignore-errors (org-back-to-heading t))
23819 (setq level (funcall outline-level))
23820 (catch 'exit
23821 (or previous (forward-char 1))
23822 (while (funcall fun re nil t)
23823 (setq l (funcall outline-level))
23824 (when (< l level) (goto-char pos) (throw 'exit nil))
23825 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23826 (goto-char pos)
23827 nil))))
23829 (defun org-show-siblings ()
23830 "Show all siblings of the current headline."
23831 (save-excursion
23832 (while (org-goto-sibling) (org-flag-heading nil)))
23833 (save-excursion
23834 (while (org-goto-sibling 'previous)
23835 (org-flag-heading nil))))
23837 (defun org-goto-first-child ()
23838 "Goto the first child, even if it is invisible.
23839 Return t when a child was found. Otherwise don't move point and
23840 return nil."
23841 (let (level (pos (point)) (re org-outline-regexp-bol))
23842 (when (ignore-errors (org-back-to-heading t))
23843 (setq level (outline-level))
23844 (forward-char 1)
23845 (if (and (re-search-forward re nil t) (> (outline-level) level))
23846 (progn (goto-char (match-beginning 0)) t)
23847 (goto-char pos) nil))))
23849 (defun org-show-hidden-entry ()
23850 "Show an entry where even the heading is hidden."
23851 (save-excursion
23852 (org-show-entry)))
23854 (defun org-flag-heading (flag &optional entry)
23855 "Flag the current heading. FLAG non-nil means make invisible.
23856 When ENTRY is non-nil, show the entire entry."
23857 (save-excursion
23858 (org-back-to-heading t)
23859 ;; Check if we should show the entire entry
23860 (if entry
23861 (progn
23862 (org-show-entry)
23863 (save-excursion
23864 (and (outline-next-heading)
23865 (org-flag-heading nil))))
23866 (outline-flag-region (max (point-min) (1- (point)))
23867 (save-excursion (outline-end-of-heading) (point))
23868 flag))))
23870 (defun org-get-next-sibling ()
23871 "Move to next heading of the same level, and return point.
23872 If there is no such heading, return nil.
23873 This is like outline-next-sibling, but invisible headings are ok."
23874 (let ((level (funcall outline-level)))
23875 (outline-next-heading)
23876 (while (and (not (eobp)) (> (funcall outline-level) level))
23877 (outline-next-heading))
23878 (if (or (eobp) (< (funcall outline-level) level))
23880 (point))))
23882 (defun org-get-last-sibling ()
23883 "Move to previous heading of the same level, and return point.
23884 If there is no such heading, return nil."
23885 (let ((opoint (point))
23886 (level (funcall outline-level)))
23887 (outline-previous-heading)
23888 (when (and (/= (point) opoint) (outline-on-heading-p t))
23889 (while (and (> (funcall outline-level) level)
23890 (not (bobp)))
23891 (outline-previous-heading))
23892 (if (< (funcall outline-level) level)
23894 (point)))))
23896 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23897 "Goto to the end of a subtree."
23898 ;; This contains an exact copy of the original function, but it uses
23899 ;; `org-back-to-heading', to make it work also in invisible
23900 ;; trees. And is uses an invisible-ok argument.
23901 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23902 ;; Furthermore, when used inside Org, finding the end of a large subtree
23903 ;; with many children and grandchildren etc, this can be much faster
23904 ;; than the outline version.
23905 (org-back-to-heading invisible-ok)
23906 (let ((first t)
23907 (level (funcall outline-level)))
23908 (if (and (derived-mode-p 'org-mode) (< level 1000))
23909 ;; A true heading (not a plain list item), in Org-mode
23910 ;; This means we can easily find the end by looking
23911 ;; only for the right number of stars. Using a regexp to do
23912 ;; this is so much faster than using a Lisp loop.
23913 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23914 (forward-char 1)
23915 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23916 ;; something else, do it the slow way
23917 (while (and (not (eobp))
23918 (or first (> (funcall outline-level) level)))
23919 (setq first nil)
23920 (outline-next-heading)))
23921 (unless to-heading
23922 (if (memq (preceding-char) '(?\n ?\^M))
23923 (progn
23924 ;; Go to end of line before heading
23925 (forward-char -1)
23926 (if (memq (preceding-char) '(?\n ?\^M))
23927 ;; leave blank line before heading
23928 (forward-char -1))))))
23929 (point))
23931 (defun org-end-of-meta-data-and-drawers ()
23932 "Jump to the first text after meta data and drawers in the current entry.
23933 This will move over empty lines, lines with planning time stamps,
23934 clocking lines, and drawers."
23935 (org-back-to-heading t)
23936 (let ((end (save-excursion (outline-next-heading) (point)))
23937 (re (concat "\\(" org-drawer-regexp "\\)"
23938 "\\|" "[ \t]*" org-keyword-time-regexp)))
23939 (forward-line 1)
23940 (while (re-search-forward re end t)
23941 (if (not (match-end 1))
23942 ;; empty or planning line
23943 (forward-line 1)
23944 ;; a drawer, find the end
23945 (re-search-forward "^[ \t]*:END:" end 'move)
23946 (forward-line 1)))
23947 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23948 (point)))
23950 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23951 "Move forward to the ARG'th subheading at same level as this one.
23952 Stop at the first and last subheadings of a superior heading.
23953 Normally this only looks at visible headings, but when INVISIBLE-OK is
23954 non-nil it will also look at invisible ones."
23955 (interactive "p")
23956 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23957 (if (and arg (< arg 0))
23958 (goto-char (point-min))
23959 (outline-next-heading))
23960 (org-at-heading-p)
23961 (let ((level (- (match-end 0) (match-beginning 0) 1))
23962 (f (if (and arg (< arg 0))
23963 're-search-backward
23964 're-search-forward))
23965 (count (if arg (abs arg) 1))
23966 (result (point)))
23967 (while (and (prog1 (> count 0)
23968 (forward-char (if (and arg (< arg 0)) -1 1)))
23969 (funcall f org-outline-regexp-bol nil 'move))
23970 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23971 (cond ((< l level) (setq count 0))
23972 ((and (= l level)
23973 (or invisible-ok
23974 (progn
23975 (goto-char (line-beginning-position))
23976 (not (outline-invisible-p)))))
23977 (setq count (1- count))
23978 (when (eq l level)
23979 (setq result (point)))))))
23980 (goto-char result))
23981 (beginning-of-line 1)))
23983 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23984 "Move backward to the ARG'th subheading at same level as this one.
23985 Stop at the first and last subheadings of a superior heading."
23986 (interactive "p")
23987 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23989 (defun org-next-block (arg &optional backward block-regexp)
23990 "Jump to the next block.
23991 With a prefix argument ARG, jump forward ARG many source blocks.
23992 When BACKWARD is non-nil, jump to the previous block.
23993 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23994 (interactive "p")
23995 (let ((re (or block-regexp org-block-regexp))
23996 (re-search-fn (or (and backward 're-search-backward)
23997 're-search-forward)))
23998 (if (looking-at re) (forward-char 1))
23999 (condition-case nil
24000 (funcall re-search-fn re nil nil arg)
24001 (error (user-error "No %s code blocks"
24002 (if backward "previous" "further" ))))
24003 (goto-char (match-beginning 0)) (org-show-context)))
24005 (defun org-previous-block (arg &optional block-regexp)
24006 "Jump to the previous block.
24007 With a prefix argument ARG, jump backward ARG many source blocks.
24008 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24009 (interactive "p")
24010 (org-next-block arg t block-regexp))
24012 (defun org-forward-paragraph ()
24013 "Move forward to beginning of next paragraph or equivalent.
24015 The function moves point to the beginning of the next visible
24016 structural element, which can be a paragraph, a table, a list
24017 item, etc. It also provides some special moves for convenience:
24019 - On an affiliated keyword, jump to the beginning of the
24020 relative element.
24021 - On an item or a footnote definition, move to the second
24022 element inside, if any.
24023 - On a table or a property drawer, jump after it.
24024 - On a verse or source block, stop after blank lines."
24025 (interactive)
24026 (when (eobp) (user-error "Cannot move further down"))
24027 (let* ((deactivate-mark nil)
24028 (element (org-element-at-point))
24029 (type (org-element-type element))
24030 (post-affiliated (org-element-property :post-affiliated element))
24031 (contents-begin (org-element-property :contents-begin element))
24032 (contents-end (org-element-property :contents-end element))
24033 (end (let ((end (org-element-property :end element)) (parent element))
24034 (while (and (setq parent (org-element-property :parent parent))
24035 (= (org-element-property :contents-end parent) end))
24036 (setq end (org-element-property :end parent)))
24037 end)))
24038 (cond ((not element)
24039 (skip-chars-forward " \r\t\n")
24040 (or (eobp) (beginning-of-line)))
24041 ;; On affiliated keywords, move to element's beginning.
24042 ((< (point) post-affiliated)
24043 (goto-char post-affiliated))
24044 ;; At a table row, move to the end of the table. Similarly,
24045 ;; at a node property, move to the end of the property
24046 ;; drawer.
24047 ((memq type '(node-property table-row))
24048 (goto-char (org-element-property
24049 :end (org-element-property :parent element))))
24050 ((memq type '(property-drawer table)) (goto-char end))
24051 ;; Consider blank lines as separators in verse and source
24052 ;; blocks to ease editing.
24053 ((memq type '(src-block verse-block))
24054 (when (eq type 'src-block)
24055 (setq contents-end
24056 (save-excursion (goto-char end)
24057 (skip-chars-backward " \r\t\n")
24058 (line-beginning-position))))
24059 (beginning-of-line)
24060 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24061 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24062 (goto-char end)
24063 (skip-chars-forward " \r\t\n")
24064 (if (= (point) contents-end) (goto-char end)
24065 (beginning-of-line))))
24066 ;; With no contents, just skip element.
24067 ((not contents-begin) (goto-char end))
24068 ;; If contents are invisible, skip the element altogether.
24069 ((outline-invisible-p (line-end-position))
24070 (case type
24071 (headline
24072 (org-with-limited-levels (outline-next-visible-heading 1)))
24073 ;; At a plain list, make sure we move to the next item
24074 ;; instead of skipping the whole list.
24075 (plain-list (forward-char)
24076 (org-forward-paragraph))
24077 (otherwise (goto-char end))))
24078 ((>= (point) contents-end) (goto-char end))
24079 ((>= (point) contents-begin)
24080 ;; This can only happen on paragraphs and plain lists.
24081 (case type
24082 (paragraph (goto-char end))
24083 ;; At a plain list, try to move to second element in
24084 ;; first item, if possible.
24085 (plain-list (end-of-line)
24086 (org-forward-paragraph))))
24087 ;; When contents start on the middle of a line (e.g. in
24088 ;; items and footnote definitions), try to reach first
24089 ;; element starting after current line.
24090 ((> (line-end-position) contents-begin)
24091 (end-of-line)
24092 (org-forward-paragraph))
24093 (t (goto-char contents-begin)))))
24095 (defun org-backward-paragraph ()
24096 "Move backward to start of previous paragraph or equivalent.
24098 The function moves point to the beginning of the current
24099 structural element, which can be a paragraph, a table, a list
24100 item, etc., or to the beginning of the previous visible one if
24101 point is already there. It also provides some special moves for
24102 convenience:
24104 - On an affiliated keyword, jump to the first one.
24105 - On a table or a property drawer, move to its beginning.
24106 - On a verse or source block, stop before blank lines."
24107 (interactive)
24108 (when (bobp) (user-error "Cannot move further up"))
24109 (let* ((deactivate-mark nil)
24110 (element (org-element-at-point))
24111 (type (org-element-type element))
24112 (contents-begin (org-element-property :contents-begin element))
24113 (contents-end (org-element-property :contents-end element))
24114 (post-affiliated (org-element-property :post-affiliated element))
24115 (begin (org-element-property :begin element)))
24116 (cond
24117 ((not element) (goto-char (point-min)))
24118 ((= (point) begin)
24119 (backward-char)
24120 (org-backward-paragraph))
24121 ((<= (point) post-affiliated) (goto-char begin))
24122 ((memq type '(node-property table-row))
24123 (goto-char (org-element-property
24124 :post-affiliated (org-element-property :parent element))))
24125 ((memq type '(property-drawer table)) (goto-char begin))
24126 ((memq type '(src-block verse-block))
24127 (when (eq type 'src-block)
24128 (setq contents-begin
24129 (save-excursion (goto-char begin) (forward-line) (point))))
24130 (if (= (point) contents-begin) (goto-char post-affiliated)
24131 ;; Inside a verse block, see blank lines as paragraph
24132 ;; separators.
24133 (let ((origin (point)))
24134 (skip-chars-backward " \r\t\n" contents-begin)
24135 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24136 (skip-chars-forward " \r\t\n" origin)
24137 (if (= (point) origin) (goto-char contents-begin)
24138 (beginning-of-line))))))
24139 ((not contents-begin) (goto-char (or post-affiliated begin)))
24140 ((eq type 'paragraph)
24141 (goto-char contents-begin)
24142 ;; When at first paragraph in an item or a footnote definition,
24143 ;; move directly to beginning of line.
24144 (let ((parent-contents
24145 (org-element-property
24146 :contents-begin (org-element-property :parent element))))
24147 (when (and parent-contents (= parent-contents contents-begin))
24148 (beginning-of-line))))
24149 ;; At the end of a greater element, move to the beginning of the
24150 ;; last element within.
24151 ((>= (point) contents-end)
24152 (goto-char (1- contents-end))
24153 (org-backward-paragraph))
24154 (t (goto-char (or post-affiliated begin))))
24155 ;; Ensure we never leave point invisible.
24156 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24158 (defun org-forward-element ()
24159 "Move forward by one element.
24160 Move to the next element at the same level, when possible."
24161 (interactive)
24162 (cond ((eobp) (user-error "Cannot move further down"))
24163 ((org-with-limited-levels (org-at-heading-p))
24164 (let ((origin (point)))
24165 (goto-char (org-end-of-subtree nil t))
24166 (unless (org-with-limited-levels (org-at-heading-p))
24167 (goto-char origin)
24168 (user-error "Cannot move further down"))))
24170 (let* ((elem (org-element-at-point))
24171 (end (org-element-property :end elem))
24172 (parent (org-element-property :parent elem)))
24173 (cond ((and parent (= (org-element-property :contents-end parent) end))
24174 (goto-char (org-element-property :end parent)))
24175 ((integer-or-marker-p end) (goto-char end))
24176 (t (message "No element at point")))))))
24178 (defun org-backward-element ()
24179 "Move backward by one element.
24180 Move to the previous element at the same level, when possible."
24181 (interactive)
24182 (cond ((bobp) (user-error "Cannot move further up"))
24183 ((org-with-limited-levels (org-at-heading-p))
24184 ;; At a headline, move to the previous one, if any, or stay
24185 ;; here.
24186 (let ((origin (point)))
24187 (org-with-limited-levels (org-backward-heading-same-level 1))
24188 ;; When current headline has no sibling above, move to its
24189 ;; parent.
24190 (when (= (point) origin)
24191 (or (org-with-limited-levels (org-up-heading-safe))
24192 (progn (goto-char origin)
24193 (user-error "Cannot move further up"))))))
24195 (let* ((elem (org-element-at-point))
24196 (beg (org-element-property :begin elem)))
24197 (cond
24198 ;; Move to beginning of current element if point isn't
24199 ;; there already.
24200 ((null beg) (message "No element at point"))
24201 ((/= (point) beg) (goto-char beg))
24202 (t (goto-char beg)
24203 (skip-chars-backward " \r\t\n")
24204 (unless (bobp)
24205 (let ((prev (org-element-at-point)))
24206 (goto-char (org-element-property :begin prev))
24207 (while (and (setq prev (org-element-property :parent prev))
24208 (<= (org-element-property :end prev) beg))
24209 (goto-char (org-element-property :begin prev)))))))))))
24211 (defun org-up-element ()
24212 "Move to upper element."
24213 (interactive)
24214 (if (org-with-limited-levels (org-at-heading-p))
24215 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24216 (let* ((elem (org-element-at-point))
24217 (parent (org-element-property :parent elem)))
24218 (if parent (goto-char (org-element-property :begin parent))
24219 (if (org-with-limited-levels (org-before-first-heading-p))
24220 (user-error "No surrounding element")
24221 (org-with-limited-levels (org-back-to-heading)))))))
24223 (defvar org-element-greater-elements)
24224 (defun org-down-element ()
24225 "Move to inner element."
24226 (interactive)
24227 (let ((element (org-element-at-point)))
24228 (cond
24229 ((memq (org-element-type element) '(plain-list table))
24230 (goto-char (org-element-property :contents-begin element))
24231 (forward-char))
24232 ((memq (org-element-type element) org-element-greater-elements)
24233 ;; If contents are hidden, first disclose them.
24234 (when (outline-invisible-p (line-end-position)) (org-cycle))
24235 (goto-char (or (org-element-property :contents-begin element)
24236 (user-error "No content for this element"))))
24237 (t (user-error "No inner element")))))
24239 (defun org-drag-element-backward ()
24240 "Move backward element at point."
24241 (interactive)
24242 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24243 (let* ((elem (org-element-at-point))
24244 (prev-elem
24245 (save-excursion
24246 (goto-char (org-element-property :begin elem))
24247 (skip-chars-backward " \r\t\n")
24248 (unless (bobp)
24249 (let* ((beg (org-element-property :begin elem))
24250 (prev (org-element-at-point))
24251 (up prev))
24252 (while (and (setq up (org-element-property :parent up))
24253 (<= (org-element-property :end up) beg))
24254 (setq prev up))
24255 prev)))))
24256 ;; Error out if no previous element or previous element is
24257 ;; a parent of the current one.
24258 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24259 (user-error "Cannot drag element backward")
24260 (let ((pos (point)))
24261 (org-element-swap-A-B prev-elem elem)
24262 (goto-char (+ (org-element-property :begin prev-elem)
24263 (- pos (org-element-property :begin elem)))))))))
24265 (defun org-drag-element-forward ()
24266 "Move forward element at point."
24267 (interactive)
24268 (let* ((pos (point))
24269 (elem (org-element-at-point)))
24270 (when (= (point-max) (org-element-property :end elem))
24271 (user-error "Cannot drag element forward"))
24272 (goto-char (org-element-property :end elem))
24273 (let ((next-elem (org-element-at-point)))
24274 (when (or (org-element-nested-p elem next-elem)
24275 (and (eq (org-element-type next-elem) 'headline)
24276 (not (eq (org-element-type elem) 'headline))))
24277 (goto-char pos)
24278 (user-error "Cannot drag element forward"))
24279 ;; Compute new position of point: it's shifted by NEXT-ELEM
24280 ;; body's length (without final blanks) and by the length of
24281 ;; blanks between ELEM and NEXT-ELEM.
24282 (let ((size-next (- (save-excursion
24283 (goto-char (org-element-property :end next-elem))
24284 (skip-chars-backward " \r\t\n")
24285 (forward-line)
24286 ;; Small correction if buffer doesn't end
24287 ;; with a newline character.
24288 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24289 (org-element-property :begin next-elem)))
24290 (size-blank (- (org-element-property :end elem)
24291 (save-excursion
24292 (goto-char (org-element-property :end elem))
24293 (skip-chars-backward " \r\t\n")
24294 (forward-line)
24295 (point)))))
24296 (org-element-swap-A-B elem next-elem)
24297 (goto-char (+ pos size-next size-blank))))))
24299 (defun org-drag-line-forward (arg)
24300 "Drag the line at point ARG lines forward."
24301 (interactive "p")
24302 (dotimes (n (abs arg))
24303 (let ((c (current-column)))
24304 (if (< 0 arg)
24305 (progn
24306 (beginning-of-line 2)
24307 (transpose-lines 1)
24308 (beginning-of-line 0))
24309 (transpose-lines 1)
24310 (beginning-of-line -1))
24311 (org-move-to-column c))))
24313 (defun org-drag-line-backward (arg)
24314 "Drag the line at point ARG lines backward."
24315 (interactive "p")
24316 (org-drag-line-forward (- arg)))
24318 (defun org-mark-element ()
24319 "Put point at beginning of this element, mark at end.
24321 Interactively, if this command is repeated or (in Transient Mark
24322 mode) if the mark is active, it marks the next element after the
24323 ones already marked."
24324 (interactive)
24325 (let (deactivate-mark)
24326 (if (and (org-called-interactively-p 'any)
24327 (or (and (eq last-command this-command) (mark t))
24328 (and transient-mark-mode mark-active)))
24329 (set-mark
24330 (save-excursion
24331 (goto-char (mark))
24332 (goto-char (org-element-property :end (org-element-at-point)))))
24333 (let ((element (org-element-at-point)))
24334 (end-of-line)
24335 (push-mark (org-element-property :end element) t t)
24336 (goto-char (org-element-property :begin element))))))
24338 (defun org-narrow-to-element ()
24339 "Narrow buffer to current element."
24340 (interactive)
24341 (let ((elem (org-element-at-point)))
24342 (cond
24343 ((eq (car elem) 'headline)
24344 (narrow-to-region
24345 (org-element-property :begin elem)
24346 (org-element-property :end elem)))
24347 ((memq (car elem) org-element-greater-elements)
24348 (narrow-to-region
24349 (org-element-property :contents-begin elem)
24350 (org-element-property :contents-end elem)))
24352 (narrow-to-region
24353 (org-element-property :begin elem)
24354 (org-element-property :end elem))))))
24356 (defun org-transpose-element ()
24357 "Transpose current and previous elements, keeping blank lines between.
24358 Point is moved after both elements."
24359 (interactive)
24360 (org-skip-whitespace)
24361 (let ((end (org-element-property :end (org-element-at-point))))
24362 (org-drag-element-backward)
24363 (goto-char end)))
24365 (defun org-unindent-buffer ()
24366 "Un-indent the visible part of the buffer.
24367 Relative indentation (between items, inside blocks, etc.) isn't
24368 modified."
24369 (interactive)
24370 (unless (eq major-mode 'org-mode)
24371 (user-error "Cannot un-indent a buffer not in Org mode"))
24372 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24373 unindent-tree ; For byte-compiler.
24374 (unindent-tree
24375 (function
24376 (lambda (contents)
24377 (mapc
24378 (lambda (element)
24379 (if (memq (org-element-type element) '(headline section))
24380 (funcall unindent-tree (org-element-contents element))
24381 (save-excursion
24382 (save-restriction
24383 (narrow-to-region
24384 (org-element-property :begin element)
24385 (org-element-property :end element))
24386 (org-do-remove-indentation)))))
24387 (reverse contents))))))
24388 (funcall unindent-tree (org-element-contents parse-tree))))
24390 (defun org-show-subtree ()
24391 "Show everything after this heading at deeper levels."
24392 (interactive)
24393 (outline-flag-region
24394 (point)
24395 (save-excursion
24396 (org-end-of-subtree t t))
24397 nil))
24399 (defun org-show-entry ()
24400 "Show the body directly following this heading.
24401 Show the heading too, if it is currently invisible."
24402 (interactive)
24403 (save-excursion
24404 (ignore-errors
24405 (org-back-to-heading t)
24406 (outline-flag-region
24407 (max (point-min) (1- (point)))
24408 (save-excursion
24409 (if (re-search-forward
24410 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24411 (match-beginning 1)
24412 (point-max)))
24413 nil)
24414 (org-cycle-hide-drawers 'children))))
24416 (defun org-make-options-regexp (kwds &optional extra)
24417 "Make a regular expression for keyword lines."
24418 (concat
24419 "^[ \t]*#\\+\\("
24420 (mapconcat 'regexp-quote kwds "\\|")
24421 (if extra (concat "\\|" extra))
24422 "\\):[ \t]*\\(.*\\)"))
24424 ;; Make isearch reveal the necessary context
24425 (defun org-isearch-end ()
24426 "Reveal context after isearch exits."
24427 (when isearch-success ; only if search was successful
24428 (if (featurep 'xemacs)
24429 ;; Under XEmacs, the hook is run in the correct place,
24430 ;; we directly show the context.
24431 (org-show-context 'isearch)
24432 ;; In Emacs the hook runs *before* restoring the overlays.
24433 ;; So we have to use a one-time post-command-hook to do this.
24434 ;; (Emacs 22 has a special variable, see function `org-mode')
24435 (unless (and (boundp 'isearch-mode-end-hook-quit)
24436 isearch-mode-end-hook-quit)
24437 ;; Only when the isearch was not quitted.
24438 (org-add-hook 'post-command-hook 'org-isearch-post-command
24439 'append 'local)))))
24441 (defun org-isearch-post-command ()
24442 "Remove self from hook, and show context."
24443 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24444 (org-show-context 'isearch))
24447 ;;;; Integration with and fixes for other packages
24449 ;;; Imenu support
24451 (defvar org-imenu-markers nil
24452 "All markers currently used by Imenu.")
24453 (make-variable-buffer-local 'org-imenu-markers)
24455 (defun org-imenu-new-marker (&optional pos)
24456 "Return a new marker for use by Imenu, and remember the marker."
24457 (let ((m (make-marker)))
24458 (move-marker m (or pos (point)))
24459 (push m org-imenu-markers)
24462 (defun org-imenu-get-tree ()
24463 "Produce the index for Imenu."
24464 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24465 (setq org-imenu-markers nil)
24466 (let* ((n org-imenu-depth)
24467 (re (concat "^" (org-get-limited-outline-regexp)))
24468 (subs (make-vector (1+ n) nil))
24469 (last-level 0)
24470 m level head0 head)
24471 (save-excursion
24472 (save-restriction
24473 (widen)
24474 (goto-char (point-max))
24475 (while (re-search-backward re nil t)
24476 (setq level (org-reduced-level (funcall outline-level)))
24477 (when (and (<= level n)
24478 (looking-at org-complex-heading-regexp)
24479 (setq head0 (org-match-string-no-properties 4)))
24480 (setq head (org-link-display-format head0)
24481 m (org-imenu-new-marker))
24482 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24483 (if (>= level last-level)
24484 (push (cons head m) (aref subs level))
24485 (push (cons head (aref subs (1+ level))) (aref subs level))
24486 (loop for i from (1+ level) to n do (aset subs i nil)))
24487 (setq last-level level)))))
24488 (aref subs 1)))
24490 (eval-after-load "imenu"
24491 '(progn
24492 (add-hook 'imenu-after-jump-hook
24493 (lambda ()
24494 (if (derived-mode-p 'org-mode)
24495 (org-show-context 'org-goto))))))
24497 (defun org-link-display-format (link)
24498 "Replace a link with its the description.
24499 If there is no description, use the link target."
24500 (save-match-data
24501 (if (string-match org-bracket-link-analytic-regexp link)
24502 (replace-match (if (match-end 5)
24503 (match-string 5 link)
24504 (concat (match-string 1 link)
24505 (match-string 3 link)))
24506 nil t link)
24507 link)))
24509 (defun org-toggle-link-display ()
24510 "Toggle the literal or descriptive display of links."
24511 (interactive)
24512 (if org-descriptive-links
24513 (progn (org-remove-from-invisibility-spec '(org-link))
24514 (org-restart-font-lock)
24515 (setq org-descriptive-links nil))
24516 (progn (add-to-invisibility-spec '(org-link))
24517 (org-restart-font-lock)
24518 (setq org-descriptive-links t))))
24520 ;; Speedbar support
24522 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24523 "Overlay marking the agenda restriction line in speedbar.")
24524 (overlay-put org-speedbar-restriction-lock-overlay
24525 'face 'org-agenda-restriction-lock)
24526 (overlay-put org-speedbar-restriction-lock-overlay
24527 'help-echo "Agendas are currently limited to this item.")
24528 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24530 (defun org-speedbar-set-agenda-restriction ()
24531 "Restrict future agenda commands to the location at point in speedbar.
24532 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24533 (interactive)
24534 (require 'org-agenda)
24535 (let (p m tp np dir txt)
24536 (cond
24537 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24538 'org-imenu t))
24539 (setq m (get-text-property p 'org-imenu-marker))
24540 (with-current-buffer (marker-buffer m)
24541 (goto-char m)
24542 (org-agenda-set-restriction-lock 'subtree)))
24543 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24544 'speedbar-function 'speedbar-find-file))
24545 (setq tp (previous-single-property-change
24546 (1+ p) 'speedbar-function)
24547 np (next-single-property-change
24548 tp 'speedbar-function)
24549 dir (speedbar-line-directory)
24550 txt (buffer-substring-no-properties (or tp (point-min))
24551 (or np (point-max))))
24552 (with-current-buffer (find-file-noselect
24553 (let ((default-directory dir))
24554 (expand-file-name txt)))
24555 (unless (derived-mode-p 'org-mode)
24556 (user-error "Cannot restrict to non-Org-mode file"))
24557 (org-agenda-set-restriction-lock 'file)))
24558 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24559 (move-overlay org-speedbar-restriction-lock-overlay
24560 (point-at-bol) (point-at-eol))
24561 (setq current-prefix-arg nil)
24562 (org-agenda-maybe-redo)))
24564 (defvar speedbar-file-key-map)
24565 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24566 (eval-after-load "speedbar"
24567 '(progn
24568 (speedbar-add-supported-extension ".org")
24569 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24570 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24571 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24572 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24573 (add-hook 'speedbar-visiting-tag-hook
24574 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24576 ;;; Fixes and Hacks for problems with other packages
24578 (defun org--flyspell-object-check-p (element)
24579 "Non-nil when Flyspell can check object at point.
24580 ELEMENT is the element at point."
24581 (let ((object (save-excursion
24582 (when (org-looking-at-p "\\>") (backward-char))
24583 (org-element-context element))))
24584 (case (org-element-type object)
24585 ;; Prevent checks in links due to keybinding conflict with
24586 ;; Flyspell.
24587 ((code entity export-snippet inline-babel-call
24588 inline-src-block line-break latex-fragment link macro
24589 statistics-cookie target timestamp verbatim)
24590 nil)
24591 (footnote-reference
24592 ;; Only in inline footnotes, within the definition.
24593 (and (eq (org-element-property :type object) 'inline)
24594 (< (save-excursion
24595 (goto-char (org-element-property :begin object))
24596 (search-forward ":" nil t 2))
24597 (point))))
24598 (otherwise t))))
24600 (defun org-mode-flyspell-verify ()
24601 "Function used for `flyspell-generic-check-word-predicate'."
24602 (if (org-at-heading-p)
24603 ;; At a headline or an inlinetask, check title only. This is
24604 ;; faster than relying on `org-element-at-point'.
24605 (and (save-excursion (beginning-of-line)
24606 (and (let ((case-fold-search t))
24607 (not (looking-at "\\*+ END[ \t]*$")))
24608 (looking-at org-complex-heading-regexp)))
24609 (match-beginning 4)
24610 (>= (point) (match-beginning 4))
24611 (or (not (match-beginning 5))
24612 (< (point) (match-beginning 5))))
24613 (let* ((element (org-element-at-point))
24614 (post-affiliated (org-element-property :post-affiliated element)))
24615 (cond
24616 ;; Ignore checks in all affiliated keywords but captions.
24617 ((< (point) post-affiliated)
24618 (and (save-excursion
24619 (beginning-of-line)
24620 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24621 (> (point) (match-end 0))
24622 (org--flyspell-object-check-p element)))
24623 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24624 ((and org-log-into-drawer
24625 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24626 (parent element))
24627 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24628 (setq parent (org-element-property :parent parent)))
24629 (and parent
24630 (eq (compare-strings
24631 log nil nil
24632 (org-element-property :drawer-name parent) nil nil t)
24633 t))))
24634 nil)
24636 (case (org-element-type element)
24637 ((comment quote-section) t)
24638 (comment-block
24639 ;; Allow checks between block markers, not on them.
24640 (and (> (line-beginning-position) post-affiliated)
24641 (save-excursion
24642 (end-of-line)
24643 (skip-chars-forward " \r\t\n")
24644 (< (point) (org-element-property :end element)))))
24645 ;; Arbitrary list of keywords where checks are meaningful.
24646 ;; Make sure point is on the value part of the element.
24647 (keyword
24648 (and (member (org-element-property :key element)
24649 '("DESCRIPTION" "TITLE"))
24650 (< (save-excursion
24651 (beginning-of-line) (search-forward ":") (point))
24652 (point))))
24653 ;; Check is globally allowed in paragraphs verse blocks and
24654 ;; table rows (after affiliated keywords) but some objects
24655 ;; must not be affected.
24656 ((paragraph table-row verse-block)
24657 (let ((cbeg (org-element-property :contents-begin element))
24658 (cend (org-element-property :contents-end element)))
24659 (and cbeg (>= (point) cbeg) (< (point) cend)
24660 (org--flyspell-object-check-p element))))))))))
24661 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24663 (defun org-remove-flyspell-overlays-in (beg end)
24664 "Remove flyspell overlays in region."
24665 (and (org-bound-and-true-p flyspell-mode)
24666 (fboundp 'flyspell-delete-region-overlays)
24667 (flyspell-delete-region-overlays beg end)))
24669 (defvar flyspell-delayed-commands)
24670 (eval-after-load "flyspell"
24671 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24673 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24674 (eval-after-load "bookmark"
24675 '(if (boundp 'bookmark-after-jump-hook)
24676 ;; We can use the hook
24677 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24678 ;; Hook not available, use advice
24679 (defadvice bookmark-jump (after org-make-visible activate)
24680 "Make the position visible."
24681 (org-bookmark-jump-unhide))))
24683 ;; Make sure saveplace shows the location if it was hidden
24684 (eval-after-load "saveplace"
24685 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24686 "Make the position visible."
24687 (org-bookmark-jump-unhide)))
24689 ;; Make sure ecb shows the location if it was hidden
24690 (eval-after-load "ecb"
24691 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24692 "Make hierarchy visible when jumping into location from ECB tree buffer."
24693 (if (derived-mode-p 'org-mode)
24694 (org-show-context))))
24696 (defun org-bookmark-jump-unhide ()
24697 "Unhide the current position, to show the bookmark location."
24698 (and (derived-mode-p 'org-mode)
24699 (or (outline-invisible-p)
24700 (save-excursion (goto-char (max (point-min) (1- (point))))
24701 (outline-invisible-p)))
24702 (org-show-context 'bookmark-jump)))
24704 (defun org-mark-jump-unhide ()
24705 "Make the point visible with `org-show-context' after jumping to the mark."
24706 (when (and (derived-mode-p 'org-mode)
24707 (outline-invisible-p))
24708 (org-show-context 'mark-goto)))
24710 (eval-after-load "simple"
24711 '(defadvice pop-to-mark-command (after org-make-visible activate)
24712 "Make the point visible with `org-show-context'."
24713 (org-mark-jump-unhide)))
24715 (eval-after-load "simple"
24716 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24717 "Make the point visible with `org-show-context'."
24718 (org-mark-jump-unhide)))
24720 (eval-after-load "simple"
24721 '(defadvice pop-global-mark (after org-make-visible activate)
24722 "Make the point visible with `org-show-context'."
24723 (org-mark-jump-unhide)))
24725 ;; Make session.el ignore our circular variable
24726 (defvar session-globals-exclude)
24727 (eval-after-load "session"
24728 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24730 ;;;; Finish up
24732 (provide 'org)
24734 (run-hooks 'org-load-hook)
24736 ;;; org.el ends here