Codebase list org-mode-doc / bd04cab
New upstream version 9.6.8 Nicholas D Steeves 8 months ago
139 changed file(s) with 20693 addition(s) and 9697 deletion(s). Raw diff Collapse all Expand all
+0
-71
CONTRIBUTE less more
0 -*- mode: org; fill-column:70 -*-
1
2 The text below explains the rules for participating in Org mode
3 development.
4
5 * Org maintenance
6
7 Org maintenance is detailed on Worg: see [[https://orgmode.org/worg/org-maintenance.html][org-maintenance]].
8
9 * Main contribution rules
10
11 1. The master git repository is hosted publicly on [[https://savannah.gnu.org][savannah.gnu.org]].
12
13 : git clone https://git.savannah.gnu.org/git/emacs/org-mode.git
14
15 This is sufficient to start hacking and to produce patches that can
16 easily and consistently be applied to the main repository.
17
18 2. People who want to participate to the Org mode development can send
19 patches to this address:
20
21 : emacs-orgmode@gnu.org
22
23 3. If you are a regular contributor, you can request push access to
24 the repository by creating an account on [[https://savannah.gnu.org/account/register.php][savannah.gnu.org]] and by
25 [[https://savannah.gnu.org/git/?group=emacs][joining the Emacs group]].
26
27 After you have been added as a user with push privileges, you can
28 clone the repository like this:
29
30 : git clone USERNAME@git.savannah.gnu.org:/srv/git/emacs/org-mode.git
31
32 Replace =USERNAME= with your Savannah username.
33
34 4. By requesting push access, you acknowledge that you have read and
35 agreed with the following rules:
36
37 - Org mode is part of GNU Emacs. Therefore, we need to be very
38 conscious about changes moving into the Org mode core. These can
39 originate only from people who have signed the appropriate papers
40 with the Free Software Foundation. The files to which this
41 applies are:
42
43 - all *.el files in the lisp directory of the repository
44 - orgcard.tex and all *.org files in the doc/ directory
45
46 - Before making any significant changes, please explain and discuss
47 them on the mailing list [[mailto:emacs-orgmode@gnu.org][emacs-orgmode@gnu.org]].
48
49 This does obviously not apply to people who are maintaining their
50 own contributions to Org mode. Please just use the new mechanism
51 to make sure all changes end up in the right place.
52
53 We value a nice tone in our discussions: please check and respect
54 the [[https://www.gnu.org/philosophy/kind-communication.en.html][GNU Kind Communications Guidelines]].
55
56 - Org mode no longer uses ChangeLog entries to document changes.
57 Instead, special commit messages are used, as described in the
58 `CONTRIBUTE' file in the main Emacs repository.
59
60 - Among other things, Org mode is widely appreciated because of its
61 simplicity, cleanness and consistency. We should try to preserve
62 them and ask everyone to keep this in mind when posting changes.
63
64 See [[https://orgmode.org/worg/org-contribute.html][worg/org-contribute]] for guidance on how to contribute effectively.
65
66 * The =contrib/= directory
67
68 The git repository used to contain a =contrib/= directory. Files in
69 this directory were moved to a new [[https://git.sr.ht/~bzg/org-contrib][org-contrib]] repository before Org
70 9.5. You can install the new =org-contrib= from [[https://elpa.nongnu.org/nongnu/][NonGNU ELPA]].
0 See [[https://orgmode.org/worg/org-contribute.html][the org-contribute page on Worg]] for guidance on how to contribute
1 effectively.
2
3 We value a nice tone in our discussions: please check and respect the
4 [[https://www.gnu.org/philosophy/kind-communication.en.html][GNU Kind Communications Guidelines]].
5
6 * Contribute as a Org user
7
8 You can contribute by helping others in various channels.
9
10 See [[https://orgmode.org/worg/org-contribute.html#org99b8f3e][these directions]].
11
12 * Contribute as an Emacs Lisp hacker
13
14 You can contribute with bug reports and patches.
15
16 See these [[https://orgmode.org/worg/org-contribute.html#org069b83a][directions]].
17
18 * As a Org maintainer
19
20 We encourage you to volunteer to maintain one of the Org files.
21
22 Just [[mailto:emacs-orgmode@gnu.org][send an email to the list]] explaining which file and your
23 motivations.
24
25 See what is [[https://orgmode.org/worg/org-maintenance.html][the role of a maintainer]].
111111
112112 - Use example blocks for Org syntax instead of "begin_src org".
113113
114 - Prefer inline footnote definition when a footnote consists of a
115 single sentence.
116
114117 - Internal links to headlines always start with a star.
115118
116119 - Tags, node properties, are not shown with the surrounding colons.
2626 ../mk/guidesplit.pl $@/*
2727 endif
2828
29 # We increase GC threshold when generating documentation. This
30 # imrpoves the performance significantly. See
31 # https://yhetil.org/emacs-devel/9778F176-E724-4E61-B0FB-327BCDD316C0@acm.org
32 # Too high number may cause memory overflow (for example, it has
33 # happened in CI during automated build). We choose 50Mb threshold,
34 # based on the above discussion.
2935 org.texi: org-manual.org
3036 $(BATCH) \
3137 --eval '(add-to-list `load-path "../lisp")' \
3238 --eval '(load "../mk/org-fixup.el")' \
39 --eval '(setq gc-cons-threshold (* 50 1000 1000))' \
3340 --eval '(org-make-manual)'
3441
3542 orgguide.texi: org-guide.org
3643 $(BATCH) \
3744 --eval '(add-to-list `load-path "../lisp")' \
3845 --eval '(load "../mk/org-fixup.el")' \
46 --eval '(setq gc-cons-threshold (* 50 1000 1000))' \
3947 --eval '(org-make-guide)'
4048
4149 org-version.inc: org.texi
00 # SETUPFILE for Org manual
11
2 # Copyright (C) 2021 Free Software Foundation, Inc.
2 # Copyright (C) 2021-2023 Free Software Foundation, Inc.
33 #
44 # This file is part of GNU Emacs.
55 #
4848
4949 # The "kbd" macro turns KBD into @kbd{KBD}. Additionally, it
5050 # encloses case-sensitive special keys (SPC, RET...) within @key{...}.
51 #+macro: kbd (eval (let ((case-fold-search nil) (regexp (regexp-opt '("SPC" "RET" "LFD" "TAB" "BS" "ESC" "DELETE" "SHIFT" "Ctrl" "Meta" "Alt" "Cmd" "Super" "UP" "LEFT" "RIGHT" "DOWN") 'words))) (format "@@texinfo:@kbd{@@%s@@texinfo:}@@" (replace-regexp-in-string regexp "@@texinfo:@key{@@\\&@@texinfo:}@@" $1 t))))
51 #+macro: kbd (eval (org-texinfo-kbd-macro $1))
5252
99 :copying: t
1010 :END:
1111
12 Copyright \copy 2004--2021 Free Software Foundation, Inc.
12 Copyright \copy 2004--2023 Free Software Foundation, Inc.
1313
1414 #+begin_quote
1515 Permission is granted to copy, distribute and/or modify this document
140140
141141 Outlines make it possible to hide parts of the text in the buffer.
142142 Org uses just two commands, bound to {{{kbd(TAB)}}} and
143 {{{kbd{S-TAB)}}} to change the visibility in the buffer.
143 {{{kbd(S-TAB)}}} to change the visibility in the buffer.
144144
145145 #+attr_texinfo: :sep ,
146146 - {{{kbd(TAB)}}} ::
666666 :DESCRIPTION: More than just on/off.
667667 :END:
668668
669 You can use TODO keywords to indicate @emph{sequential} working progress
669 You can use TODO keywords to indicate /sequential/ working progress
670670 states:
671671
672672 #+begin_src emacs-lisp
10921092 =<2003-09-16 Tue 09:39>= or =<2003-09-16 Tue 12:00-12:30>=.
10931093 A timestamp can appear anywhere in the headline or body of an Org tree
10941094 entry. Its presence causes entries to be shown on specific dates in
1095 the agenda (see [[*The Weekly/daily Agenda]]). We distinguish:
1095 the agenda (see [[*The Weekly/Daily Agenda]]). We distinguish:
10961096
10971097 - Plain timestamp; Event; Appointment ::
10981098
11101110
11111111 A timestamp may contain a /repeater interval/, indicating that it
11121112 applies not only on the given date, but again and again after
1113 a certain interval of N days (d), weeks (w), months (m), or years
1114 (y). The following shows up in the agenda every Wednesday:
1113 a certain interval of N hours (h), days (d), weeks (w), months (m),
1114 or years (y). The following shows up in the agenda every Wednesday:
11151115
11161116 #+begin_example
11171117 ,* Pick up Sam at school
12931293 a {{{kbd(C-u)}}} prefix argument, select the target task from a list
12941294 of recently clocked tasks.
12951295
1296 The {{{kbd(l)}}} key may be used in the agenda (see [[*The Weekly/daily
1296 The {{{kbd(l)}}} key may be used in the agenda (see [[*The Weekly/Daily
12971297 Agenda]]) to show which tasks have been worked on or closed during
12981298 a day.
12991299
15261526 #+attr_texinfo: :sep ,
15271527 - {{{kbd(a)}}} ::
15281528
1529 Create the calendar-like agenda (see [[*The Weekly/daily Agenda]]).
1529 Create the calendar-like agenda (see [[*The Weekly/Daily Agenda]]).
15301530
15311531 - {{{kbd(t)}}}, {{{kbd(T)}}} ::
15321532
20652065 text. For example:
20662066
20672067 #+begin_example
2068 The Org homepage[fn:1] now looks a lot better than it used to.
2068 The Org website[fn:1] now looks a lot better than it used to.
20692069 ...
20702070 [fn:1] The link is: https://orgmode.org
20712071 #+end_example
1717 :END:
1818 #+cindex: summary
1919
20 Org is a mode for keeping notes, maintaining TODO lists, and project
21 planning with a fast and effective plain-text markup language. It
22 also is an authoring system with unique support for literate
23 programming and reproducible research.
24
25 Org is implemented on top of Outline mode, which makes it possible to
26 keep the content of large files well structured. Visibility cycling
27 and structure editing help to work with the tree. Tables are easily
28 created with a built-in table editor. Plain text URL-like links
29 connect to websites, emails, Usenet messages, BBDB entries, and any
30 files related to the projects.
20 Org Mode is an authoring tool and a TODO lists manager for GNU Emacs.
21 It relies on a lightweight plain-text markup language used in files
22 with the =.org= extension.
23
24 As an authoring tool, Org helps you write structured documents and
25 provides exporting facilities. Org files can also be used for literate
26 programming and reproducible research. As a TODO lists manager, Org
27 helps you organize your tasks in a flexible way, from daily needs to
28 detailed project-planning, allowing logging, multiple views on your
29 tasks, exporting your agendas, etc.
30
31 Org mode is implemented on top of Outline mode, which makes it
32 possible to keep the content of large files well structured.
33 Visibility cycling and structure editing help to work with the tree.
34 Tables are easily created with a built-in table editor. Plain text
35 URL-like links connect to websites, emails, Usenet messages, BBDB
36 entries, and any files related to the projects.
3137
3238 Org develops organizational tasks around notes files that contain
3339 lists or information about projects as plain text. Project planning
3440 and task management make use of metadata which is part of an outline
3541 node. Based on this data, specific entries can be extracted in
36 queries and create dynamic /agenda views/ that also integrate the
37 Emacs calendar and diary. Org can be used to implement many different
42 queries and create dynamic /agenda views/ that also integrate the Emacs
43 calendar and diary. Org can be used to implement many different
3844 project planning schemes, such as David Allen's GTD system.
3945
4046 Org files can serve as a single source authoring system with export to
6773 [[https://orgmode.org]].
6874
6975 #+cindex: print edition
70 An earlier version (7.3) of this manual is available as a [[http://www.network-theory.co.uk/org/manual/][paperback
71 book from Network Theory Ltd.]].
76 An earlier version (7.3) of this manual was available as a paperback
77 book from the Network Theory Ltd. publishing company, closed in 2009.
7278
7379 ** Installation
7480 :PROPERTIES:
7682 :END:
7783 #+cindex: installation
7884
79 Org is included in all recent distributions of GNU Emacs, so you
80 probably do not need to install it. Most users will simply activate
81 Org and begin exploring its many features.
85 Org is included in distributions of GNU Emacs, you probably do not
86 need to install it. Most users will simply activate Org and begin
87 exploring its features.
8288
8389 If, for one reason or another, you want to install Org on top of this
8490 pre-packaged version, you can use the Emacs package system or clone
85 Org's git repository.
86
87 We *strongly recommend* sticking to a single installation method.
91 Org's git repository. We *strongly recommend* sticking to a single
92 installation method.
93
94 When installing Org on top of the pre-packaged version, please note
95 that Org stable versions are meant to be fully compatible with the
96 last three stable versions of Emacs but not with older Emacsen.
8897
8998 *** Using Emacs packaging system
9099 :PROPERTIES:
120129 Org's version in =org-version.el= and Org's autoloads in
121130 =org-loaddefs.el=.
122131
123 Remember to add the correct load path as described in the method
124 above.
132 Make sure you set the load path correctly in your Emacs init file:
133
134 #+begin_src emacs-lisp
135 (add-to-list 'load-path "~/src/org-mode/lisp")
136 #+end_src
125137
126138 You can also compile with =make=, generate the documentation with
127139 =make doc=, create a local configuration with =make config= and
137149 :END:
138150
139151 Org's repository used to contain =contrib/= directory for add-ons
140 contributed by others. As of Org 9.5, the directory has bee moved to
141 this new dedicated [[https://git.sr.ht/~bzg/org-contrib][org-contrib]] repository, which you can install
142 separately.
152 contributed by others. As of Org 9.5, the directory has been moved to
153 the dedicated org-contrib [[https://git.sr.ht/~bzg/org-contrib][repository]], which you can install
154 separately as a [[https://elpa.nongnu.org/nongnu/org-contrib.html][package]] from NonGNU ELPA.
155
156 There are enough valuable packages maintained outside of the Org repository.
157 Worg has a list of [[https://orgmode.org/worg/org-contrib/index.html][org-contrib and external packages]], certainly it is not
158 exhaustive.
143159
144160 ** Activation
145161 :PROPERTIES:
152168 #+cindex: key bindings, global
153169
154170 Org mode buffers need Font Lock to be turned on: this is the default
155 in Emacs[fn:1].
171 in Emacs[fn:: If you do not use Font Lock globally turn it on in Org
172 buffer with =(add-hook 'org-mode-hook #'turn-on-font-lock)=.].
156173
157174 There are compatibility issues between Org mode and some other Elisp
158175 packages (see [[*Packages that conflict with Org mode]]). Please take the
204221
205222 If you find problems with Org, or if you have questions, remarks, or
206223 ideas about it, please send an email to the Org mailing list
207 [[mailto:emacs-orgmode@gnu.org]]. You can subscribe to the list [[https://lists.gnu.org/mailman/listinfo/emacs-orgmode][from this
208 web page]]. If you are not a member of the mailing list, your mail will
209 be passed to the list after a moderator has approved it[fn:2]. We ask
210 you to read and respect the [[https://www.gnu.org/philosophy/kind-communication.html][GNU Kind Communications Guidelines]] when
211 sending messages on this mailing list.
224 [[mailto:emacs-orgmode@gnu.org]]. You can subscribe to the list
225 [[https://lists.gnu.org/mailman/listinfo/emacs-orgmode][from this web
226 page]]. If you are not a member of the mailing list, your mail will
227 be passed to the list after a moderator has approved it[fn:: Please
228 consider subscribing to the mailing list in order to minimize the work
229 the mailing list moderators have to do.]. We ask you to read and
230 respect the
231 [[https://www.gnu.org/philosophy/kind-communication.html][GNU Kind
232 Communications Guidelines]] when sending messages on this mailing
233 list. Please allow up to one month for the response and followup if
234 no response is received on the bug report.
212235
213236 #+findex: org-version
214237 #+findex: org-submit-bug-report
255278 (add-to-list 'load-path (expand-file-name "/path/to/org-mode/lisp"))
256279 #+end_src
257280
281 If you are using Org mode version from Git repository, you can start
282 minimal session using make.
283
284 : # Bare Emacs
285 : make repro
286 : # or pass extra arguments
287 : make repro REPRO_ARGS="-l /path/to/minimal/config.el /tmp/bug.org"
288
258289 If an error occurs, a "backtrace" can be very useful---see below on
259290 how to create one. Often a small example file helps, along with clear
260291 information about:
379410 #+vindex: org-ctrl-k-protect-subtree
380411
381412 Headlines define the structure of an outline tree. Org headlines
382 start on the left margin[fn:3] with one or more stars followed by
413 start on the left margin[fn:1] with one or more stars followed by
383414 a space. For example:
384415
385416 #+begin_example
448479 #+end_example
449480
450481 #+vindex: org-cycle-emulate-tab
451 Point must be on a headline for this to work[fn:4].
482 Point must be on a headline for this to work[fn:: See, however, the
483 option ~org-cycle-emulate-tab~.].
452484
453485 - {{{kbd(S-TAB)}}} (~org-global-cycle~), {{{kbd(C-u TAB)}}} ::
454486
487519 Switch back to the startup visibility of the buffer (see [[*Initial
488520 visibility]]).
489521
490 - {{{kbd(C-u C-u C-u TAB)}}} (~outline-show-all~) ::
522 - {{{kbd(C-u C-u C-u TAB)}}} (~org-show-all~) ::
491523
492524 #+cindex: show all, command
493525 #+kindex: C-u C-u C-u TAB
494 #+findex: outline-show-all
526 #+findex: org-show-all
495527 Show all, including drawers.
496528
497529 - {{{kbd(C-c C-r)}}} (~org-reveal~) ::
507539 headings. With a double prefix argument, also show the entire
508540 subtree of the parent.
509541
510 - {{{kbd(C-c C-k)}}} (~outline-show-branches~) ::
542 - {{{kbd(C-c C-k)}}} (~org-show-branches~) ::
511543
512544 #+cindex: show branches, command
513545 #+kindex: C-c C-k
514 #+findex: outline-show-branches
546 #+findex: org-show-branches
515547 Expose all the headings of the subtree, but not their bodies.
516548
517 - {{{kbd(C-c TAB)}}} (~outline-show-children~) ::
549 - {{{kbd(C-c TAB)}}} (~org-show-children~) ::
518550
519551 #+cindex: show children, command
520552 #+kindex: C-c TAB
521 #+findex: outline-show-children
553 #+findex: org-show-children
522554 Expose all direct children of the subtree. With a numeric prefix
523555 argument {{{var(N)}}}, expose all children down to level
524556 {{{var(N)}}}.
527559
528560 #+kindex: C-c C-x b
529561 #+findex: org-tree-to-indirect-buffer
530 Show the current subtree in an indirect buffer[fn:5]. With
562 Show the current subtree in an indirect buffer[fn:2]. With
531563 a numeric prefix argument {{{var(N)}}}, go up to level {{{var(N)}}}
532564 and then take that tree. If {{{var(N)}}} is negative then go up
533565 that many levels. With a {{{kbd(C-u)}}} prefix, do not remove the
546578
547579 #+vindex: org-startup-folded
548580 When Emacs first visits an Org file, the global state is set to
549 ~showeverything~, i.e., all file content is visible[fn:6]. This can
550 be configured through the variable ~org-startup-folded~, or on
551 a per-file basis by adding one of the following lines anywhere in the
552 buffer:
581 ~showeverything~, i.e., all file content is visible[fn:: When
582 ~org-agenda-inhibit-startup~ is non-~nil~, Org does not honor the
583 default visibility state when first opening a file for the agenda (see
584 [[*Speeding Up Your Agendas]]).]. This can be configured through the
585 variable ~org-startup-folded~, or on a per-file basis by adding one of
586 the following lines anywhere in the buffer:
553587
554588 #+cindex: @samp{STARTUP}, keyword
555589 #+begin_example
582616 :END:
583617 #+cindex: edits, catching invisible
584618
585 #+vindex: org-catch-invisible-edits
619 #+vindex: org-fold-catch-invisible-edits
586620 Sometimes you may inadvertently edit an invisible part of the buffer
587621 and be confused on what has been edited and how to undo the mistake.
588 Setting ~org-catch-invisible-edits~ to non-~nil~ helps preventing
622 Setting ~org-fold-catch-invisible-edits~ to non-~nil~ helps preventing
589623 this. See the docstring of this option on how Org should catch
590624 invisible edits and process them.
591625
896930 An important feature of Org mode is the ability to construct /sparse
897931 trees/ for selected information in an outline tree, so that the entire
898932 document is folded as much as possible, but the selected information
899 is made visible along with the headline structure above it[fn:7].
900 Just try it out and you will see immediately how it works.
933 is made visible along with the headline structure above it[fn:: See
934 also the variable ~org-show-context-detail~ to decide how much context
935 is shown around each match.]. Just try it out and you will see
936 immediately how it works.
901937
902938 Org mode contains several commands creating such trees, all these
903939 commands can be accessed through a dispatcher:
915951 #+kindex: C-c / /
916952 #+findex: org-occur
917953 #+vindex: org-remove-highlights-with-change
918 Prompts for a regexp (see [[*Regular Expressions]]) and shows a sparse
919 tree with all matches. If the match is in a headline, the headline
920 is made visible. If the match is in the body of an entry, headline
921 and body are made visible. In order to provide minimal context,
922 also the full hierarchy of headlines above the match is shown, as
923 well as the headline following the match. Each match is also
924 highlighted; the highlights disappear when the buffer is changed by
925 an editing command, or by pressing {{{kbd(C-c C-c)}}}[fn:8]. When
926 called with a {{{kbd(C-u)}}} prefix argument, previous highlights
927 are kept, so several calls to this command can be stacked.
954 Prompts for a regexp (see [[*Regular Expressions]]) and shows a
955 sparse tree with all matches. If the match is in a headline, the
956 headline is made visible. If the match is in the body of an entry,
957 headline and body are made visible. In order to provide minimal
958 context, also the full hierarchy of headlines above the match is
959 shown, as well as the headline following the match. Each match is
960 also highlighted; the highlights disappear when the buffer is
961 changed by an editing command, or by pressing {{{kbd(C-c
962 C-c)}}}[fn:: This depends on the option
963 ~org-remove-highlights-with-change~.]. When called with a
964 {{{kbd(C-u)}}} prefix argument, previous highlights are kept, so
965 several calls to this command can be stacked.
928966
929967 - {{{kbd(M-g n)}}} or {{{kbd(M-g M-n)}}} (~next-error~) ::
930968
9851023 Org knows ordered lists, unordered lists, and description lists.
9861024
9871025 #+attr_texinfo: :indic @bullet
988 - /Unordered/ list items start with =-=, =+=, or =*=[fn:9] as bullets.
1026 - /Unordered/ list items start with =-=, =+=, or =*=[fn:3] as bullets.
9891027
9901028 -
9911029 #+vindex: org-plain-list-ordered-item-terminator
9921030 #+vindex: org-alphabetical-lists
993 /Ordered/ list items start with a numeral followed by either
994 a period or a right parenthesis[fn:10], such as =1.= or =1)=[fn:11]
995 If you want a list to start with a different value---e.g.,
996 20---start the text of the item with =[@20]=[fn:12]. Those
997 constructs can be used in any item of the list in order to enforce
998 a particular numbering.
1031 /Ordered/ list items start with a numeral followed by either a
1032 period or a right parenthesis[fn:: You can filter out any of them by
1033 configuring ~org-plain-list-ordered-item-terminator~.], such as =1.=
1034 or =1)=[fn:4] If you want a list to start with a different
1035 value---e.g., 20---start the text of the item with =[@20]=[fn:5].
1036 Those constructs can be used in any item of the list in order to
1037 enforce a particular numbering.
9991038
10001039 - /Description/ list items are unordered list items, and contain the
10011040 separator =::= to distinguish the description /term/ from the
10741113 #+kindex: M-RET
10751114 #+findex: org-insert-heading
10761115 #+vindex: org-M-RET-may-split-line
1077 Insert new item at current level. With a prefix argument, force
1078 a new heading (see [[*Structure Editing]]). If this command is used in
1079 the middle of an item, that item is /split/ in two, and the second
1080 part becomes the new item[fn:13]. If this command is executed
1081 /before item's body/, the new item is created /before/ the current
1082 one.
1116 Insert new item at current level. With a prefix argument, force a
1117 new heading (see [[*Structure Editing]]). If this command is used
1118 in the middle of an item, that item is /split/ in two, and the
1119 second part becomes the new item[fn:: If you do not want the item to
1120 be split, customize the variable ~org-M-RET-may-split-line~.]. If
1121 this command is executed /before item's body/, the new item is
1122 created /before/ the current one.
10831123
10841124 - {{{kbd(M-S-RET)}}} ::
10851125
10941134 #+vindex: org-support-shift-select
10951135 #+vindex: org-list-use-circular-motion
10961136 Jump to the previous/next item in the current list, but only if
1097 ~org-support-shift-select~ is off[fn:14]. If not, you can still use
1098 paragraph jumping commands like {{{kbd(C-UP)}}} and
1099 {{{kbd(C-DOWN)}}} to quite similar effect.
1137 ~org-support-shift-select~ is off[fn:: If you want to cycle around
1138 items that way, you may customize ~org-list-use-circular-motion~.].
1139 If not, you can still use paragraph jumping commands like
1140 {{{kbd(C-UP)}}} and {{{kbd(C-DOWN)}}} to quite similar effect.
11001141
11011142 - {{{kbd(M-UP)}}}, {{{kbd(M-DOWN)}}} ::
11021143
11031144 #+kindex: M-UP
11041145 #+kindex: M-DOWN
1105 Move the item including subitems up/down[fn:15], i.e., swap with
1106 previous/next item of same indentation. If the list is ordered,
1107 renumbering is automatic.
1146 Move the item including subitems up/down[fn:: See
1147 ~org-list-use-circular-motion~ for a cyclic behavior.], i.e., swap
1148 with previous/next item of same indentation. If the list is
1149 ordered, renumbering is automatic.
11081150
11091151 - {{{kbd(M-LEFT)}}}, {{{kbd(M-RIGHT)}}} ::
11101152
12061248 #+findex: org-insert-drawer
12071249 You can interactively insert a drawer at point by calling
12081250 ~org-insert-drawer~, which is bound to {{{kbd(C-c C-x d)}}}. With an
1209 active region, this command puts the region inside the drawer. With
1210 a prefix argument, this command calls ~org-insert-property-drawer~,
1211 which creates a =PROPERTIES= drawer right below the current headline.
1212 Org mode uses this special drawer for storing properties (see
1213 [[*Properties and Columns]]). You cannot use it for anything else.
1251 active region, this command puts the region inside the drawer. With a
1252 prefix argument, this command calls non-interactive function
1253 ~org-insert-property-drawer~, which creates a =PROPERTIES= drawer
1254 right below the current headline. Org mode uses this special drawer
1255 for storing properties (see [[*Properties and Columns]]). You cannot use
1256 it for anything else.
12141257
12151258 Completion over drawer keywords is also possible using
1216 {{{kbd(M-TAB)}}}[fn:16].
1259 {{{kbd(M-TAB)}}}[fn:6].
12171260
12181261 Visibility cycling (see [[*Visibility Cycling]]) on the headline hides and
12191262 shows the entry, but keep the drawer collapsed to a single line. In
12731316 #+cindex: table syntax
12741317 Org makes it easy to format tables in plain ASCII. Any line with =|=
12751318 as the first non-whitespace character is considered part of a table.
1276 =|= is also the column separator[fn:17]. Moreover, a line starting
1277 with =|-= is a horizontal rule. It separates rows explicitly. Rows
1278 before the first horizontal rule are header lines. A table might look
1279 like this:
1319 =|= is also the column separator[fn:: To insert a vertical bar into a
1320 table field, use =\vert= or, inside a word =abc\vert{}def=.].
1321 Moreover, a line starting with =|-= is a horizontal rule. It
1322 separates rows explicitly. Rows before the first horizontal rule are
1323 header lines. A table might look like this:
12801324
12811325 #+begin_example
12821326 | Name | Phone | Age |
13571401 - {{{kbd(M-x org-table-blank-field)}}} ::
13581402
13591403 #+findex: org-table-blank-field
1360 Blank the field at point.
1404 Blank the current table field or active region.
13611405
13621406 - {{{kbd(S-TAB)}}} (~org-table-previous-field~) ::
13631407
18381882 in any other spreadsheet, you may reference fields with
18391883 a letter/number combination like =B3=, meaning the second field in the
18401884 third row. However, Org prefers to use another, more general
1841 representation that looks like this:[fn:18]
1885 representation that looks like this:[fn:7]
18421886
18431887 : @ROW$COLUMN
18441888
19451989 #+texinfo: @noindent
19461990 For the second and third examples, table {{{var(FOO)}}} must have at
19471991 least as many rows or columns as the current table. Note that this is
1948 inefficient[fn:19] for large number of rows.
1992 inefficient[fn:: The computation time scales as O(N^2) because table
1993 {{{var(FOO)}}} is parsed for each field to be copied.] for large
1994 number of rows.
19491995
19501996 **** Named references
19511997 :PROPERTIES:
19732019 entry and in the hierarchy above it. If you have the =constants.el=
19742020 package, it will also be used to resolve constants, including natural
19752021 constants like =$h= for Planck's constant, and units like =$km= for
1976 kilometers[fn:20]. Column names and parameters can be specified in
2022 kilometers[fn:8]. Column names and parameters can be specified in
19772023 special table lines. These are described below, see [[*Advanced
19782024 features]]. All names must start with a letter, and further consist
19792025 of letters and numbers.
20942140 display for floating point numbers you may alternatively provide
20952141 a ~printf~ format specifier to reformat the Calc result after it has
20962142 been passed back to Org instead of letting Calc already do the
2097 formatting[fn:21]. A few examples:
2143 formatting[fn:9]. A few examples:
20982144
20992145 | =$1+$2= | Sum of first and second field |
21002146 | =$1+$2;%.2f= | Same, format result to two decimals |
21232169 required to not convert empty fields to 0. =f-1= is an optional
21242170 Calc format string similar to =%.1f= but leaves empty results empty.
21252171
2126 - =if(typeof(vmean($1..$7)) =​= 12, string(""), vmean($1..$7); E= ::
2172 - =if(typeof(vmean($1..$7)) =​= 12, string(""), vmean($1..$7)); E= ::
21272173
21282174 Mean value of a range unless there is any empty field. Every field
21292175 in the range that is empty is replaced by =nan= which lets =vmean=
26192665 #+cindex: debugging, of table formulas
26202666
26212667 When the evaluation of a formula leads to an error, the field content
2622 becomes the string =#ERROR=. If you would like to see what is going
2623 on during variable substitution and calculation in order to find
2624 a bug, turn on formula debugging in the Tbl menu and repeat the
2625 calculation, for example by pressing {{{kbd(C-u C-u C-c = RET)}}} in
2626 a field. Detailed information are displayed.
2668 becomes the string =#ERROR=. If you want to see what is going on
2669 during variable substitution and calculation in order to find a bug,
2670 turn on formula debugging in the Tbl menu and repeat the calculation,
2671 for example by pressing {{{kbd(C-u C-u C-c = RET)}}} in a field.
2672 Detailed information are displayed.
26272673
26282674 *** Updating the table
26292675 :PROPERTIES:
26812727 :END:
26822728
26832729 If you want the recalculation of fields to happen automatically, or if
2684 you want to be able to assign /names/[fn:22] to fields and columns,
2685 you need to reserve the first column of the table for special marking
2686 characters.
2730 you want to be able to assign /names/[fn:: Such names must start with
2731 an alphabetic character and use only alphanumeric/underscore
2732 characters.] to fields and columns, you need to reserve the first
2733 column of the table for special marking characters.
26872734
26882735 - {{{kbd(C-#)}}} (~org-table-rotate-recalc-marks~) ::
26892736
28652912 - transpose ::
28662913
28672914 When =y=, =yes=, or =t= attempt to transpose the table data before
2868 plotting. Also recognises the shorthand option =trans=.
2915 plotting. Also recognizes the shorthand option =trans=.
28692916
28702917 - =type= ::
28712918
28722919 Specify the type of the plot, by default one of =2d=, =3d=, =radar=, or =grid=.
2873 Available types can be customised with ~org-plot/preset-plot-types~.
2920 Available types can be customized with ~org-plot/preset-plot-types~.
28742921
28752922 - =with= ::
28762923
29903037 #+cindex: angle bracket links
29913038 #+cindex: plain links
29923039 Org recognizes plain URIs, possibly wrapped within angle
2993 brackets[fn:23], and activate them as clickable links.
3040 brackets[fn:10], and activate them as clickable links.
29943041
29953042 #+cindex: bracket links
29963043 The general link format, however, looks like this:
30343081
30353082 If you place point at the beginning or just behind the end of the
30363083 displayed text and press {{{kbd(BS)}}}, you remove
3037 the---invisible---bracket at that location[fn:24]. This makes the link
3084 the---invisible---bracket at that location[fn:: More accurately, the
3085 precise behavior depends on how point arrived there---see
3086 [[info:elisp#Invisible Text][Invisible Text]].]. This makes the link
30383087 incomplete and the internals are again displayed as plain text.
30393088 Inserting the missing bracket hides the link internals again. To show
3040 the internal structure of all links, use the menu: Org \rarr Hyperlinks \rarr
3041 Literal links.
3089 the internal structure of all links, use the menu: Org \rarr
3090 Hyperlinks \rarr Literal links.
30423091
30433092 ** Internal Links
30443093 :PROPERTIES:
30573106 a document. Most notably, a construct like =[[#my-custom-id]]=
30583107 specifically targets the entry with the =CUSTOM_ID= property set to
30593108 =my-custom-id=. Also, an internal link looking like =[[*Some
3060 section]]= points to a headline with the name =Some section=[fn:25].
3109 section]]= points to a headline with the name =Some section=[fn:11].
30613110
30623111 #+cindex: targets, for links
30633112 When the link does not belong to any of the cases above, Org looks for
30903139 During export, internal links are used to mark objects and assign them
30913140 a number. Marked objects are then referenced by links pointing to
30923141 them. In particular, links without a description appear as the number
3093 assigned to the marked object[fn:26]. In the following excerpt from
3094 an Org buffer
3142 assigned to the marked object[fn:: When targeting a =NAME= keyword,
3143 the =CAPTION= keyword is mandatory in order to get proper numbering
3144 (see [[*Captions]]).]. In the following excerpt from an Org buffer
30953145
30963146 #+begin_example
30973147 1. one item
32443294 | | =/ssh:me@some.where:papers/last.pdf= (same as above) |
32453295 | | =file:sometextfile::NNN= (jump to line number) |
32463296 | | =file:projects.org= |
3247 | | =file:projects.org::some words= (text search)[fn:27] |
3297 | | =file:projects.org::some words= (text search)[fn:12] |
32483298 | | =file:projects.org::*task title= (headline search) |
32493299 | | =file:projects.org::#custom-id= (headline search) |
32503300 | attachment | =attachment:projects.org= |
33273377
33283378 For Org files, if there is a =<<target>>= at point, the link points
33293379 to the target. Otherwise it points to the current headline, which
3330 is also the description[fn:28].
3380 is also the description.
33313381
33323382 #+vindex: org-id-link-to-org-use-id
33333383 #+cindex: @samp{CUSTOM_ID}, property
33353385 If the headline has a =CUSTOM_ID= property, store a link to this
33363386 custom ID. In addition or alternatively, depending on the value of
33373387 ~org-id-link-to-org-use-id~, create and/or use a globally unique
3338 =ID= property for the link[fn:29]. So using this command in Org
3339 buffers potentially creates two links: a human-readable link from
3340 the custom ID, and one that is globally unique and works even if the
3341 entry is moved from file to file. The =ID= property can be either a
3342 UUID (default) or a timestamp, depending on ~org-id-method~. Later,
3343 when inserting the link, you need to decide which one to use.
3388 =ID= property for the link[fn:: The Org Id library must first be
3389 loaded, either through ~org-customize~, by enabling ~id~ in
3390 ~org-modules~, or by adding =(require 'org-id)= in your Emacs init
3391 file.]. So using this command in Org buffers potentially creates
3392 two links: a human-readable link from the custom ID, and one that is
3393 globally unique and works even if the entry is moved from file to
3394 file. The =ID= property can be either a UUID (default) or a
3395 timestamp, depending on ~org-id-method~. Later, when inserting the
3396 link, you need to decide which one to use.
33443397
33453398 - /Email/News clients: VM, Rmail, Wanderlust, MH-E, Gnus/ ::
33463399
33513404 ~org-link-email-description-format~. By default, it refers to the
33523405 addressee and the subject.
33533406
3354 - /Web browsers: W3, W3M and EWW/ ::
3407 - /Web browsers: W3M and EWW/ ::
33553408
33563409 Here the link is the current URL, with the page title as the
33573410 description.
33973450 #+cindex: completion, of links
33983451 #+cindex: inserting links
33993452 #+vindex: org-link-keep-stored-after-insertion
3400 Insert a link[fn:30]. This prompts for a link to be inserted into
3453 Insert a link[fn:13]. This prompts for a link to be inserted into
34013454 the buffer. You can just type a link, using text for an internal
34023455 link, or one of the link type prefixes mentioned in the examples
34033456 above. The link is inserted into the buffer, along with
3404 a descriptive text[fn:31]. If some text was selected at this time,
3457 a descriptive text[fn:14]. If some text was selected at this time,
34053458 it becomes the default description.
34063459
34073460 - /Inserting stored links/ ::
34163469 prefixes like =http= or =ftp=, including the prefixes defined
34173470 through link abbreviations (see [[*Link Abbreviations]]). If you
34183471 press {{{kbd(RET)}}} after inserting only the prefix, Org offers
3419 specific completion support for some link types[fn:32]. For
3420 example, if you type {{{kbd(f i l e RET)}}}---alternative access:
3421 {{{kbd(C-u C-c C-l)}}}, see below---Org offers file name
3422 completion, and after {{{kbd(b b d b RET)}}} you can complete
3423 contact names.
3472 specific completion support for some link types[fn:: This works if
3473 a function has been defined in the ~:complete~ property of a link
3474 in ~org-link-parameters~.]. For example, if you type {{{kbd(f i l
3475 e RET)}}}---alternative access: {{{kbd(C-u C-c C-l)}}}, see
3476 below---Org offers file name completion, and after {{{kbd(b b d b
3477 RET)}}} you can complete contact names.
34243478
34253479 - {{{kbd(C-u C-c C-l)}}} ::
34263480
34873541 #+vindex: org-link-use-indirect-buffer-for-internals
34883542 #+kindex: mouse-3
34893543 Like {{{kbd(mouse-2)}}}, but force file links to be opened with
3490 Emacs, and internal links to be displayed in another window[fn:33].
3544 Emacs, and internal links to be displayed in another window[fn:: See
3545 the variable ~org-link-use-indirect-buffer-for-internals~.].
34913546
34923547 - {{{kbd(C-c %)}}} (~org-mark-ring-push~) ::
34933548
35653620 (setq org-link-abbrev-alist
35663621 '(("bugzilla" . "http://10.1.2.9/bugzilla/show_bug.cgi?id=")
35673622 ("Nu Html Checker" . "https://validator.w3.org/nu/?doc=%h")
3568 ("duckduckgo" . "https://duckduckgo.com/?q=%s")
3569 ("omap" . "http://nominatim.openstreetmap.org/search?q=%s&polygon=1")
3623 ("duckduckgo" . "https://duckduckgo.com/?q=%s")
3624 ("omap" . "https://nominatim.openstreetmap.org/search?q=%s&polygon=1")
35703625 ("ads" . "https://ui.adsabs.harvard.edu/search/q=%20author%3A\"%s\"")))
35713626 #+end_src
35723627
35953650
35963651 #+cindex: @samp{LINK}, keyword
35973652 #+begin_example
3598 ,#+LINK: bugzilla http://10.1.2.9/bugzilla/show_bug.cgi?id=
3653 ,#+LINK: bugzilla https://10.1.2.9/bugzilla/show_bug.cgi?id=
35993654 ,#+LINK: duckduckgo https://duckduckgo.com/?q=%s
3655 ,#+LINK: "Nu Html Checker" https://validator.w3.org/nu/?doc=%h
36003656 #+end_example
3657
3658 The abbreviations containing spaces must be quoted.
36013659
36023660 In-buffer completion (see [[*Completion]]) can be used after =[= to
36033661 complete link abbreviations. You may also define a Lisp function that
36213679
36223680 File links can contain additional information to make Emacs jump to a
36233681 particular location in the file when following a link. This can be a
3624 line number or a search option after a double colon[fn:34]. For
3682 line number or a search option after a double colon[fn:: For backward
3683 compatibility, line numbers can also follow a single colon.]. For
36253684 example, when the command ~org-store-link~ creates a link (see
3626 [[*Handling Links]]) to a file, it encodes the words in the current line
3627 as a search string that can be used to find this line back later when
3628 following the link with {{{kbd(C-c C-o)}}}.
3685 [[*Handling Links]]) to a file, it encodes the words in the current
3686 line as a search string that can be used to find this line back later
3687 when following the link with {{{kbd(C-c C-o)}}}.
36293688
36303689 Note that all search options apply for Attachment links in the same
36313690 way that they apply for File links.
37053764 :END:
37063765 #+cindex: TODO items
37073766
3708 Org mode does not maintain TODO lists as separate documents[fn:35].
3709 Instead, TODO items are an integral part of the notes file, because
3710 TODO items usually come up while taking notes! With Org mode, simply
3711 mark any entry in a tree as being a TODO item. In this way,
3712 information is not duplicated, and the entire context from which the
3713 TODO item emerged is always present.
3767 Org mode does not maintain TODO lists as separate documents[fn:: Of
3768 course, you can make a document that contains only long lists of TODO
3769 items, but this is not required.]. Instead, TODO items are an
3770 integral part of the notes file, because TODO items usually come up
3771 while taking notes! With Org mode, simply mark any entry in a tree as
3772 being a TODO item. In this way, information is not duplicated, and
3773 the entire context from which the TODO item emerged is always present.
37143774
37153775 Of course, this technique for managing TODO items scatters them
37163776 throughout your notes file. Org mode compensates for this by
38243884 #+cindex: workflow states as TODO keywords
38253885
38263886 You can use TODO keywords to indicate different, possibly /sequential/
3827 states in the process of working on an item, for example[fn:36]:
3887 states in the process of working on an item, for example[fn:: Changing
3888 the variable ~org-todo-keywords~ only becomes effective after
3889 restarting Org mode in a buffer.]:
38283890
38293891 #+begin_src emacs-lisp
38303892 (setq org-todo-keywords
38733935 (setq org-todo-keywords '((type "Fred" "Sara" "Lucy" "|" "DONE")))
38743936 #+end_src
38753937
3876 In this case, different keywords do not indicate states, but
3877 rather different types. So the normal work flow would be to assign
3878 a task to a person, and later to mark it DONE. Org mode supports this
3879 style by adapting the workings of the command {{{kbd(C-c
3880 C-t)}}}[fn:37]. When used several times in succession, it still
3881 cycles through all names, in order to first select the right type for
3882 a task. But when you return to the item after some time and execute
3883 {{{kbd(C-c C-t)}}} again, it will switch from any name directly to
3884 =DONE=. Use prefix arguments or completion to quickly select
3885 a specific name. You can also review the items of a specific TODO
3886 type in a sparse tree by using a numeric prefix to {{{kbd(C-c / t)}}}.
3887 For example, to see all things Lucy has to do, you would use
3888 {{{kbd(C-3 C-c / t)}}}. To collect Lucy's items from all agenda files
3889 into a single buffer, you would use the numeric prefix argument as
3890 well when creating the global TODO list: {{{kbd(C-3 M-x org-agenda
3891 t)}}}.
3938 In this case, different keywords do not indicate states, but rather
3939 different types. So the normal work flow would be to assign a task to
3940 a person, and later to mark it DONE. Org mode supports this style by
3941 adapting the workings of the command {{{kbd(C-c C-t)}}}[fn:: This is
3942 also true for the {{{kbd(t)}}} command in the agenda buffer.]. When
3943 used several times in succession, it still cycles through all names,
3944 in order to first select the right type for a task. But when you
3945 return to the item after some time and execute {{{kbd(C-c C-t)}}}
3946 again, it will switch from any name directly to =DONE=. Use prefix
3947 arguments or completion to quickly select a specific name. You can
3948 also review the items of a specific TODO type in a sparse tree by
3949 using a numeric prefix to {{{kbd(C-c / t)}}}. For example, to see all
3950 things Lucy has to do, you would use {{{kbd(C-3 C-c / t)}}}. To
3951 collect Lucy's items from all agenda files into a single buffer, you
3952 would use the numeric prefix argument as well when creating the global
3953 TODO list: {{{kbd(C-3 M-x org-agenda t)}}}.
38923954
38933955 *** Multiple keyword sets in one file
38943956 :PROPERTIES:
39494011 If you would like to quickly change an entry to an arbitrary TODO
39504012 state instead of cycling through the states, you can set up keys for
39514013 single-letter access to the states. This is done by adding the
3952 selection character after each keyword, in parentheses[fn:38]. For
3953 example:
4014 selection character after each keyword, in parentheses[fn:: All
4015 characters are allowed except =@=, =^= and =!=, which have a special
4016 meaning here.]. For example:
39544017
39554018 #+begin_src emacs-lisp
39564019 (setq org-todo-keywords
39624025 #+vindex: org-fast-tag-selection-include-todo
39634026 If you then press {{{kbd(C-c C-t)}}} followed by the selection key,
39644027 the entry is switched to this state. {{{kbd(SPC)}}} can be used to
3965 remove any TODO keyword from an entry[fn:39].
4028 remove any TODO keyword from an entry[fn:15].
39664029
39674030 *** Setting up keywords for individual files
39684031 :PROPERTIES:
40074070 keyword if no bar is there---must always mean that the item is DONE,
40084071 although you may use a different word. After changing one of these
40094072 lines, use {{{kbd(C-c C-c)}}} with point still in the line to make the
4010 changes known to Org mode[fn:40].
4073 changes known to Org mode[fn:: Org mode parses these lines only when
4074 Org mode is activated after visiting a file. {{{kbd(C-c C-c)}}} with
4075 point in a line starting with =#+= is simply restarting Org mode for
4076 the current buffer.].
40114077
40124078 *** Faces for TODO keywords
40134079 :PROPERTIES:
41504216 :END:
41514217
41524218 The most basic automatic logging is to keep track of /when/ a certain
4153 TODO item was marked as done. This can be achieved with[fn:41]
4219 TODO item was marked as done. This can be achieved with[fn:: The
4220 corresponding in-buffer setting is: =#+STARTUP: logdone=.]
41544221
41554222 #+begin_src emacs-lisp
41564223 (setq org-log-done 'time)
41644231 through further state cycling, that line is removed again. If you
41654232 turn the entry back to a non-TODO state (by pressing {{{kbd(C-c C-t
41664233 SPC)}}} for example), that line is also removed, unless you set
4167 ~org-closed-keep-when-no-todo~ to non-~nil~. If you want to record
4168 a note along with the timestamp, use[fn:42]
4234 ~org-closed-keep-when-no-todo~ to non-~nil~. If you want to record a
4235 note along with the timestamp, use[fn:: The corresponding in-buffer
4236 setting is: =#+STARTUP: lognotedone=.]
41694237
41704238 #+begin_src emacs-lisp
41714239 (setq org-log-done 'note)
41874255 You might want to automatically keep track of when a state change
41884256 occurred and maybe take a note about this change. You can either
41894257 record just a timestamp, or a time-stamped note. These records are
4190 inserted after the headline as an itemized list, newest first[fn:43].
4191 When taking a lot of notes, you might want to get the notes out of the
4192 way into a drawer (see [[*Drawers]]). Customize the variable
4193 ~org-log-into-drawer~ to get this behavior---the recommended drawer
4194 for this is called =LOGBOOK=[fn:44]. You can also overrule the
4195 setting of this variable for a subtree by setting a =LOG_INTO_DRAWER=
4196 property.
4258 inserted after the headline as an itemized list, newest first[fn:: See
4259 the variable ~org-log-states-order-reversed~.]. When taking a lot of
4260 notes, you might want to get the notes out of the way into a drawer
4261 (see [[*Drawers]]). Customize the variable ~org-log-into-drawer~ to
4262 get this behavior---the recommended drawer for this is called
4263 =LOGBOOK=[fn:: Note that the =LOGBOOK= drawer is unfolded when
4264 pressing {{{kbd(SPC)}}} in the agenda to show an entry---use
4265 {{{kbd(C-u SPC)}}} to keep it folded here.]. You can also overrule
4266 the setting of this variable for a subtree by setting a
4267 =LOG_INTO_DRAWER= property.
41974268
41984269 Since it is normally too much to record a note for every state, Org
41994270 mode expects configuration on a per-keyword basis for this. This is
42104281 You not only define global TODO keywords and fast access keys, but
42114282 also request that a time is recorded when the entry is set to =DONE=,
42124283 and that a note is recorded when switching to =WAIT= or
4213 =CANCELED=[fn:45]. The setting for =WAIT= is even more special: the
4284 =CANCELED=[fn:16]. The setting for =WAIT= is even more special: the
42144285 =!= after the slash means that in addition to the note taken when
42154286 entering the state, a timestamp should be recorded when /leaving/ the
42164287 =WAIT= state, if and only if the /target/ state does not configure
42594330 #+cindex: @samp{STYLE}, property
42604331
42614332 Org has the ability to track the consistency of a special category of
4262 TODO, called "habits." To use habits, you have to enable the ~habits~
4333 TODO, called "habits." To use habits, you have to enable the ~habit~
42634334 module by customizing the variable ~org-modules~.
42644335
42654336 A habit has the following properties:
44154486 #+findex: org-priority-up
44164487 #+findex: org-priority-down
44174488 #+vindex: org-priority-start-cycle-with-default
4418 Increase/decrease the priority of the current headline[fn:46]. Note
4419 that these keys are also used to modify timestamps (see [[*Creating
4420 Timestamps]]). See also [[*Packages that conflict with Org mode]], for
4421 a discussion of the interaction with shift-selection.
4489 Increase/decrease the priority of the current headline[fn:: See also
4490 the option ~org-priority-start-cycle-with-default~.]. Note that
4491 these keys are also used to modify timestamps (see [[*Creating
4492 Timestamps]]). See also [[*Packages that conflict with Org mode]],
4493 for a discussion of the interaction with shift-selection.
44224494
44234495 #+vindex: org-priority-highest
44244496 #+vindex: org-priority-lowest
44474519 #+vindex: org-agenda-todo-list-sublevels
44484520 It is often advisable to break down large tasks into smaller,
44494521 manageable subtasks. You can do this by creating an outline tree
4450 below a TODO item, with detailed subtasks on the tree[fn:47]. To keep
4451 an overview of the fraction of subtasks that have already been marked
4452 as done, insert either =[/]= or =[%]= anywhere in the headline. These
4453 cookies are updated each time the TODO status of a child changes, or
4454 when pressing {{{kbd(C-c C-c)}}} on the cookie. For example:
4522 below a TODO item, with detailed subtasks on the tree[fn:: To keep
4523 subtasks out of the global TODO list, see the option
4524 ~org-agenda-todo-list-sublevels~.]. To keep an overview of the
4525 fraction of subtasks that have already been marked as done, insert
4526 either =[/]= or =[%]= anywhere in the headline. These cookies are
4527 updated each time the TODO status of a child changes, or when pressing
4528 {{{kbd(C-c C-c)}}} on the cookie. For example:
44554529
44564530 #+begin_example
44574531 ,* Organize Party [33%]
44744548 include the word =recursive= into the value of the =COOKIE_DATA=
44754549 property.
44764550
4477 #+begin_example org
4551 #+begin_example
44784552 ,* Parent capturing statistics [2/20]
44794553 :PROPERTIES:
44804554 :COOKIE_DATA: todo recursive
44874561 #+begin_src emacs-lisp
44884562 (defun org-summary-todo (n-done n-not-done)
44894563 "Switch entry to DONE when all subentries are done, to TODO otherwise."
4490 (let (org-log-done org-log-states) ; turn off logging
4564 (let (org-log-done org-todo-log-states) ; turn off logging
44914565 (org-todo (if (= n-not-done 0) "DONE" "TODO"))))
44924566
44934567 (add-hook 'org-after-todo-statistics-hook #'org-summary-todo)
45034577 #+cindex: checkboxes
45044578
45054579 #+vindex: org-list-automatic-rules
4506 Every item in a plain list[fn:48] (see [[*Plain Lists]]) can be made into
4580 Every item in a plain list[fn:17] (see [[*Plain Lists]]) can be made into
45074581 a checkbox by starting it with the string =[ ]=. This feature is
45084582 similar to TODO items (see [[*TODO Items]]), but is more lightweight.
45094583 Checkboxes are not included into the global TODO list, so they are
45394613 entry. The cookies can be placed into a headline or into (the first
45404614 line of) a plain list item. Each cookie covers checkboxes of direct
45414615 children structurally below the headline/item on which the cookie
4542 appears[fn:49]. You have to insert the cookie yourself by typing
4543 either =[/]= or =[%]=. With =[/]= you get an =n out of m= result, as
4544 in the examples above. With =[%]= you get information about the
4545 percentage of checkboxes checked (in the above example, this would be
4546 =[50%]= and =[33%]=, respectively). In a headline, a cookie can count
4547 either checkboxes below the heading or TODO states of children, and it
4548 displays whatever was changed last. Set the property =COOKIE_DATA= to
4549 either =checkbox= or =todo= to resolve this issue.
4616 appears[fn:: Set the variable ~org-hierarchical-checkbox-statistics~
4617 if you want such cookies to count all checkboxes below the cookie, not
4618 just those belonging to direct children.]. You have to insert the
4619 cookie yourself by typing either =[/]= or =[%]=. With =[/]= you get
4620 an =n out of m= result, as in the examples above. With =[%]= you get
4621 information about the percentage of checkboxes checked (in the above
4622 example, this would be =[50%]= and =[33%]=, respectively). In a
4623 headline, a cookie can count either checkboxes below the heading or
4624 TODO states of children, and it displays whatever was changed last.
4625 Set the property =COOKIE_DATA= to either =checkbox= or =todo= to
4626 resolve this issue.
45504627
45514628 #+cindex: blocking, of checkboxes
45524629 #+cindex: checkbox blocking
45634640 #+findex: org-toggle-checkbox
45644641 Toggle checkbox status or---with prefix argument---checkbox presence
45654642 at point. With a single prefix argument, add an empty checkbox or
4566 remove the current one[fn:50]. With a double prefix argument, set
4567 it to =[-]=, which is considered to be an intermediate state.
4643 remove the current one[fn:: {{{kbd(C-u C-c C-c)}}} on the /first/
4644 item of a list with no checkbox adds checkboxes to the rest of the
4645 list.]. With a double prefix argument, set it to =[-]=, which is
4646 considered to be an intermediate state.
45684647
45694648 - {{{kbd(C-c C-x C-b)}}} (~org-toggle-checkbox~) ::
45704649
46764755 even though the final heading is not explicitly marked with those
46774756 tags. You can also set tags that all entries in a file should inherit
46784757 just as if these tags were defined in a hypothetical level zero that
4679 surrounds the entire file. Use a line like this[fn:51]
4758 surrounds the entire file. Use a line like this[fn:: As with all
4759 these in-buffer settings, pressing {{{kbd(C-c C-c)}}} activates any
4760 changes in the line.]
46804761
46814762 #+cindex: @samp{FILETAGS}, keyword
46824763 : #+FILETAGS: :Peter:Boss:Secret:
46904771 #+vindex: org-tags-match-list-sublevels
46914772 When a headline matches during a tags search while tag inheritance is
46924773 turned on, all the sublevels in the same tree---for a simple match
4693 form---match as well[fn:52]. The list of matches may then become
4694 very long. If you only want to see the first tags match in a subtree,
4695 configure the variable ~org-tags-match-list-sublevels~ (not
4696 recommended).
4774 form---match as well[fn:: This is only true if the search does not
4775 involve more complex tests including properties (see [[*Property
4776 Searches]]).]. The list of matches may then become very long. If you
4777 only want to see the first tags match in a subtree, configure the
4778 variable ~org-tags-match-list-sublevels~ (not recommended).
46974779
46984780 #+vindex: org-agenda-use-tag-inheritance
46994781 Tag inheritance is relevant when the agenda search tries to match
47434825 #+cindex: @samp{TAGS}, keyword
47444826 Org supports tag insertion based on a /list of tags/. By default this
47454827 list is constructed dynamically, containing all tags currently used in
4746 the buffer[fn:53]. You may also globally specify a hard list of tags
4747 with the variable ~org-tag-alist~. Finally you can set the default
4748 tags for a given file using the =TAGS= keyword, like
4828 the buffer[fn:: To extend this default list to all tags used in all
4829 agenda files (see [[*Agenda Views]]), customize the variable
4830 ~org-complete-tags-always-offer-all-agenda-tags~.]. You may also
4831 globally specify a hard list of tags with the variable
4832 ~org-tag-alist~. Finally you can set the default tags for a given
4833 file using the =TAGS= keyword, like
47494834
47504835 #+begin_example
47514836 ,#+TAGS: @work @home @tennisclub
48294914 If at least one tag has a selection key then pressing {{{kbd(C-c
48304915 C-c)}}} automatically presents you with a special interface, listing
48314916 inherited tags, the tags of the current headline, and a list of all
4832 valid tags with corresponding keys[fn:54].
4917 valid tags with corresponding keys[fn:: Keys are automatically
4918 assigned to tags that have no configured keys.].
48334919
48344920 Pressing keys assigned to tags adds or removes them from the list of
48354921 tags in the current line. Selecting a tag in a group of mutually
51005186
51015187 Depending on the value of ~org-use-property-inheritance~, a property
51025188 set this way is associated either with a single entry, or with the
5103 sub-tree defined by the entry, see [[*Property Inheritance]].
5189 subtree defined by the entry, see [[*Property Inheritance]].
51045190
51055191 You may define the allowed values for a particular property =Xyz= by
51065192 setting a property =Xyz_ALL=. This special property is /inherited/,
52045290 Set a property in the current entry. Both the property and the
52055291 value can be inserted using completion.
52065292
5207 - {{{kbd(S-RIGHT)}}} (~org-property-next-allowed-values~), {{{kbd(S-LEFT)}}} (~org-property-previous-allowed-value~) ::
5293 - {{{kbd(S-RIGHT)}}} (~org-property-next-allowed-value~), {{{kbd(S-LEFT)}}} (~org-property-previous-allowed-value~) ::
52085294
52095295 #+kindex: S-RIGHT
52105296 #+kindex: S-LEFT
54695555 - {{{var(SUMMARY-TYPE)}}} ::
54705556
54715557 The summary type. If specified, the column values for parent nodes
5472 are computed from the children[fn:55].
5558 are computed from the children[fn:: If more than one summary type
5559 applies to the same property, the parent values are computed
5560 according to the first of them.].
54735561
54745562 Supported summary types are:
54755563
54865574 | =:min= | Smallest time value in column. |
54875575 | =:max= | Largest time value. |
54885576 | =:mean= | Arithmetic mean of time values. |
5489 | =@min= | Minimum age[fn:56] (in days/hours/mins/seconds). |
5577 | =@min= | Minimum age[fn:18] (in days/hours/mins/seconds). |
54905578 | =@max= | Maximum age (in days/hours/mins/seconds). |
54915579 | =@mean= | Arithmetic mean of ages (in days/hours/mins/seconds). |
54925580 | =est+= | Add low-high estimates. |
55145602 days.
55155603
55165604 Here is an example for a complete columns definition, along with
5517 allowed values[fn:57].
5605 allowed values[fn:: Please note that the =COLUMNS= definition must be
5606 on a single line; it is wrapped here only because of formatting
5607 constraints.].
55185608
55195609 #+begin_example
55205610 :COLUMNS: %25ITEM %9Approved(Approved?){X} %Owner %11Status \
57875877
57885878 An alternative way to capture and process property values into a table
57895879 is provided by Eric Schulte's =org-collector.el=, which is a package
5790 in =org-contrib=[fn:58]. It provides a general API to collect
5880 in =org-contrib=[fn:: Contributed packages are not part of Emacs, but
5881 are distributed with the main distribution of Org---visit
5882 [[https://orgmode.org]].]. It provides a general API to collect
57915883 properties from entries in a certain scope, and arbitrary Lisp
57925884 expressions to process these values before inserting them into a table
57935885 or a dynamic block.
58205912
58215913 A timestamp is a specification of a date (possibly with a time or
58225914 a range of times) in a special format, either =<2003-09-16 Tue>= or
5823 =<2003-09-16 Tue 09:39>= or =<2003-09-16 Tue 12:00-12:30>=[fn:59].
5915 =<2003-09-16 Tue 09:39>= or =<2003-09-16 Tue 12:00-12:30>=[fn:19].
58245916 A timestamp can appear anywhere in the headline or body of an Org tree
58255917 entry. Its presence causes entries to be shown on specific dates in
58265918 the agenda (see [[*Weekly/daily agenda]]). We distinguish:
58465938 #+cindex: timestamp, with repeater interval
58475939 A timestamp may contain a /repeater interval/, indicating that it
58485940 applies not only on the given date, but again and again after
5849 a certain interval of N days (d), weeks (w), months (m), or years
5850 (y). The following shows up in the agenda every Wednesday:
5941 a certain interval of N hours (h), days (d), weeks (w), months (m),
5942 or years (y). The following shows up in the agenda every Wednesday:
58515943
58525944 #+begin_example
58535945 ,* Pick up Sam at school
58585950
58595951 #+cindex: diary style timestamps
58605952 #+cindex: sexp timestamps
5953 # Mentioned inside the footnote.
5954 #+findex: org-date
5955 #+findex: org-anniversary
5956 #+findex: org-cyclic
5957 #+findex: org-block
5958
58615959 For more complex date specifications, Org mode supports using the
5862 special expression diary entries implemented in the Emacs Calendar
5863 package[fn:60]. For example, with optional time:
5960 special expression diary entries implemented in the
5961 [[info:emacs#Special Diary Entries][Emacs Calendar package]][fn:20].
5962 For example, with optional time:
58645963
58655964 #+begin_example
58665965 ,* 22:00-23:00 The nerd meeting on every 2nd Thursday of the month
60126111 information, Org mode assumes that most of the time you want to enter
60136112 a date in the future: if you omit the month/year and the given
60146113 day/month is /before/ today, it assumes that you mean a future
6015 date[fn:61]. If the date has been automatically shifted into the
6114 date[fn:21]. If the date has been automatically shifted into the
60166115 future, the time prompt shows this with =(=>F)=.
60176116
60186117 For example, let's assume that today is *June 13, 2006*. Here is how
60776176
60786177 #+cindex: calendar, for selecting date
60796178 #+vindex: org-popup-calendar-for-date-prompt
6080 Parallel to the minibuffer prompt, a calendar is popped up[fn:62].
6081 When you exit the date prompt, either by clicking on a date in the
6082 calendar, or by pressing {{{kbd(RET)}}}, the date selected in the
6083 calendar is combined with the information entered at the prompt. You
6084 can control the calendar fully from the minibuffer:
6179 Parallel to the minibuffer prompt, a calendar is popped up[fn:: If you
6180 do not need/want the calendar, configure the variable
6181 ~org-popup-calendar-for-date-prompt~.]. When you exit the date
6182 prompt, either by clicking on a date in the calendar, or by pressing
6183 {{{kbd(RET)}}}, the date selected in the calendar is combined with the
6184 information entered at the prompt. You can control the calendar fully
6185 from the minibuffer:
60856186
60866187 #+kindex: <
60876188 #+kindex: >
61106211 | {{{kbd(<)}}} | Scroll calendar backward by one month. |
61116212 | {{{kbd(M-v)}}} | Scroll calendar forward by 3 months. |
61126213 | {{{kbd(C-v)}}} | Scroll calendar backward by 3 months. |
6113 | {{{kbd(C-.)}}} | Select today's date[fn:63] |
6214 | {{{kbd(C-.)}}} | Select today's date[fn:22] |
61146215
61156216 #+vindex: org-read-date-display-live
61166217 The actions of the date/time prompt may seem complex, but I assure you
61176218 they will grow on you, and you will start getting annoyed by pretty
61186219 much any other way of entering a date/time out there. To help you
61196220 understand what is going on, the current interpretation of your input
6120 is displayed live in the minibuffer[fn:64].
6221 is displayed live in the minibuffer[fn:: If you find this distracting,
6222 turn off the display with ~org-read-date-display-live~.].
61216223
61226224 *** Custom time format
61236225 :PROPERTIES:
62096311 date.
62106312
62116313 #+vindex: org-agenda-skip-scheduled-if-done
6212 The headline is listed under the given date[fn:65]. In addition,
6314 The headline is listed under the given date[fn:23]. In addition,
62136315 a reminder that the scheduled date has passed is present in the
62146316 compilation for /today/, until the entry is marked as done, i.e.,
62156317 the task is automatically forwarded until completed.
62616363 :END:
62626364
62636365 The following commands allow you to quickly insert a deadline or to
6264 schedule an item:[fn:66]
6366 schedule an item:[fn:24]
62656367
62666368 - {{{kbd(C-c C-d)}}} (~org-deadline~) ::
62676369
62736375 timestamp . When called with a prefix argument, also remove any
62746376 existing deadline from the entry. Depending on the variable
62756377 ~org-log-redeadline~, take a note when changing an existing
6276 deadline[fn:67].
6378 deadline[fn:: Note the corresponding =STARTUP= options
6379 =logredeadline=, =lognoteredeadline=, and =nologredeadline=.].
62776380
62786381 - {{{kbd(C-c C-s)}}} (~org-schedule~) ::
62796382
62856388 =CLOSED= timestamp. When called with a prefix argument, also remove
62866389 the scheduling date from the entry. Depending on the variable
62876390 ~org-log-reschedule~, take a note when changing an existing
6288 scheduling time[fn:68].
6391 scheduling time[fn:: Note the corresponding =STARTUP= options
6392 =logreschedule=, =lognotereschedule=, and =nologreschedule=.].
62896393
62906394 - {{{kbd(C-c / d)}}} (~org-check-deadlines~) ::
62916395
63256429
63266430 Some tasks need to be repeated again and again. Org mode helps to
63276431 organize such tasks using a so-called repeater in a =DEADLINE=,
6328 =SCHEDULED=, or plain timestamps[fn:69]. In the following example:
6432 =SCHEDULED=, or plain timestamps[fn:25]. In the following example:
63296433
63306434 #+begin_example
63316435 ,** TODO Pay the rent
63466450 #+vindex: org-todo-repeat-to-state
63476451 Deadlines and scheduled items produce entries in the agenda when they
63486452 are over-due, so it is important to be able to mark such an entry as
6349 done once you have done so. When you mark a =DEADLINE= or
6350 a =SCHEDULED= with the TODO keyword =DONE=, it no longer produces
6453 done once you have done so. When you mark a =DEADLINE= or a
6454 =SCHEDULED= with the TODO keyword =DONE=, it no longer produces
63516455 entries in the agenda. The problem with this is, however, is that
63526456 then also the /next/ instance of the repeated entry will not be
63536457 active. Org mode deals with this in the following way: when you try
63546458 to mark such an entry as done, using {{{kbd(C-c C-t)}}}, it shifts the
63556459 base date of the repeating timestamp by the repeater interval, and
6356 immediately sets the entry state back to TODO[fn:70]. In the example
6357 above, setting the state to =DONE= would actually switch the date like
6358 this:
6460 immediately sets the entry state back to TODO[fn:: In fact, the target
6461 state is taken from, in this sequence, the =REPEAT_TO_STATE= property,
6462 the variable ~org-todo-repeat-to-state~ if it is a string, the
6463 previous TODO state if ~org-todo-repeat-to-state~ is ~t~, or the first
6464 state of the TODO state sequence.]. In the example above, setting the
6465 state to =DONE= would actually switch the date like this:
63596466
63606467 #+begin_example
63616468 ,** TODO Pay the rent
63666473 i.e., ~org-todo~ with a numeric prefix argument of =-1=.
63676474
63686475 #+vindex: org-log-repeat
6369 A timestamp[fn:71] is added under the deadline, to keep a record that
6476 A timestamp[fn:26] is added under the deadline, to keep a record that
63706477 you actually acted on the previous instance of this deadline.
63716478
63726479 As a consequence of shifting the base date, this entry is no longer
64046511 Marking this DONE shifts the date to one month after today.
64056512
64066513 ,** TODO Wash my hands
6407 DEADLINE: <2019-04-05 08:00 Sun .+1h>
6514 DEADLINE: <2019-04-05 08:00 Fri .+1h>
64086515 Marking this DONE shifts the date to exactly one hour from now.
64096516 #+end_example
64106517
64366543 clock. When you stop working on that task, or when you mark the task
64376544 done, the clock is stopped and the corresponding time interval is
64386545 recorded. It also computes the total time spent on each
6439 subtree[fn:72] of a project. And it remembers a history or tasks
6546 subtree[fn:27] of a project. And it remembers a history or tasks
64406547 recently clocked, so that you can jump quickly between a number of
64416548 tasks absorbing your time.
64426549
64496556
64506557 #+vindex: org-clock-persist
64516558 When you clock into a new task after resuming Emacs, the incomplete
6452 clock[fn:73] is retrieved (see [[*Resolving idle time]]) and you are
6453 prompted about what to do with it.
6559 clock[fn:: To resume the clock under the assumption that you have
6560 worked on this task while outside Emacs, use =(setq org-clock-persist
6561 t)=.] is retrieved (see [[*Resolving idle time]]) and you are prompted
6562 about what to do with it.
64546563
64556564 *** Clocking commands
64566565 :PROPERTIES:
64866595 While the clock is running, Org shows the current clocking time in
64876596 the mode line, along with the title of the task. The clock time
64886597 shown is all time ever clocked for this task and its children. If
6489 the task has an effort estimate (see [[*Effort Estimates]]), the mode
6490 line displays the current clocking time against it[fn:74]. If the
6491 task is a repeating one (see [[*Repeated tasks]]), show only the time
6492 since the last reset of the task[fn:75]. You can exercise more
6493 control over show time with the =CLOCK_MODELINE_TOTAL= property. It
6494 may have the values =current= to show only the current clocking
6495 instance, =today= to show all time clocked on this tasks today---see
6496 also the variable ~org-extend-today-until~, ~all~ to include all
6497 time, or ~auto~ which is the default[fn:76]. Clicking with
6498 {{{kbd(mouse-1)}}} onto the mode line entry pops up a menu with
6499 clocking options.
6598 the task has an effort estimate (see [[*Effort Estimates]]), the
6599 mode line displays the current clocking time against it[fn:: To add
6600 an effort estimate "on the fly", hook a function doing this to
6601 ~org-clock-in-prepare-hook~.]. If the task is a repeating one (see
6602 [[*Repeated tasks]]), show only the time since the last reset of the
6603 task[fn:: The last reset of the task is recorded by the
6604 =LAST_REPEAT= property.]. You can exercise more control over show
6605 time with the =CLOCK_MODELINE_TOTAL= property. It may have the
6606 values =current= to show only the current clocking instance, =today=
6607 to show all time clocked on this tasks today---see also the variable
6608 ~org-extend-today-until~, ~all~ to include all time, or ~auto~ which
6609 is the default[fn:: See also the variable
6610 ~org-clock-mode-line-total~.]. Clicking with {{{kbd(mouse-1)}}}
6611 onto the mode line entry pops up a menu with clocking options.
65006612
65016613 - {{{kbd(C-c C-x C-o)}}} (~org-clock-out~) ::
65026614
65086620 computes the resulting time in inserts it after the time range as
65096621 ==>HH:MM=. See the variable ~org-log-note-clock-out~ for the
65106622 possibility to record an additional note together with the clock-out
6511 timestamp[fn:77].
6623 timestamp[fn:: The corresponding in-buffer setting is: =#+STARTUP:
6624 lognoteclock-out=.].
65126625
65136626 - {{{kbd(C-c C-x C-x)}}} (~org-clock-in-last~) ::
65146627
66516764 #+cindex: @samp{BEGIN clocktable}
66526765 #+begin_example
66536766 ,#+BEGIN: clocktable :maxlevel 2 :emphasize nil :scope file
6654 ,#+END: clocktable
6767 ,#+END:
66556768 #+end_example
66566769
66576770 #+vindex: org-clocktable-defaults
66886801 absolutely, or relative to the current time and may be any of these
66896802 formats:
66906803
6691 | =2007-12-31= | New year eve 2007 |
6692 | =2007-12= | December 2007 |
6693 | =2007-W50= | ISO-week 50 in 2007 |
6694 | =2007-Q2= | 2nd quarter in 2007 |
6695 | =2007= | the year 2007 |
6696 | =today=, =yesterday=, =today-N= | a relative day |
6697 | =thisweek=, =lastweek=, =thisweek-N= | a relative week |
6698 | =thismonth=, =lastmonth=, =thismonth-N= | a relative month |
6699 | =thisyear=, =lastyear=, =thisyear-N= | a relative year |
6700 | =untilnow=[fn:78] | all clocked time ever |
6804 | =2007-12-31= | New year eve 2007 |
6805 | =2007-12= | December 2007 |
6806 | =2007-W50= | ISO-week 50 in 2007 |
6807 | =2007-Q2= | 2nd quarter in 2007 |
6808 | =2007= | the year 2007 |
6809 | =today=, =yesterday=, =today-N= | a relative day |
6810 | =thisweek=, =lastweek=, =thisweek-N= | a relative week |
6811 | =thismonth=, =lastmonth=, =thismonth-N= | a relative month |
6812 | =thisyear=, =lastyear=, =thisyear-N= | a relative year |
6813 | =untilnow=[fn:: When using ~:step~, ~untilnow~ starts from the beginning of 2003, not the beginning of time.] | all clocked time ever |
67016814
67026815 #+vindex: org-clock-display-default-range
67036816 When this option is not set, Org falls back to the value in
67296842
67306843 - =:step= ::
67316844
6732 Set to =day=, =week=, =semimonth=, =month=, or =year= to split the
6845 Set to =day=, =week=, =semimonth=, =month=, =quarter=, or =year= to split the
67336846 table into chunks. To use this, either =:block=, or =:tstart= and
67346847 =:tend= are required.
67356848
67596872
67606873 - =:lang= ::
67616874
6762 Language[fn:79] to use for descriptive cells like "Task".
6875 Language[fn:: Language terms can be set through the variable
6876 ~org-clock-clocktable-language-setup~.] to use for descriptive cells
6877 like "Task".
67636878
67646879 - =:link= ::
67656880
67746889 - =:indent= ::
67756890
67766891 Indent each headline field according to its level.
6892
6893 - =:filetitle= ::
6894
6895 Show title in the file column if the file has a =#+title=.
67776896
67786897 - =:hidefiles= ::
67796898
68356954
68366955 #+begin_example
68376956 ,#+BEGIN: clocktable :maxlevel 2 :block today :scope tree1 :link t
6838 ,#+END: clocktable
6957 ,#+END:
68396958 #+end_example
68406959
68416960 #+texinfo: @noindent
6842 To use a specific time range you could write[fn:80]
6961 To use a specific time range you could write[fn:: Note that all
6962 parameters must be specified in a single line---the line is broken
6963 here only to fit it into the manual.]
68436964
68446965 #+begin_example
68456966 ,#+BEGIN: clocktable :tstart "<2006-08-10 Thu 10:00>"
68466967 :tend "<2006-08-10 Thu 12:00>"
6847 ,#+END: clocktable
6968 ,#+END:
68486969 #+end_example
68496970
68506971 #+texinfo: @noindent
68526973
68536974 #+begin_example
68546975 ,#+BEGIN: clocktable :tstart "<-1w>" :tend "<now>"
6855 ,#+END: clocktable
6976 ,#+END:
68566977 #+end_example
68576978
68586979 #+texinfo: @noindent
68606981
68616982 #+begin_example
68626983 ,#+BEGIN: clocktable :scope subtree :link t :formula %
6863 ,#+END: clocktable
6984 ,#+END:
68646985 #+end_example
68656986
68666987 #+texinfo: @noindent
68696990
68706991 #+begin_example
68716992 ,#+BEGIN: clocktable :scope agenda :block lastweek :compact t
6872 ,#+END: clocktable
6993 ,#+END:
68736994 #+end_example
68746995
68756996 *** Resolving idle time and continuous clocking
68957016 #+vindex: org-clock-x11idle-program-name
68967017 By customizing the variable ~org-clock-idle-time~ to some integer,
68977018 such as 10 or 15, Emacs can alert you when you get back to your
6898 computer after being idle for that many minutes[fn:81], and ask what
7019 computer after being idle for that many minutes[fn:28], and ask what
68997020 you want to do with the idle time. There will be a question waiting
69007021 for you when you get back, indicating how much idle time has passed
69017022 constantly updated with the current amount, as well as a set of
70647185
70657186 #+vindex: org-agenda-columns-add-appointments-to-effort-sum
70667187 If you switch to column view in the daily/weekly agenda, the effort
7067 column summarizes the estimated work effort for each day[fn:82], and
7068 you can use this to find space in your schedule. To get an overview
7069 of the entire part of the day that is committed, you can set the
7070 option ~org-agenda-columns-add-appointments-to-effort-sum~. The
7071 appointments on a day that take place over a specified time interval
7072 are then also added to the load estimate of the day.
7188 column summarizes the estimated work effort for each day[fn:: Please
7189 note the pitfalls of summing hierarchical data in a flat list (see
7190 [[*Using Column View in the Agenda]]).], and you can use this to find
7191 space in your schedule. To get an overview of the entire part of the
7192 day that is committed, you can set the option
7193 ~org-agenda-columns-add-appointments-to-effort-sum~. The appointments
7194 on a day that take place over a specified time interval are then also
7195 added to the load estimate of the day.
70737196
70747197 Effort estimates can be used in secondary agenda filtering that is
70757198 triggered with the {{{kbd(/)}}} key in the agenda (see [[*Commands in
70977220 #+findex: org-timer-start
70987221 Start or reset the relative timer. By default, the timer is set
70997222 to 0. When called with a {{{kbd(C-u)}}} prefix, prompt the user for
7100 a starting offset. If there is a timer string at point, this is
7101 taken as the default, providing a convenient way to restart taking
7102 notes after a break in the process. When called with a double
7103 prefix argument {{{kbd(C-u C-u)}}}, change all timer strings in the
7104 active region by a certain amount. This can be used to fix timer
7105 strings if the timer was not started at exactly the right moment.
7223 a starting offset. The prompt will default to a timer string at
7224 point (if any), providing a convenient way to restart taking notes
7225 after a break in the process. When called with a double prefix
7226 argument {{{kbd(C-u C-u)}}}, change all timer strings in the active
7227 region by a certain amount. This can be used to fix timer strings
7228 if the timer was not started at exactly the right moment.
71067229
71077230 - {{{kbd(C-c C-x ;)}}} (~org-timer-set-timer~) ::
71087231
71977320 By default, all level 1 headlines in the current buffer are
71987321 considered to be targets, but you can have more complex definitions
71997322 across a number of files. See the variable ~org-refile-targets~ for
7200 details. If you would like to select a location via
7201 a file-path-like completion along the outline path, see the
7202 variables ~org-refile-use-outline-path~ and
7323 details. If you would like to select a location via a
7324 file-path-like completion along the outline path, see the variables
7325 ~org-refile-use-outline-path~ and
72037326 ~org-outline-path-complete-in-steps~. If you would like to be able
72047327 to create new nodes as new parents for refiling on the fly, check
72057328 the variable ~org-refile-allow-creating-parent-nodes~. When the
7206 variable ~org-log-refile~[fn:83] is set, a timestamp or a note is
7207 recorded whenever an entry is refiled.
7329 variable ~org-log-refile~[fn:: Note the corresponding =STARTUP=
7330 options =logrefile=, =lognoterefile=, and =nologrefile=.] is set, a
7331 timestamp or a note is recorded whenever an entry is refiled.
72087332
72097333 - {{{kbd(C-u C-c C-w)}}} ::
72107334
73597483 #+vindex: org-cycle-open-archived-trees
73607484 It does not open when you attempt to do so with a visibility cycling
73617485 command (see [[*Visibility Cycling]]). You can force cycling archived
7362 subtrees with {{{kbd(C-TAB)}}}, or by setting the option
7486 subtrees with {{{kbd(C-c C-TAB)}}}, or by setting the option
73637487 ~org-cycle-open-archived-trees~. Also normal outline commands, like
7364 ~outline-show-all~, open archived subtrees.
7488 ~org-show-all~, open archived subtrees.
73657489
73667490 -
73677491 #+vindex: org-sparse-tree-open-archived-trees
74077531 child. If point is /not/ on a headline when this command is
74087532 invoked, check the level 1 trees.
74097533
7410 - {{{kbd(C-c C-TAB)}}} (~org-force-cycle-archived~) ::
7411
7412 #+kindex: C-TAB
7534 - {{{kbd(C-c C-TAB)}}} (~org-cycle-force-archived~) ::
7535
7536 #+kindex: C-c C-TAB
74137537 Cycle a tree even if it is tagged with =ARCHIVE=.
74147538
74157539 - {{{kbd(C-c C-x A)}}} (~org-archive-to-archive-sibling~) ::
74737597 - {{{kbd(M-x org-capture)}}} (~org-capture~) ::
74747598
74757599 #+findex: org-capture
7476 #+cindex: date tree
74777600 Display the capture templates menu. If you have templates defined
74787601 (see [[*Capture templates]]), it offers these templates for selection or
74797602 use a new Org outline node as the default template. It inserts the
76527775
76537776 #+vindex: org-default-notes-file
76547777 #+vindex: org-directory
7778 #+cindex: date tree
76557779 Specification of where the captured item should be placed. In Org
76567780 files, targets usually define a node. Entries will become children
76577781 of this node. Other types will be added to the table or list in the
76857809
76867810 - =(file+olp+datetree "filename" [ "Level 1 heading" ...])= ::
76877811
7688 This target[fn:84] creates a heading in a date tree[fn:85] for
7812 This target[fn:29] creates a heading in a date tree[fn:30] for
76897813 today's date. If the optional outline path is given, the tree
76907814 will be built under the node it is pointing to, instead of at top
76917815 level. Check out the ~:time-prompt~ and ~:tree-type~ properties
77107834 empty, an appropriate default template will be used. Otherwise this
77117835 is a string with escape codes, which will be replaced depending on
77127836 time and context of the capture call. You may also get this
7713 template string from a file[fn:86], or dynamically, from a function
7714 using either syntax:
7837 template string from a file[fn:: When the file name is not absolute,
7838 Org assumes it is relative to ~org-directory~.], or dynamically,
7839 from a function using either syntax:
77157840
77167841 : (file "/path/to/template-file")
77177842 : (function FUNCTION-RETURNING-THE-TEMPLATE)
78067931
78077932 Do not save the target file after finishing the capture.
78087933
7809 - ~:refile-targets :: Temporarily set ~org-refile-targets~ to the
7934 - ~:refile-targets~ :: Temporarily set ~org-refile-targets~ to the
78107935 value of this property.
78117936
7937 - ~:hook~ ::
7938
7939 A nullary function or list of nullary functions run before
7940 ~org-capture-mode-hook~ when the template is selected.
7941
7942 - ~:prepare-finalize~ ::
7943
7944 A nullary function or list of nullary functions run before
7945 ~org-capture-prepare-finalize-hook~ when the template is selected.
7946
7947 - ~:before-finalize~ ::
7948
7949 A nullary function or list of nullary functions run before
7950 ~org-capture-before-finalize-hook~ when the template is selected.
7951
7952 - ~:after-finalize~ ::
7953
7954 A nullary function or list of nullary functions run before
7955 ~org-capture-after-finalize-hook~ when the template is selected.
7956
78127957 **** Template expansion
78137958 :PROPERTIES:
78147959 :DESCRIPTION: Filling in information about time and context.
78157960 :END:
78167961
7817 In the template itself, special "%-escapes"[fn:87] allow dynamic
7818 insertion of content. The templates are expanded in the order given
7819 here:
7962 In the template itself, special "%-escapes"[fn:: If you need one of
7963 these sequences literally, escape the =%= with a backslash.] allow
7964 dynamic insertion of content. The templates are expanded in the order
7965 given here:
78207966
78217967 - =%[FILE]= ::
78227968
79468092 After completing the template, position point here.
79478093
79488094 #+vindex: org-store-link-props
7949 For specific link types, the following keywords are defined[fn:88]:
8095 For specific link types, the following keywords are defined[fn:: If
8096 you define your own link types (see [[*Adding Hyperlink Types]]), any
8097 property you store with ~org-store-link-props~ can be accessed in
8098 capture templates in a similar way.]:
79508099
79518100 #+vindex: org-link-from-user-regexp
79528101 | Link type | Available keywords |
79598108 | | =%:date= (message date header field) |
79608109 | | =%:date-timestamp= (date as active timestamp) |
79618110 | | =%:date-timestamp-inactive= (date as inactive timestamp) |
7962 | | =%:fromto= (either "to NAME" or "from NAME")[fn:89] |
8111 | | =%:fromto= (either "to NAME" or "from NAME")[fn:31] |
79638112 | gnus | =%:group=, for messages also all email fields |
79648113 | w3, w3m | =%:url= |
79658114 | info | =%:file=, =%:node= |
80188167 outline nodes. This makes working with attachments fully automated.
80198168 There is no decision needed for folder-name or location. ID-based
80208169 directories are by default located in the =data/= directory, which
8021 lives in the same directory where your Org file lives[fn:90].
8170 lives in the same directory where your Org file lives[fn:: If you move
8171 entries or Org files from one directory to another, you may want to
8172 configure ~org-attach-id-dir~ to contain an absolute path.].
80228173
80238174 When attachments are made using ~org-attach~ a default tag =ATTACH= is
80248175 added to the node that gets the attachments.
84158566
84168567 #+vindex: org-agenda-files
84178568 The information to be shown is normally collected from all /agenda
8418 files/, the files listed in the variable ~org-agenda-files~[fn:91].
8419 If a directory is part of this list, all files with the extension
8420 =.org= in this directory are part of the list.
8569 files/, the files listed in the variable ~org-agenda-files~[fn:: If
8570 the value of that variable is not a list, but a single file name, then
8571 the list of agenda files in maintained in that external file.]. If a
8572 directory is part of this list, all files with the extension =.org= in
8573 this directory are part of the list.
84218574
84228575 Thus, even if you only work with a single Org file, that file should
8423 be put into the list[fn:92]. You can customize ~org-agenda-files~,
8424 but the easiest way to maintain it is through the following commands
8576 be put into the list[fn:: When using the dispatcher, pressing
8577 {{{kbd(<)}}} before selecting a command actually limits the command to
8578 the current file, and ignores ~org-agenda-files~ until the next
8579 dispatcher command.]. You can customize ~org-agenda-files~, but the
8580 easiest way to maintain it is through the following commands
84258581
84268582 #+attr_texinfo: :sep and
84278583 - {{{kbd(C-c [)}}} (~org-agenda-file-to-front~) ::
85438699 Search for a regular expression in all agenda files and additionally
85448700 in the files listed in ~org-agenda-text-search-extra-files~. This
85458701 uses the Emacs command ~multi-occur~. A prefix argument can be used
8546 to specify the number of context lines for each match, default is
8547 1.
8702 to specify the number of context lines for each match, the default
8703 is 1.
85488704
85498705 - {{{kbd(#)}}} ::
85508706
85578713 - {{{kbd(<)}}} ::
85588714
85598715 #+kindex: < @r{(Agenda dispatcher)}
8560 Restrict an agenda command to the current buffer[fn:93]. If
8561 narrowing is in effect restrict to the narrowed part of the buffer.
8562 After pressing {{{kbd(<)}}}, you still need to press the character
8563 selecting the command.
8716 Restrict an agenda command to the current buffer[fn:: For backward
8717 compatibility, you can also press {{{kbd(1)}}} to restrict to the
8718 current buffer.]. If narrowing is in effect restrict to the
8719 narrowed part of the buffer. After pressing {{{kbd(<)}}}, you still
8720 need to press the character selecting the command.
85648721
85658722 - {{{kbd(< <)}}} ::
85668723
85678724 #+kindex: < < @r{(Agenda dispatcher)}
85688725 If there is an active region, restrict the following agenda command
8569 to the region. Otherwise, restrict it to the current
8570 subtree[fn:94]. After pressing {{{kbd(< <)}}}, you still need to
8571 press the character selecting the command.
8726 to the region. Otherwise, restrict it to the current subtree[fn::
8727 For backward compatibility, you can also press {{{kbd(0)}}} to
8728 restrict to the current region/subtree.]. After pressing {{{kbd(<
8729 <)}}}, you still need to press the character selecting the command.
85728730
85738731 - {{{kbd(*)}}} ::
85748732
86178775 #+cindex: org-agenda, command
86188776 Compile an agenda for the current week from a list of Org files.
86198777 The agenda shows the entries for each day. With a numeric prefix
8620 argument[fn:95]---like {{{kbd(C-u 2 1 M-x org-agenda a)}}}---you may
8778 argument[fn:32]---like {{{kbd(C-u 2 1 M-x org-agenda a)}}}---you may
86218779 set the number of days to be displayed.
86228780
86238781 #+vindex: org-agenda-span
86308788 is to start on the previous Monday (see
86318789 ~org-agenda-start-on-weekday~). You can also set the start date using
86328790 a date shift: =(setq org-agenda-start-day "+10d")= starts the agenda
8633 ten days from today in the future.
8791 ten days from today in the future. ~org-agenda-start-on-weekday~
8792 takes precedence over ~org-agenda-start-day~ in weekly and bi-weekly
8793 agendas.
86348794
86358795 Remote editing from the agenda buffer means, for example, that you can
86368796 change the dates of deadlines and appointments from the agenda buffer.
86768836 expression entries, and does it faster because there is no overhead
86778837 for first creating the diary display. Note that the expression
86788838 entries must start at the left margin, no whitespace is allowed before
8679 them, as seen in the following segment of an Org file:[fn:96]
8839 them, as seen in the following segment of an Org file:[fn:: The
8840 variable ~org-anniversary~ used in the example is just like
8841 ~diary-anniversary~, but the argument order is always according to ISO
8842 and therefore independent of the value of ~calendar-date-style~.]
86808843
86818844 #+begin_example
86828845 ,* Holidays
87888951 #+findex: org-todo-list
87898952 Show the global TODO list. This collects the TODO items from all
87908953 agenda files (see [[*Agenda Views]]) into a single buffer. By default,
8791 this lists items with a state the is not a DONE state. The buffer
8954 this lists items with a state that is not a DONE state. The buffer
87928955 is in Agenda mode, so there are commands to examine and manipulate
87938956 the TODO entries directly from that buffer (see [[*Commands in the
87948957 Agenda Buffer]]).
91789341 : <2005-05-10 Tue 20:30>--<2005-05-10 Tue 22:15>
91799342
91809343 #+vindex: org-agenda-search-headline-for-time
9181 In the headline of the entry itself, a time(range)---like =12:45= or
9182 a =8:30-1pm=---may also appear as plain text[fn:97].
9344 In the headline of the entry itself, a time(range)---like =12:45= or a
9345 =8:30-1pm=---may also appear as plain text[fn:: You can, however,
9346 disable this by setting ~org-agenda-search-headline-for-time~ variable
9347 to a ~nil~ value.].
91839348
91849349 If the agenda integrates the Emacs diary (see [[*Weekly/daily agenda]]),
91859350 time specifications in diary entries are recognized as well.
92699434 entries.
92709435
92719436 /Filters/ only change the visibility of items, are very fast and are
9272 mostly used interactively[fn:98]. You can switch quickly between
9437 mostly used interactively[fn:33]. You can switch quickly between
92739438 different filters without having to recreate the agenda. /Limits/ on
92749439 the other hand take effect before the agenda buffer is populated, so
92759440 they are mostly useful when defined as local variables within custom
94019566 #+begin_src emacs-lisp
94029567 (defun my-auto-exclude-fn (tag)
94039568 (when (cond ((string= tag "net")
9404 (/= 0 (call-process "/sbin/ping" nil nil nil
9405 "-c1" "-q" "-t1" "mail.gnu.org")))
9569 (/= 0 (call-process "/sbin/ping" nil nil nil
9570 "-c1" "-q" "-t1" "mail.gnu.org")))
94069571 ((member tag '("errand" "call"))
9407 (let ((hr (nth 2 (decode-time))))
9408 (or (< hr 8) (> hr 21)))))
9572 (let ((hr (nth 2 (decode-time))))
9573 (or (< hr 8) (> hr 21)))))
94099574 (concat "-" tag)))
94109575
94119576 (setq org-agenda-auto-exclude-function #'my-auto-exclude-fn)
97319896 agenda always shows a table with the clocked times for the time span
97329897 and file scope covered by the current agenda view. The initial
97339898 setting for this mode in new agenda buffers can be set with the
9734 variable ~org-agenda-start-with-clockreport-mode~. By using
9735 a prefix argument when toggling this mode (i.e., {{{kbd(C-u R)}}}),
9899 variable ~org-agenda-start-with-clockreport-mode~. By using a
9900 prefix argument when toggling this mode (i.e., {{{kbd(C-u R)}}}),
97369901 the clock table does not show contributions from entries that are
9737 hidden by agenda filtering[fn:99]. See also the variable
9738 ~org-clock-report-include-clocking-task~.
9902 hidden by agenda filtering[fn:: Only tags filtering is respected
9903 here, effort filtering is ignored.]. See also the variables
9904 ~org-clock-report-include-clocking-task~ and
9905 ~org-agenda-clock-report-header~.
97399906
97409907 - {{{kbd(v c)}}} ::
97419908
1008510252
1008610253 Unmark entry for bulk action.
1008710254
10088 - {{{kbd(U)}}} (~org-agenda-bulk-remove-all-marks~) ::
10255 - {{{kbd(U)}}} (~org-agenda-bulk-unmark-all~) ::
1008910256 #+kindex: U
10090 #+findex: org-agenda-bulk-remove-all-marks
10257 #+findex: org-agenda-bulk-unmark-all
1009110258
1009210259 Unmark all marked entries for bulk action.
1009310260
1017410341 - {{{kbd(f)}}} ::
1017510342
1017610343 #+vindex: org-agenda-bulk-custom-functions
10177 Apply a function[fn:100] to marked entries. For example, the
10178 function below sets the =CATEGORY= property of the entries to
10179 =web=.
10344 Apply a function[fn:: You can also create persistent custom
10345 functions through ~org-agenda-bulk-custom-functions~.] to marked
10346 entries. For example, the function below sets the =CATEGORY=
10347 property of the entries to =web=.
1018010348
1018110349 #+begin_src emacs-lisp
1018210350 (defun set-category ()
1021410382 #+cindex: diary entries, creating from agenda
1021510383 Insert a new entry into the diary, using the date at point and (for
1021610384 block entries) the date at the mark. This adds to the Emacs diary
10217 file[fn:101], in a way similar to the {{{kbd(i)}}} command in the
10218 calendar. The diary file pops up in another window, where you can
10219 add the entry.
10385 file[fn:: This file is parsed for the agenda when
10386 ~org-agenda-include-diary~ is set.], in a way similar to the
10387 {{{kbd(i)}}} command in the calendar. The diary file pops up in
10388 another window, where you can add the entry.
1022010389
1022110390 #+vindex: org-agenda-diary-file
1022210391 If you configure ~org-agenda-diary-file~ to point to an Org file,
1034010509 this is just a single character, but if you have many similar
1034110510 commands, you can also define two-letter combinations where the first
1034210511 character is the same in several combinations and serves as a prefix
10343 key[fn:102]. The second parameter is the search type, followed by the
10344 string or regular expression to be used for the matching. The example
10345 above will therefore define:
10512 key[fn:: You can provide a description for a prefix key by inserting a
10513 cons cell with the prefix and the description.]. The second parameter
10514 is the search type, followed by the string or regular expression to be
10515 used for the matching. The example above will therefore define:
1034610516
1034710517 - {{{kbd(x)}}} ::
1034810518
10349 as a global search for agenda entries planned[fn:103] this week/day.
10519 as a global search for agenda entries planned[fn:34] this week/day.
1035010520
1035110521 - {{{kbd(y)}}} ::
1035210522
1052610696 :END:
1052710697 #+cindex: agenda views, exporting
1052810698
10529 If you are away from your computer, it can be very useful to have
10530 a printed version of some agenda views to carry around. Org mode can
10531 export custom agenda views as plain text, HTML[fn:104], Postscript,
10532 PDF[fn:105], and iCalendar files. If you want to do this only
10533 occasionally, use the following command:
10699 If you are away from your computer, it can be very useful to have a
10700 printed version of some agenda views to carry around. Org mode can
10701 export custom agenda views as plain text, HTML[fn:: For HTML you need
10702 to install Hrvoje Nikšić's =htmlize.el= as an Emacs package from
10703 [[https://elpa.nongnu.org/][NonGNU ELPA]] or from
10704 [[https://github.com/hniksic/emacs-htmlize][Hrvoje Nikšić's repository]].],
10705 Postscript, PDF[fn:35], and iCalendar files. If you
10706 want to do this only occasionally, use the following command:
1053410707
1053510708 - {{{kbd(C-x C-w)}}} (~org-agenda-write~) ::
1053610709 #+kindex: C-x C-w
1054310716
1054410717 If you need to export certain agenda views frequently, you can
1054510718 associate any custom agenda command with a list of output file
10546 names[fn:106]. Here is an example that first defines custom commands
10547 for the agenda and the global TODO list, together with a number of
10548 files to which to export them. Then we define two block agenda
10549 commands and specify file names for them as well. File names can be
10550 relative to the current working directory, or absolute.
10719 names[fn:: If you want to store standard views like the weekly agenda
10720 or the global TODO list as well, you need to define custom commands
10721 for them in order to be able to specify file names.]. Here is an
10722 example that first defines custom commands for the agenda and the
10723 global TODO list, together with a number of files to which to export
10724 them. Then we define two block agenda commands and specify file names
10725 for them as well. File names can be relative to the current working
10726 directory, or absolute.
1055110727
1055210728 #+begin_src emacs-lisp
1055310729 (setq org-agenda-custom-commands
1063110807 #+end_src
1063210808
1063310809 #+texinfo: @noindent
10634 or, if you need to modify some parameters[fn:107]
10810 or, if you need to modify some parameters[fn:: Quoting depends on the
10811 system you use, please check the FAQ for examples.]
1063510812
1063610813 #+begin_src shell
1063710814 emacs -eval '(org-batch-store-agenda-views \
1090111078
1090211079 #+cindex: special symbols, in-buffer display
1090311080 If you would like to see entities displayed as UTF-8 characters, use
10904 the following command[fn:108]:
11081 the following command[fn:: You can turn this on by default by setting
11082 the variable ~org-pretty-entities~, or on a per-file base with the
11083 =STARTUP= option =entitiespretty=.]:
1090511084
1090611085 - {{{kbd(C-c C-x \)}}} (~org-toggle-pretty-entities~) ::
1090711086 #+kindex: C-c C-x \
1091411093 #+cindex: shy hyphen, special symbol
1091511094 #+cindex: dash, special symbol
1091611095 #+cindex: ellipsis, special symbol
10917 In addition to regular entities defined above, Org exports in
10918 a special way[fn:109] the following commonly used character
11096 In addition to regular entities defined above, Org exports in a
11097 special way[fn:: This behavior can be disabled with =-= export setting
11098 (see [[*Export Settings]]).] the following commonly used character
1091911099 combinations: =\-= is treated as a shy hyphen, =--= and =---= are
1092011100 converted into dashes, and =...= becomes a compact set of dots.
1092111101
1092811108
1092911109 Plain ASCII is normally sufficient for almost all note taking.
1093011110 Exceptions include scientific notes, which often require mathematical
10931 symbols and the occasional formula. LaTeX[fn:110] is widely used to
11111 symbols and the occasional formula. LaTeX[fn:36] is widely used to
1093211112 typeset scientific documents. Org mode supports embedding LaTeX code
1093311113 into its files, because many academics are used to writing and reading
1093411114 LaTeX source code, and because it can be readily processed to produce
1095011130 LaTeX fragments do not need any special marking at all. The following
1095111131 snippets are identified as LaTeX source code:
1095211132
10953 - Environments of any kind[fn:111]. The only requirement is that the
11133 - Environments of any kind[fn:37]. The only requirement is that the
1095411134 =\begin= statement appears on a new line, preceded by only
1095511135 whitespace.
1095611136
1099411174
1099511175 #+vindex: org-preview-latex-default-process
1099611176 If you have a working LaTeX installation and =dvipng=, =dvisvgm= or
10997 =convert= installed[fn:112], LaTeX fragments can be processed to
11177 =convert= installed[fn:38], LaTeX fragments can be processed to
1099811178 produce images of the typeset expressions to be used for inclusion
1099911179 while exporting to HTML (see [[*LaTeX fragments]]), or for inline
1100011180 previewing within Org mode.
1104111221 environments and math templates. Inside Org mode, you can make use of
1104211222 some of the features of CDLaTeX mode. You need to install
1104311223 =cdlatex.el= and =texmathp.el= (the latter comes also with AUCTeX)
11044 using [[https://melpa.org/][MELPA]] with the [[https://www.gnu.org/software/emacs/manual/html_node/emacs/Package-Installation.html][Emacs packaging system]] or alternatively from
11224 from [[https://elpa.nongnu.org/][NonGNU ELPA]] with the [[https://www.gnu.org/software/emacs/manual/html_node/emacs/Package-Installation.html][Emacs packaging system]] or alternatively from
1104511225 [[https://staff.fnwi.uva.nl/c.dominik/Tools/cdlatex/]]. Do not use
1104611226 CDLaTeX mode itself under Org mode, but use the special version Org
1104711227 CDLaTeX minor mode that comes as part of Org. Turn it on for the
1106411244 - {{{kbd(TAB)}}} ::
1106511245 #+kindex: TAB
1106611246
11067 The {{{kbd(TAB)}}} key expands the template if point is inside
11068 a LaTeX fragment[fn:113]. For example, {{{kbd(TAB)}}} expands =fr=
11069 to =\frac{}{}= and position point correctly inside the first brace.
11070 Another {{{kbd(TAB)}}} gets you into the second brace.
11247 The {{{kbd(TAB)}}} key expands the template if point is inside a
11248 LaTeX fragment[fn:: Org mode has a method to test if point is inside
11249 such a fragment, see the documentation of the function
11250 ~org-inside-LaTeX-fragment-p~.]. For example, {{{kbd(TAB)}}}
11251 expands =fr= to =\frac{}{}= and position point correctly inside the
11252 first brace. Another {{{kbd(TAB)}}} gets you into the second brace.
1107111253
1107211254 Even outside fragments, {{{kbd(TAB)}}} expands environment
1107311255 abbreviations at the beginning of a line. For example, if you write
1109811280 #+kindex: '
1109911281
1110011282 Pressing the single-quote followed by another character modifies the
11101 symbol before point with an accent or a font. If you wait more than
11102 1.5 seconds after the single-quote, a help window pops up.
11283 LaTeX symbol before point with an accent or a font. If you wait
11284 more than 1.5 seconds after the single-quote, a help window pops up.
1110311285 Character modification works only inside LaTeX fragments; outside
1110411286 the quote is normal.
1110511287
1114511327 #+end_example
1114611328
1114711329 #+cindex: formatting source code, markup rules
11148 #+vindex: org-latex-listings
11330 #+vindex: org-latex-src-block-backend
1114911331 If the example is source code from a programming language, or any
1115011332 other text that can be marked up by Font Lock in Emacs, you can ask
11151 for the example to look like the fontified Emacs buffer[fn:114]. This
11333 for the example to look like the fontified Emacs buffer[fn:39]. This
1115211334 is done with the code block, where you also need to specify the name
11153 of the major mode that should be used to fontify the example[fn:115],
11335 of the major mode that should be used to fontify the example[fn:40],
1115411336 see [[*Structure Templates]] for shortcuts to easily insert code blocks.
1115511337
1115611338 #+cindex: @samp{BEGIN_SRC}
1119111373 corresponding code line, which is kind of cool.
1119211374
1119311375 You can also add a =-r= switch which /removes/ the labels from the
11194 source code[fn:116]. With the =-n= switch, links to these references
11195 are labeled by the line numbers from the code listing. Otherwise
11196 links use the labels with no parentheses. Here is an example:
11376 source code[fn:: Adding =-k= to =-n -r= /keeps/ the labels in the
11377 source code while using line numbers for the links, which might be
11378 useful to explain those in an Org mode example code.]. With the =-n=
11379 switch, links to these references are labeled by the line numbers from
11380 the code listing. Otherwise links use the labels with no parentheses.
11381 Here is an example:
1119711382
1119811383 #+begin_example -l "(dumb-reference:%s)"
1119911384 ,#+BEGIN_SRC emacs-lisp -n -r
1123511420 works by switching to a temporary buffer with the source code. You
1123611421 need to exit by pressing {{{kbd(C-c ')}}} again. The edited version
1123711422 then replaces the old version in the Org buffer. Fixed-width
11238 regions---where each line starts with a colon followed by
11239 a space---are edited using Artist mode[fn:117] to allow creating
11240 ASCII drawings easily. Using this command in an empty line creates
11241 a new fixed-width region.
11423 regions---where each line starts with a colon followed by a
11424 space---are edited using Artist mode[fn:: You may select a different
11425 mode with the variable ~org-edit-fixed-width-region-mode~.] to allow
11426 creating ASCII drawings easily. Using this command in an empty line
11427 creates a new fixed-width region.
1124211428
1124311429 #+cindex: storing link, in a source code buffer
1124411430 Calling ~org-store-link~ (see [[*Handling Links]]) while editing a source
1125511441
1125611442 #+cindex: inlining images
1125711443 #+cindex: images, markup rules
11258 An image is a link to an image file[fn:118] that does not have
11259 a description part, for example
11444 An image is a link to an image file[fn:: What Emacs considers to be an
11445 image depends on ~image-file-name-extensions~ and
11446 ~image-file-name-regexps~.] that does not have a description part, for
11447 example
1126011448
1126111449 : ./img/cat.jpg
1126211450
1127911467 #+kindex: C-c C-x C-v
1128011468 #+findex: org-toggle-inline-images
1128111469 #+vindex: org-startup-with-inline-images
11282 Toggle the inline display of linked images. When called with
11283 a prefix argument, also display images that do have a link
11470 Toggle the inline display of linked images. When called with a
11471 prefix argument, also display images that do have a link
1128411472 description. You can ask for inline images to be displayed at
1128511473 startup by configuring the variable
11286 ~org-startup-with-inline-images~[fn:119].
11474 ~org-startup-with-inline-images~[fn:: The variable
11475 ~org-startup-with-inline-images~ can be set within a buffer with the
11476 =STARTUP= options =inlineimages= and =noinlineimages=.].
11477
11478
11479 #+vindex: org-image-actual-width
11480 #+cindex: @samp{ORG-IMAGE-ACTUAL-WIDTH}, property
11481 By default, Org mode displays inline images according to their
11482 actual width. You can customize the displayed image width using
11483 ~org-image-actual-width~ variable (globally) or
11484 =ORG-IMAGE-ACTUAL-WIDTH= property (subtree-level)[fn:: The width can
11485 be customized in Emacs >= 24.1, built with imagemagick support.].
11486 Their value can be the following:
11487 - (default) Non-nil, use the actual width of images when inlining them.
11488 - When set to a number, use imagemagick (when available) to set the
11489 image's width to this value.
11490 - When set to a number in a list, try to get the width from any
11491 =#+ATTR.*= keyword if it matches a width specification like:
11492 #+begin_example
11493 ,#+ATTR_HTML: :width 300px
11494 #+end_example
11495 and fall back on that number if none is found.
11496 - When set to nil, try to get the width from an =#+ATTR.*= keyword
11497 and fall back on the original width if none is found.
11498
11499
11500 #+vindex: org-cycle-inline-images-display
11501 Inline images can also be displayed when cycling the folding state.
11502 When custom option ~org-cycle-inline-images-display~ is set, the
11503 visible inline images under subtree will be displayed automatically.
1128711504
1128811505 ** Captions
1128911506 :PROPERTIES:
1133211549 text. Markers always start with =fn:=. For example:
1133311550
1133411551 #+begin_example
11335 The Org homepage[fn:1] now looks a lot better than it used to.
11552 The Org website[fn:1] now looks a lot better than it used to.
1133611553 ...
11337 [fn:1] The link is: https://orgmode.org
11554 [fn:55] The link is: https://orgmode.org
1133811555 #+end_example
1133911556
1134011557 Org mode extends the number-based syntax to /named/ footnotes and
1137511592 #+vindex: org-footnote-define-inline
1137611593 #+vindex: org-footnote-section
1137711594 Otherwise, create a new footnote. Depending on the variable
11378 ~org-footnote-define-inline~[fn:120], the definition is placed right
11379 into the text as part of the reference, or separately into the
11380 location determined by the variable ~org-footnote-section~.
11595 ~org-footnote-define-inline~[fn:: The corresponding in-buffer
11596 setting is: =#+STARTUP: fninline= or =#+STARTUP: nofninline=.], the
11597 definition is placed right into the text as part of the reference,
11598 or separately into the location determined by the variable
11599 ~org-footnote-section~.
1138111600
1138211601 When this command is called with a prefix argument, a menu of
1138311602 additional options is offered:
1139011609 | {{{kbd(d)}}} | Delete the footnote at point, including definition and references. |
1139111610
1139211611 #+vindex: org-footnote-auto-adjust
11393 Depending on the variable ~org-footnote-auto-adjust~[fn:121],
11394 renumbering and sorting footnotes can be automatic after each
11395 insertion or deletion.
11612 Depending on the variable ~org-footnote-auto-adjust~[fn:: The
11613 corresponding in-buffer options are =#+STARTUP: fnadjust= and
11614 =#+STARTUP: nofnadjust=.], renumbering and sorting footnotes can be
11615 automatic after each insertion or deletion.
1139611616
1139711617 - {{{kbd(C-c C-c)}}} ::
1139811618
1147211692 a non-~nil~ value, Org prompts in the minibuffer. To switch back to
1147311693 the hierarchical menu, press {{{kbd(?)}}}.
1147411694
11475 - {{{kbd(C-c C-e)}}} (~org-export~) ::
11695 - {{{kbd(C-c C-e)}}} (~org-export-dispatch~) ::
1147611696 #+kindex: C-c C-e
11477 #+findex: org-export
11697 #+findex: org-export-dispatch
1147811698
1147911699 Invokes the export dispatcher interface. The options show default
1148011700 settings. The {{{kbd(C-u)}}} prefix argument preserves options from
11481 the previous export, including any sub-tree selections.
11701 the previous export, including any subtree selections.
1148211702
1148311703 Org exports the entire buffer by default. If the Org buffer has an
1148411704 active region, then Org exports just that region.
1151711737 - {{{kbd(C-s)}}} ::
1151811738 #+kindex: C-c C-e C-s
1151911739
11520 Toggle sub-tree export. When turned on, Org exports only the
11521 sub-tree starting from point position at the time the export
11522 dispatcher was invoked. Org uses the top heading of this sub-tree
11740 Toggle subtree export. When turned on, Org exports only the
11741 subtree starting from point position at the time the export
11742 dispatcher was invoked. Org uses the top heading of this subtree
1152311743 as the document's title. If point is not on a heading, Org uses the
1152411744 nearest enclosing header. If point is in the document preamble, Org
1152511745 signals an error and aborts export.
1152611746
1152711747 #+vindex: org-export-initial-scope
11528 To make sub-tree export the default, customize the variable
11748 To make subtree export the default, customize the variable
1152911749 ~org-export-initial-scope~.
1153011750
1153111751 - {{{kbd(C-v)}}} ::
1155811778 Dispatcher]]) using the =Insert template= command by pressing
1155911779 {{{kbd(#)}}}. To insert keywords individually, a good way to make
1156011780 sure the keyword is correct is to type =#+= and then to use
11561 {{{kbd(M-TAB)}}}[fn:16] for completion.
11781 {{{kbd(M-TAB)}}}[fn:6] for completion.
1156211782
1156311783 The export keywords available for every back-end, and their equivalent
1156411784 global variables, include:
1158011800
1158111801 #+cindex: @samp{DATE}, keyword
1158211802 #+vindex: org-export-date-timestamp-format
11583 A date or a time-stamp[fn:122].
11803 A date or a time-stamp[fn:: The variable
11804 ~org-export-date-timestamp-format~ defines how this timestamp are
11805 exported.].
1158411806
1158511807 - =EMAIL= ::
1158611808
1159511817 Language to use for translating certain strings
1159611818 (~org-export-default-language~). With =#+LANGUAGE: fr=, for
1159711819 example, Org translates =Table of contents= to the French =Table des
11598 matières=[fn:123].
11820 matières=[fn:41].
1159911821
1160011822 - =SELECT_TAGS= ::
1160111823
1160311825 #+vindex: org-export-select-tags
1160411826 The default value is =("export")=. When a tree is tagged with
1160511827 =export= (~org-export-select-tags~), Org selects that tree and its
11606 sub-trees for export. Org excludes trees with =noexport= tags, see
11828 subtrees for export. Org excludes trees with =noexport= tags, see
1160711829 below. When selectively exporting files with =export= tags set, Org
1160811830 does not export any text that appears before the first headline.
1160911831
1161311835 #+vindex: org-export-exclude-tags
1161411836 The default value is =("noexport")=. When a tree is tagged with
1161511837 =noexport= (~org-export-exclude-tags~), Org excludes that tree and
11616 its sub-trees from export. Entries tagged with =noexport= are
11838 its subtrees from export. Entries tagged with =noexport= are
1161711839 unconditionally excluded from the export, even if they have an
11618 =export= tag. Even if a sub-tree is not exported, Org executes any
11840 =export= tag. Even if a subtree is not exported, Org executes any
1161911841 code blocks contained there.
1162011842
1162111843 - =TITLE= ::
1183412056 #+vindex: org-export-with-tables
1183512057 Toggle inclusion of tables (~org-export-with-tables~).
1183612058
11837 When exporting sub-trees, special node properties can override the
12059 When exporting subtrees, special node properties can override the
1183812060 above keywords. These properties have an =EXPORT_= prefix. For
1183912061 example, =DATE= becomes, =EXPORT_DATE= when used for a specific
11840 sub-tree. Except for =SETUPFILE=, all other keywords listed above
12062 subtree. Except for =SETUPFILE=, all other keywords listed above
1184112063 have an =EXPORT_= equivalent.
1184212064
1184312065 #+cindex: @samp{BIND}, keyword
1187212094 #+cindex: excluding entries from table of contents
1187312095 #+cindex: table of contents, exclude entries
1187412096 Org includes both numbered and unnumbered headlines in the table of
11875 contents[fn:124]. If you need to exclude an unnumbered headline,
12097 contents[fn:42]. If you need to exclude an unnumbered headline,
1187612098 along with all its children, set the =UNNUMBERED= property to =notoc=
1187712099 value.
1187812100
1199112213 | =#+INCLUDE: "~/.emacs" :lines "10-"= | Include lines from 10 to EOF |
1199212214
1199312215 Inclusions may specify a file-link to extract an object matched by
11994 ~org-link-search~[fn:125] (see [[*Search Options in File Links]]). The
12216 ~org-link-search~[fn:43] (see [[*Search Options in File Links]]). The
1199512217 ranges for =:lines= keyword are relative to the requested element.
1199612218 Therefore,
1199712219
1201012232
1201112233 The following command allows navigating to the included document:
1201212234
12013 - {{{kbd(C-c ')}}} (~org-edit~special~) ::
12235 - {{{kbd(C-c ')}}} (~org-edit-special~) ::
1201412236 #+kindex: C-c '
1201512237 #+findex: org-edit-special
1201612238
1203112253 : #+MACRO: name replacement text; $1, $2 are arguments
1203212254
1203312255 #+texinfo: @noindent
12034 which can be referenced using ={{{name(arg1, arg2)}}}=[fn:126]. For
12256 which can be referenced using ={{{name(arg1, arg2)}}}=[fn:44]. For
1203512257 example
1203612258
1203712259 #+begin_example
1215012372 Finally, a =COMMENT= keyword at the beginning of an entry, but after
1215112373 any other keyword or priority cookie, comments out the entire subtree.
1215212374 In this case, the subtree is not exported and no code block within it
12153 is executed either[fn:127]. The command below helps changing the
12154 comment status of a headline.
12375 is executed either[fn:: For a less drastic behavior, consider using a
12376 select tag (see [[*Export Settings]]) instead.]. The command below
12377 helps changing the comment status of a headline.
1215512378
1215612379 - {{{kbd(C-c ;)}}} (~org-toggle-comment~) ::
1215712380 #+kindex: C-c ;
1242212645
1242312646 - Org exports a Beamer frame's objects as block environments. Org can
1242412647 enforce wrapping in special block types when =BEAMER_ENV= property
12425 is set[fn:128]. For valid values see
12648 is set[fn:45]. For valid values see
1242612649 ~org-beamer-environments-default~. To add more values, see
1242712650 ~org-beamer-environments-extra~.
1242812651 #+vindex: org-beamer-environments-default
1244112664 When =ignoreheading= is set, Org export ignores the entry's headline
1244212665 but not its content. This is useful for inserting content between
1244312666 frames. It is also useful for properly closing a =column=
12444 environment. @end itemize
12667 environment.
1244512668
1244612669 #+cindex: @samp{BEAMER_ACT}, property
1244712670 #+cindex: @samp{BEAMER_OPT}, property
1249112714
1249212715 ,#+BEGIN_EXPORT beamer
1249312716 Only Beamer export back-end exports this.
12494 ,#+END_BEAMER
12717 ,#+END_EXPORT
1249512718
1249612719 Text @@beamer:some code@@ within a paragraph.
1249712720 #+end_example
1281013033 ~org-html-preamble-format~ for the format string.
1281113034
1281213035 Set ~org-html-preamble~ to a string to override the default format
12813 string. If the string is a function, the HTML exporter expects the
12814 function to return a string upon execution. The HTML exporter inserts
12815 this string in the preamble. The HTML exporter does not insert
12816 a preamble if ~org-html-preamble~ is set ~nil~.
12817
12818 The default value for ~org-html-postamble~ is ~auto~, which makes the
12819 HTML exporter build a postamble from looking up author's name, email
12820 address, creator's name, and date. Set ~org-html-postamble~ to ~t~ to
12821 insert the postamble in the format specified in the
12822 ~org-html-postamble-format~ variable. The HTML exporter does not
12823 insert a postamble if ~org-html-postamble~ is set to ~nil~.
13036 string. If set to a function, the HTML exporter expects the function
13037 to return a string upon execution. The HTML exporter inserts this
13038 string in the preamble. The HTML exporter does not insert a preamble
13039 if ~org-html-preamble~ is set ~nil~.
13040
13041 The above also applies to ~org-html-postamble~ and
13042 ~org-html-postamble-format~. In addition, ~org-html-postamble~ can be
13043 set to ~auto~ (its default value), which makes the HTML exporter build
13044 a postamble from looking up author's name, email address, creator's
13045 name, and date.
13046
1282413047
1282513048 *** Quoting HTML tags
1282613049 :PROPERTIES:
1289313116
1289413117 #+cindex: @samp{ATTR_HTML}, keyword
1289513118 #+begin_example
12896 ,#+ATTR_HTML: :title The Org mode homepage :style color:red;
13119 ,#+ATTR_HTML: :title The Org mode website :style color:red;
1289713120 [[https://orgmode.org]]
1289813121 #+end_example
1289913122
1300913232
1301013233 #+vindex: org-html-mathjax-options~
1301113234 LaTeX math snippets (see [[*LaTeX fragments]]) can be displayed in two
13012 different ways on HTML pages. The default is to use the [[https://www.mathjax.org][MathJax]],
13013 which should work out of the box with Org[fn:129][fn:130]. Some MathJax
13014 display options can be configured via ~org-html-mathjax-options~, or
13015 in the buffer. For example, with the following settings,
13235 different ways on HTML pages. The default is to use the
13236 [[https://www.mathjax.org][MathJax]], which should work out of the box
13237 with Org[fn:: By default, Org loads MathJax from
13238 [[https://www.jsdelivr.com/][jsDelivr]], as recommended in
13239 [[https://docs.mathjax.org/en/latest/web/start.html][Getting Started
13240 with MathJax Components]].][fn:46]. Some MathJax display options can
13241 be configured via ~org-html-mathjax-options~, or in the buffer. For
13242 example, with the following settings,
1301613243
1301713244 #+begin_example
13018 ,#+HTML_MATHJAX: align: left indent: 5em tagside: left font: Neo-Euler
13019 ,#+HTML_MATHJAX: cancel.js noErrors.js
13245 ,#+HTML_MATHJAX: align: left indent: 5em tagside: left
1302013246 #+end_example
1302113247
1302213248 #+texinfo: @noindent
1302313249 equation labels are displayed on the left margin and equations are
13024 five em from the left margin. In addition, it loads the two MathJax
13025 extensions =cancel.js= and =noErrors.js=[fn:131].
13250 five em from the left margin.
1302613251
1302713252 #+vindex: org-html-mathjax-template
1302813253 See the docstring of ~org-html-mathjax-options~ for all supported
1308513310 #+vindex: org-export-html-todo-kwd-class-prefix
1308613311 #+vindex: org-export-html-tag-class-prefix
1308713312 You can modify the CSS style definitions for the exported file. The
13088 HTML exporter assigns the following special CSS classes[fn:132] to
13089 appropriate parts of the document---your style specifications may
13090 change these, in addition to any of the standard classes like for
13091 headlines, tables, etc.
13313 HTML exporter assigns the following special CSS classes[fn:: If the
13314 classes on TODO keywords and tags lead to conflicts, use the variables
13315 ~org-html-todo-kwd-class-prefix~ and ~org-html-tag-class-prefix~ to
13316 make them unique.] to appropriate parts of the document---your style
13317 specifications may change these, in addition to any of the standard
13318 classes like for headlines, tables, etc.
1309213319
1309313320 | ~p.author~ | author information, including email |
1309413321 | ~p.date~ | publishing date |
1315313380
1315413381 #+cindex: @samp{HTML_CONTAINER_CLASS}, property
1315513382 #+cindex: @samp{HTML_HEADLINE_CLASS}, property
13156 In order to add styles to a sub-tree, use the =HTML_CONTAINER_CLASS=
13383 In order to add styles to a subtree, use the =HTML_CONTAINER_CLASS=
1315713384 property to assign a class to the tree. In order to specify CSS
1315813385 styles for a particular headline, you can use the ID specified in
1315913386 a =CUSTOM_ID= property. You can also assign a specific class to
1332213549 Org file. See the docstring for the
1332313550 ~org-latex-default-packages-alist~ for loading packages with certain
1332413551 compilers. Also see ~org-latex-bibtex-compiler~ to set the
13325 bibliography compiler[fn:133].
13552 bibliography compiler[fn:47].
1332613553
1332713554 *** LaTeX specific export settings
1332813555 :PROPERTIES:
1334813575 - =LANGUAGE= ::
1334913576 #+cindex: @samp{LANGUAGE}, keyword
1335013577 #+vindex: org-latex-packages-alist
13578 #+vindex: org-latex-language-alist
13579
13580 Language code of the primary document language.
13581
13582 The list of language codes supported by Org is stored in the
13583 variable ~org-latex-language-alist~.
13584
1335113585 In order to be effective, the =babel= or =polyglossia=
1335213586 packages---according to the LaTeX compiler used---must be loaded
1335313587 with the appropriate language as argument. This can be accomplished
1335413588 by modifying the ~org-latex-packages-alist~ variable, e.g., with the
13355 following snippet:
13589 following snippet (note that =polyglossia= does not work with
13590 pdfLaTeX):
1335613591
1335713592 #+begin_src emacs-lisp
1335813593 (add-to-list 'org-latex-packages-alist
13359 '("AUTO" "babel" t ("pdflatex")))
13594 '("AUTO" "babel" t ("pdflatex" "xelatex" "lualatex")))
1336013595 (add-to-list 'org-latex-packages-alist
1336113596 '("AUTO" "polyglossia" t ("xelatex" "lualatex")))
1336213597 #+end_src
1344613681 To change the default class globally, edit ~org-latex-default-class~.
1344713682 To change the default class locally in an Org file, add option lines
1344813683 =#+LATEX_CLASS: myclass=. To change the default class for just a part
13449 of the Org file, set a sub-tree property, =EXPORT_LATEX_CLASS=. The
13684 of the Org file, set a subtree property, =EXPORT_LATEX_CLASS=. The
1345013685 class name entered here must be valid member of ~org-latex-classes~.
1345113686 This variable defines a header template for each class into which the
1345213687 exporter splices the values of ~org-latex-default-packages-alist~ and
1348613721 some more text
1348713722 #+end_example
1348813723
13724 #+cindex: @samp{LANGUAGE}, keyword
13725 #+vindex: org-export-default-language
13726 LaTeX packages =babel= or =polyglossia= can also be loaded in a
13727 document. The "AUTO" string will be replaced in both cases by the
13728 appropriate value for the =LANGUAGE= keyword, if present in the
13729 document, or by the value of ~org-export-default-language~. Let's see
13730 some examples in one or another case.
13731
13732 =Babel= accepts the classic syntax and (in addition) the new syntax
13733 with the =\babelprovide= command to load the languages using the new
13734 =INI= files procedure. Keep in mind that there are a number of
13735 languages that are only served in babel using =INI= files, so they
13736 cannot be declared using the classic syntax, but only using the
13737 =\babelprovide= command (see
13738 https://mirrors.ctan.org/macros/latex/required/babel/base/babel.pdf).
13739 Valid usage examples could be:
13740
13741 #+begin_example
13742 ,#+LATEX_HEADER: \usepackage[french,italian,AUTO]{babel}
13743 #+end_example
13744
13745 where "AUTO" is the main language. But it can also be loaded using
13746 the =\babelprovide= command:
13747
13748 #+begin_example
13749 ,#+LATEX_HEADER: \usepackage[french,italian]{babel}
13750 ,#+LATEX_HEADER: \babelprovide[import, main]{AUTO}
13751 #+end_example
13752
13753 =Polyglossia=, for this procedure to be effective, must be loaded
13754 using the same =babel= classic syntax (but note that /this is not/
13755 the actual polyglossia syntax). For example, suppose a document
13756 declares Polytonic Greek as the primary language, and French as the
13757 secondary language. In this case, it would be expressed as:
13758
13759 #+begin_example
13760 ,#+LANGUAGE: el-polyton
13761 ,#+LATEX_HEADER: \usepackage[french,AUTO]{polyglossia}
13762 #+end_example
13763
13764 This would produce in LaTeX (with the actual =polyglossia= syntax):
13765
13766 #+begin_example
13767 \usepackage{polyglossia}
13768 \setmainlanguage[variant=polytonic]{greek}
13769 \setotherlanguage{french}
13770 #+end_example
13771
1348913772 *** Quoting LaTeX code
1349013773 :PROPERTIES:
1349113774 :DESCRIPTION: Incorporating literal @LaTeX{} code.
1353213815 #+vindex: org-latex-default-table-mode
1353313816 The LaTeX export back-end wraps the table differently depending on
1353413817 the mode for accurate rendering of math symbols. Mode is either
13535 =table=, =math=, =inline-math= or =verbatim=.
13818 =table=, =math=, =inline-math=, =verbatim= or =tabbing=.
1353613819
1353713820 For =math= or =inline-math= mode, LaTeX export back-end wraps the
1353813821 table in a math environment, but every cell in it is exported as-is.
13822 For =tabbing= the LaTeX tabbing environment is used and the correct
13823 tabbing delimiters =\>= are used.
1353913824 The LaTeX export back-end determines the default mode from
1354013825 ~org-latex-default-table-mode~. The LaTeX export back-end merges
1354113826 contiguous tables in the same mode into a single environment.
1356413849
1356513850 The table environments by default are not floats in LaTeX. To make
1356613851 them floating objects use =:float= with one of the following
13567 options: =sideways=, =multicolumn=, =t=, and =nil=.
13852 options: =t= (for a default =table= environment), =sideways= (for a
13853 =sidewaystable= environment), =multicolumn= (to span the table
13854 across multiple columns of a page in a =table*= environment) and
13855 =nil=. In addition to these three values, =:float= can pass through
13856 any arbitrary value, for example a user-defined float type with the
13857 =float= LaTeX package.
1356813858
1356913859 LaTeX floats can also have additional layout =:placement=
1357013860 attributes. These are the usual =[h t b p ! H]= permissions
1357513865
1357613866 The LaTeX export back-end uses these attributes for regular tables
1357713867 to set their alignments, fonts, and widths.
13868
13869 - =:options= ::
13870
13871 The =:options= attribute allows adding an optional argument with
13872 a list of various table options (between brackets in LaTeX export),
13873 since certain tabular environments, such as longtblr of the
13874 tabularray LaTeX package, provides this structure. For example:
13875 =:options remark{Note}={note},remark{Source}={source}=.
1357813876
1357913877 - =:spread= ::
1358013878
1364113939 =[[./img.jpg]]=, as direct image insertions in the final PDF output. In
1364213940 the PDF, they are no longer links but actual images embedded on the
1364313941 page. The LaTeX export back-end uses =\includegraphics= macro to
13644 insert the image. But for TikZ (http://sourceforge.net/projects/pgf/)
13942 insert the image. But for TikZ (https://sourceforge.net/projects/pgf/)
1364513943 images, the back-end uses an ~\input~ macro wrapped within
1364613944 a ~tikzpicture~ environment.
1364713945
1367013968
1367113969 - =t= ::
1367213970
13673 For a standard =figure= environment; used by default whenever an
13674 image has a caption.
13971 For a default =figure= environment.
1367513972
1367613973 - =multicolumn= ::
1367713974
1369113988 - =nil= ::
1369213989
1369313990 To avoid a =:float= even if using a caption.
13991
13992 - Any arbitrary value ::
13993
13994 For example, a user-defined float type with the =float= LaTeX
13995 package.
13996
1369413997
1369513998 Use the =placement= attribute to modify a floating environment's
1369613999 placement.
1377914082
1378014083 #+vindex: org-latex-listings-options
1378114084 #+vindex: org-latex-minted-options
14085 #+vindex: org-latex-engraved-options
1378214086 The LaTeX export back-end passes string values in =:options= to LaTeX
1378314087 packages for customization of that specific source block. In the
13784 example below, the =:options= are set for Minted. Minted is a source
13785 code highlighting LaTeX package with many configurable options[fn:134].
14088 example below, the =:options= are set for Engraved or Minted. Minted
14089 is a source code highlighting LaTeX package with many configurable
14090 options[fn:: Minted uses an external Python package for code
14091 highlighting, which requires the flag =-shell-escape= to be added to
14092 ~org-latex-pdf-process~.]. Both Minted and Engraved are built on
14093 [[https://www.ctan.org/pkg/fvextra][fvextra]], and so support many of
14094 the same options.
1378614095
1378714096 #+begin_example
13788 ,#+ATTR_LATEX: :options commentstyle=\bfseries
14097 ,#+ATTR_LATEX: :options mathescape
1378914098 ,#+BEGIN_SRC emacs-lisp
13790 (defun Fib (n)
14099 (defun Fib (n) ; $n_i = n_{i-2} + n_{i-1}$
1379114100 (if (< n 2) n (+ (Fib (- n 1)) (Fib (- n 2)))))
1379214101 ,#+END_SRC
1379314102 #+end_example
1379414103
13795 To apply similar configuration options for all source blocks in
13796 a file, use the ~org-latex-listings-options~ and
13797 ~org-latex-minted-options~ variables.
14104 To apply similar configuration options for all source blocks in a
14105 file, use the ~org-latex-listings-options~,
14106 ~org-latex-engraved-options~, and ~org-latex-minted-options~
14107 variables.
1379814108
1379914109 *** Example blocks in LaTeX export
1380014110 :PROPERTIES:
1398114291 #+cindex: Markdown export
1398214292
1398314293 The Markdown export back-end, "md", converts an Org file to Markdown
13984 format, as defined at http://daringfireball.net/projects/markdown/.
14294 format, as defined at https://daringfireball.net/projects/markdown/.
1398514295
1398614296 Since it is built on top of the HTML back-end (see [[*HTML Export]]), it
1398714297 converts every Org construct not defined in Markdown syntax, such as
1403314343
1403414344 The ODT export back-end handles creating of OpenDocument Text (ODT)
1403514345 format. Documents created by this exporter use the
14036 {{{cite(OpenDocument-v1.2 specification)}}}[fn:135] and are compatible
14037 with LibreOffice 3.4.
14346 {{{cite(OpenDocument-v1.2 specification)}}}[fn:: See
14347 [[https://docs.oasis-open.org/office/v1.2/OpenDocument-v1.2.html][Open
14348 Document Format for Office Applications (OpenDocument) Version 1.2]].]
14349 and are compatible with LibreOffice 3.4.
1403814350
1403914351 *** Pre-requisites for ODT export
1404014352 :PROPERTIES:
1405114363 :DESCRIPTION: Invoking export.
1405214364 :END:
1405314365
14054 - {{{kbd(C-c C-e o o)}}} (~org-export-to-odt~) ::
14366 - {{{kbd(C-c C-e o o)}}} (~org-odt-export-to-odt~) ::
1405514367
1405614368 #+kindex: C-c C-e o o
14057 #+findex: org-export-to-odt
14369 #+findex: org-odt-export-to-odt
1405814370 Export as OpenDocument Text file.
1405914371
1406014372 #+cindex: @samp{EXPORT_FILE_NAME}, property
1406914381
1407014382 If the selected region is a single tree, the ODT export back-end
1407114383 makes the tree head the document title. Incidentally, {{{kbd(C-c
14072 @)}}} selects the current sub-tree. If the tree head entry has, or
14384 @)}}} selects the current subtree. If the tree head entry has, or
1407314385 inherits, an =EXPORT_FILE_NAME= property, the ODT export back-end
1407414386 uses that for file name.
1407514387
1421914531
1422014532 The ODT export back-end relies on many templates and style names.
1422114533 Using third-party styles and templates can lead to mismatches.
14222 Templates derived from built in ODT templates and styles seem to have
14534 Templates derived from built-in ODT templates and styles seem to have
1422314535 fewer problems.
1422414536
1422514537 *** Links in ODT export
1443414746 variables ~org-latex-to-mathml-convert-command~ and
1443514747 ~org-latex-to-mathml-jar-file~.
1443614748
14437 If you prefer to use MathToWeb[fn:136] as your converter, you can
14438 configure the above variables as shown below.
14749 If you prefer to use MathToWeb[fn:: See
14750 [[http://www.mathtoweb.com/cgi-bin/mathtoweb_home.pl][MathToWeb]].]
14751 as your converter, you can configure the above variables as shown
14752 below.
1443914753
1444014754 #+begin_src emacs-lisp
1444114755 (setq org-latex-to-mathml-convert-command
1444514759 #+end_src
1444614760
1444714761 #+texinfo: @noindent
14448 or, to use LaTeX​ML[fn:137] instead,
14762 or, to use LaTeX​ML[fn:: See [[https://dlmf.nist.gov/LaTeXML/]].]
14763 instead,
1444914764
1445014765 #+begin_src emacs-lisp
1445114766 (setq org-latex-to-mathml-convert-command
1476415079 tables, see [[*Tables in ODT export]].
1476515080
1476615081 This feature closely mimics the way table templates are defined in the
14767 OpenDocument-v1.2 specification[fn:138].
15082 OpenDocument-v1.2 specification[fn::
15083 [[https://docs.oasis-open.org/office/v1.2/OpenDocument-v1.2.html][OpenDocument-v1.2
15084 Specification]]].
1476815085
1476915086 #+vindex: org-odt-table-styles
1477015087 For quick preview of this feature, install the settings below and export the
1479815115
1479915116 To use this feature proceed as follows:
1480015117
14801 1. Create a table template[fn:139].
15118 1. Create a table template[fn:: See the =<table:table-template>=
15119 element of the OpenDocument-v1.2 specification.].
1480215120
1480315121 A table template is set of =table-cell= and =paragraph= styles for
1480415122 each of the following table cell categories:
1483715155 =</office:automatic-styles>= element of the content template file
1483815156 (see [[x-orgodtcontenttemplate-xml][Factory styles]]).
1483915157
14840 2. Define a table style[fn:140].
15158 2. Define a table style[fn:: See the attributes =table:template-name=,
15159 =table:use-first-row-styles=, =table:use-last-row-styles=,
15160 =table:use-first-column-styles=, =table:use-last-column-styles=,
15161 =table:use-banding-rows-styles=, and
15162 =table:use-banding-column-styles= of the =<table:table>= element in
15163 the OpenDocument-v1.2 specification.].
1484115164
1484215165 #+vindex: org-odt-table-styles
1484315166 To define a table style, create an entry for the style in the
1522015543 :DESCRIPTION: List attributes.
1522115544 :END:
1522215545
15546 #+cindex: lettered lists, in Texinfo export
15547 #+cindex: enum, Texinfo attribute
15548 The Texinfo export back-end converts unordered and ordered lists in
15549 the Org file using the default command =@itemize=.
15550
15551 Ordered lists are numbered when exported to Texinfo format. Such
15552 numbering obeys any counter (see [[*Plain Lists]]) in the first item of
15553 the list. The =:enum= attribute also let you start the list at a
15554 specific number, or switch to a lettered list, as illustrated here:
15555
15556 #+begin_example
15557 #+ATTR_TEXINFO: :enum A
15558 1. Alpha
15559 2. Bravo
15560 3. Charlie
15561 #+end_example
15562
1522315563 #+cindex: @samp{ATTR_TEXINFO}, keyword
1522415564 #+cindex: two-column tables, in Texinfo export
1522515565 #+cindex: table-type, Texinfo attribute
1526115601 @end table
1526215602 #+end_example
1526315603
15264 #+cindex: lettered lists, in Texinfo export
15265 #+cindex: enum, Texinfo attribute
15266 Ordered lists are numbered when exported to Texinfo format. Such
15267 numbering obeys any counter (see [[*Plain Lists]]) in the first item of
15268 the list. The =:enum= attribute also let you start the list at
15269 a specific number, or switch to a lettered list, as illustrated here
15604 The =:compact= attribute is an alternative to the =:sep= attribute,
15605 which allows writing each entry on its own line. If this attribute is
15606 non-nil and an item in a description list has no body but is followed
15607 by another item, then the second item is transcoded to =@itemx=. This
15608 example is transcoded to the same output as above.
1527015609
1527115610 #+begin_example
15272 #+ATTR_TEXINFO: :enum A
15273 1. Alpha
15274 2. Bravo
15275 3. Charlie
15611 ,#+ATTR_TEXINFO: :table-type vtable :indic asis :compact t
15612 - foo ::
15613 - bar ::
15614 This is the common text for variables foo and bar.
1527615615 #+end_example
15616
15617 Support for this compact syntax can also be enabled for all lists in
15618 a file using the =compact-itemx= export option, or globally using the
15619 variable ~org-texinfo-compact-itemx~.
15620
15621 The Texinfo export back-end also supports two approaches to writing
15622 Texinfo definition commands (see [[info:texinfo::Definition Commands]]).
15623 One of them uses description lists and is described below, the other
15624 relies on special blocks (see [[*Special blocks in Texinfo export]]).
15625
15626 Items in a description list in a Org file that begin with =Function:=
15627 or certain other prefixes are converted using Texinfo definition
15628 commands. This works even if other items in the same list do not have
15629 such a prefix; if necessary a single description list is converted
15630 using multiple tables (such as =@vtable=) and definition commands
15631 (such as =@defun=).
15632
15633 #+begin_example
15634 - Function: org-texinfo-drawer drawer contents info ::
15635 Transcode a DRAWER element from Org to Texinfo.
15636 #+end_example
15637
15638 #+texinfo: @noindent
15639 becomes
15640
15641 #+begin_example
15642 @defun org-texinfo-drawer drawer contents info ::
15643 Transcode a DRAWER element from Org to Texinfo.
15644 @end defun
15645 #+end_example
15646
15647 The recognized prefixes are =Command:=, =Function:=, =Macro:=,
15648 =Special Form:=, =Variable:= and =User Option:=. These are the same
15649 prefixes that appear in the Info file for the respective definition
15650 commands. For example a =Function:= item in the Org file is converted
15651 to a =@defun= command in the Texinfo file, which in turn is converted
15652 to a definition prefixed with =-- Function:= in the Info file.
15653
15654 As a special case the prefix =Key:= is also recognized. No Texinfo
15655 definition command exists for key bindings and the output in Info
15656 files also lacks the =Key:= prefix. Even so this special case is
15657 supported because it provides a convenient shorthand, as illustrated
15658 here:
15659
15660 #+begin_example
15661 - Key: C-c C-c (do-something) ::
15662 This command does something.
15663
15664 - User Option: do-something-somehow ::
15665 This option controls how exactly ~do-something~ does its thing.
15666 #+end_example
15667
15668 #+texinfo: @noindent
15669 becomes
15670
15671 #+begin_example
15672 @table @asis
15673 @item @kbd{C-c C-c} (@code{do-something})
15674 @kindex C-c C-c
15675 @findex do-something
15676 This command does something.
15677 @end table
15678
15679 @defopt do-something-somehow
15680 This option controls how exactly @code{do-something} does its thing.
15681 @end defopt
15682 #+end_example
15683
15684 #+texinfo: @noindent
15685 Command in parenthesis, as done above, is optional.
1527715686
1527815687 *** Tables in Texinfo export
1527915688 :PROPERTIES:
1533715746 ,#+END_QUOTE
1533815747 #+end_example
1533915748
15749 *** Key bindings in Texinfo export
15750 :PROPERTIES:
15751 :DESCRIPTION: @@kbd Texinfo command.
15752 :END:
15753
15754 Org does not provide any markup for key bindings that corresponds to
15755 Texinfo's ~@kbd~ and ~@key~ commands. One way to deal with this is to
15756 fall back to code syntax. =~C-x SPC~=, for example, is transcoded to
15757 ~@code{C-x SPC}~.
15758
15759 A better approach is to define and use an Org macro named ~kbd~. To
15760 make that easier the function ~org-texinfo-kbd-macro~ is provided,
15761 which is intended to be used like this:
15762
15763 #+begin_example
15764 ,#+macro: kbd (eval (org-texinfo-kbd-macro $1))
15765
15766 Type {{{kbd(C-c SPC)}}}.
15767 #+end_example
15768
15769 #+texinfo: @noindent
15770 which becomes
15771
15772 #+begin_example
15773 Type @kbd{C-c @key{SPC}}.
15774 #+end_example
15775
1534015776 *** Special blocks in Texinfo export
1534115777 :PROPERTIES:
1534215778 :DESCRIPTION: Special block attributes.
1534315779 :END:
15780
15781 The Texinfo export back-end supports two approaches to writing Texinfo
15782 definition commands. One of them is described here, the other in
15783 [[*Plain lists in Texinfo export]].
1534415784
1534515785 #+cindex: @samp{ATTR_TEXINFO}, keyword
1534615786
1559316033 "Remove all headlines in the current buffer.
1559416034 BACKEND is the export back-end being used, as a symbol."
1559516035 (org-map-entries
15596 (lambda () (delete-region (point) (line-beginning-position 2)))))
16036 (lambda ()
16037 (delete-region (point) (line-beginning-position 2))
16038 ;; We need to tell `org-map-entries' to not skip over heading at
16039 ;; point. Otherwise, it would continue from _next_ heading. See
16040 ;; the docstring of `org-map-entries' for details.
16041 (setq org-map-continue-from (point)))))
1559716042
1559816043 (add-hook 'org-export-before-parsing-hook #'my-headline-removal)
1559916044 #+end_src
1595116396 ~org-org-publish-to-org~. This produces =file.org= and puts it in the
1595216397 publishing directory. If you want a htmlized version of this file,
1595316398 set the parameter ~:htmlized-source~ to ~t~. It produces
15954 =file.org.html= in the publishing directory[fn:141].
16399 =file.org.html= in the publishing directory[fn:: If the publishing
16400 directory is the same as the source directory, =file.org= is exported
16401 as =file.org.org=, so you probably do not want to do this.].
1595516402
1595616403 Other files like images only need to be copied to the publishing
1595716404 destination; for this you can use ~org-publish-attachment~. For
1610916556 | ~:html-preamble-format~ | ~org-html-preamble-format~ |
1611016557 | ~:html-preamble~ | ~org-html-preamble~ |
1611116558 | ~:html-self-link-headlines~ | ~org-html-self-link-headlines~ |
16112 | ~:html-table-align-individual-field~ | ~de{org-html-table-align-individual-fields~ |
16559 | ~:html-table-align-individual-field~ | ~org-html-table-align-individual-fields~ |
1611316560 | ~:html-table-attributes~ | ~org-html-table-default-attributes~ |
1611416561 | ~:html-table-caption-above~ | ~org-html-table-caption-above~ |
1611516562 | ~:html-table-data-tags~ | ~org-html-table-data-tags~ |
1614016587 | ~:latex-default-table-environment~ | ~org-latex-default-table-environment~ |
1614116588 | ~:latex-default-table-mode~ | ~org-latex-default-table-mode~ |
1614216589 | ~:latex-diary-timestamp-format~ | ~org-latex-diary-timestamp-format~ |
16590 | ~:latex-engraved-options~ | ~org-latex-engraved-options~ |
16591 | ~:latex-engraved-preamble~ | ~org-latex-engraved-preamble~ |
16592 | ~:latex-engraved-theme~ | ~org-latex-engraved-theme~ |
1614316593 | ~:latex-footnote-defined-format~ | ~org-latex-footnote-defined-format~ |
1614416594 | ~:latex-footnote-separator~ | ~org-latex-footnote-separator~ |
1614516595 | ~:latex-format-drawer-function~ | ~org-latex-format-drawer-function~ |
1615516605 | ~:latex-link-with-unknown-path-format~ | ~org-latex-link-with-unknown-path-format~ |
1615616606 | ~:latex-listings-langs~ | ~org-latex-listings-langs~ |
1615716607 | ~:latex-listings-options~ | ~org-latex-listings-options~ |
16158 | ~:latex-listings~ | ~org-latex-listings~ |
1615916608 | ~:latex-minted-langs~ | ~org-latex-minted-langs~ |
1616016609 | ~:latex-minted-options~ | ~org-latex-minted-options~ |
1616116610 | ~:latex-prefer-user-labels~ | ~org-latex-prefer-user-labels~ |
1616216611 | ~:latex-subtitle-format~ | ~org-latex-subtitle-format~ |
1616316612 | ~:latex-subtitle-separate~ | ~org-latex-subtitle-separate~ |
16613 | ~:latex-src-block-backend~ | ~org-latex-src-block-backend~ |
1616416614 | ~:latex-table-scientific-notation~ | ~org-latex-table-scientific-notation~ |
1616516615 | ~:latex-tables-booktabs~ | ~org-latex-tables-booktabs~ |
1616616616 | ~:latex-tables-centered~ | ~org-latex-tables-centered~ |
1617616626 | ~:md-footnote-format~ | ~org-md-footnote-format~ |
1617716627 | ~:md-footnotes-section~ | ~org-md-footnotes-section~ |
1617816628 | ~:md-headline-style~ | ~org-md-headline-style~ |
16629 | ~:md-toplevel-hlevel~ | ~org-md-toplevel-hlevel~ |
1617916630
1618016631 **** ODT specific properties
1618116632 :PROPERTIES:
1620316654 | ~:texinfo-active-timestamp-format~ | ~org-texinfo-active-timestamp-format~ |
1620416655 | ~:texinfo-classes~ | ~org-texinfo-classes~ |
1620516656 | ~:texinfo-class~ | ~org-texinfo-default-class~ |
16657 | ~:texinfo-compact-itemx | ~org-texinfo-compact-itemx~ |
1620616658 | ~:texinfo-table-default-markup~ | ~org-texinfo-table-default-markup~ |
1620716659 | ~:texinfo-diary-timestamp-format~ | ~org-texinfo-diary-timestamp-format~ |
1620816660 | ~:texinfo-filename~ | ~org-texinfo-filename~ |
1622316675 #+cindex: links, publishing
1622416676
1622516677 To create a link from one Org file to another, you would use something
16226 like =[[file:foo.org][The foo]]= or simply =[[file:foo.org]]= (see [[*External Links]]). When
16227 published, this link becomes a link to =foo.html=. You can thus
16228 interlink the pages of your "Org web" project and the links will work
16229 as expected when you publish them to HTML. If you also publish the
16230 Org source file and want to link to it, use an =http= link instead of
16231 a =file:= link, because =file= links are converted to link to the
16232 corresponding =.html= file.
16678 like =[[file:foo.org][The foo]]= or simply =[[file:foo.org]]= (see
16679 [[*External Links]]). When published, this link becomes a link to
16680 =foo.html=. You can thus interlink the pages of your "Org web"
16681 project and the links will work as expected when you publish them to
16682 HTML. If you also publish the Org source file and want to link to it,
16683 use an =http= link instead of a =file:= link, because =file= links are
16684 converted to link to the corresponding =.html= file.
16685
16686 Links to encrypted Org files, like =[[file:foo.org.gpg]]= are also
16687 supported.
1623316688
1623416689 You may also link to related files, such as images. Provided you are
1623516690 careful with relative file names, and provided you have also
1623716692 See [[*Example: complex publishing configuration]], for an example of this
1623816693 usage.
1623916694
16240 Eventually, links between published documents can contain some search
16241 options (see [[*Search Options in File Links]]), which will be resolved to
16242 the appropriate location in the linked file. For example, once
16243 published to HTML, the following links all point to a dedicated anchor
16244 in =foo.html=.
16695 Links between published documents can contain some search options (see
16696 [[*Search Options in File Links]]), which will be resolved to the
16697 appropriate location in the linked file. For example, once published
16698 to HTML, the following links all point to a dedicated anchor in
16699 =foo.html=.
1624516700
1624616701 #+begin_example
1624716702 [[file:foo.org::*heading]]
1653616991 - insert :: Add and edit citations via ~org-cite-insert~.
1653716992 - export :: Via different libraries for different target formats.
1653816993
16539 The user can configure these with ~org-cite-activate-processor~,
16994 To use a "citation processor", the user must load them; for example;
16995
16996 #+begin_src emacs-lisp
16997 (require 'oc-bibtex)
16998 #+end_src
16999
17000 They can then configure them with ~org-cite-activate-processor~,
1654017001 ~org-cite-follow-processor~, ~org-cite-insert-processor~, and
1654117002 ~org-cite-export-processors~ respectively.
1654217003
1656817029
1656917030 - Each key can be qualified by a /prefix/ (e.g.\nbsp{}"see ") and/or
1657017031 a /suffix/ (e.g.\nbsp{}"p.\nbsp{}123"), giving information useful or necessary
16571 fo the comprehension of the citation but not included in the
17032 for the comprehension of the citation but not included in the
1657217033 reference.
1657317034
1657417035 - A single citation can cite more than one reference ; the keys are
1660117062 - csl :: this export processor uses format files written in [[https://en.wikipedia.org/wiki/Citation_Style_Language][Citation
1660217063 Style Language]] via [[https://github.com/andras-simonyi/citeproc-el][citeproc-el]];
1660317064
16604 - In contrast, two other processors target LaTeX and LaTeX-derived
17065 - In contrast, three other processors target LaTeX and LaTeX-derived
1660517066 formats exclusively:
1660617067
16607 - natbib :: this export processor uses BibTeX, the historical
17068 - bibtex :: this export processor uses BibTeX, the historical
1660817069 bibliographic processor used with LaTeX, thus allowing the use of
16609 data and style files compatible with this processor (including
16610 a large number of publishers' styles). It uses citation commands
16611 implemented in the LaTeX package =natbib=, allowing more stylistic
16612 variants that LaTeX's =\cite= command.
17070 data and style files compatible with this processor (including a
17071 large number of publishers' styles). It only supports LaTeX's
17072 =\cite= and =\nocite= commands.
17073
17074 - natbib :: as with the bibtex processor, but using the LaTeX
17075 package =natbib=, allowing more stylistic variants that LaTeX's
17076 =\cite= command.
1661317077
1661417078 - biblatex :: this backend allows the use of data and formats
1661517079 prepared for BibLaTeX, an alternate bibliographic processor used
1664117105 conformant to the Harvard style and the specification of the
1664217106 Wolkers-Kluwer publisher; since it relies on the ~bibtex~ processor of
1664317107 your LaTeX installation, it won't export to anything but PDF.
17108
17109 ** Bibliography printing
17110
17111 The =PRINT_BIBLIOGRAPHY= keyword specifies where the bibliography
17112 should be printed (note the colon):
17113
17114 : #+print_bibliography:
17115
17116 The bibliography printed by the LaTeX-based export processors
17117 "bibtex", "natbib" and "biblatex" has a chapter or section heading by
17118 default, while the "basic" and "csl" processors print the list of
17119 bibliography entries without a heading.
17120
17121 A document may contain more than one =PRINT_BIBLIOGRAPHY= keywords.
17122 Each of the keywords will trigger printing the bibliography.
17123
17124 The keywords can be used with or without additional options. Options
17125 can be used, for example, to print only entries that belong to a
17126 certain category or to control formatting. The set of supported
17127 =PRINT_BIBLIOGRAPHY= options and their interpretation varies between
17128 the different citation export processors. Some export processors do
17129 not support passing options.
17130
17131 *** Bibliography options in the "biblatex" and "csl" export processors
17132
17133 The "biblatex" and "csl" export processors support bibliography
17134 options through a property list attached to the =PRINT_BIBLIOGRAPHY=
17135 keyword. For example,
17136
17137 : #print_bibliography: :keyword algebra :type book
17138
17139 Values including spaces must be surrounded with double quotes. If you
17140 need to use a key multiple times, you can separate its values with
17141 commas, but without any space in-between:
17142
17143 : #print_bibliography: :keyword "algebraic logic" :nottype article,book
17144
17145 The "biblatex" export processor accepts all options supported by
17146 BibLaTeX's ~\printbibliography~ command, while the "csl" processor
17147 accepts the following ones:
17148
17149 - =:keyword <keyword(,keyword2...)>= :: Print only entries whose
17150 keyword field contains all given keywords.
17151
17152 - =:notkeyword <keyword(,keyword2...)>= :: Print only entries whose
17153 keyword field does not contain any of the given keywords.
17154
17155 - =:type <entrytype>= :: Print only entries whose type is
17156 =<entrytype>=. Entry type is the BibTeX/BibLaTeX entry type if this
17157 information is available (the entry was read from a BibTeX/BibLaTeX
17158 bibliography) and the CSL entry type otherwise.
17159
17160 - =:nottype <entrytype(,entrytype2...)>= :: Print only entries whose
17161 type is not among the given entry types. Entry type is determined
17162 as in the case of =:type=.
17163
17164 - =:csltype <entrytype>= :: Print only entries whose CSL entry type
17165 (possibly based on a conversion from BibTeX/BibLaTeX to CSL) is
17166 =<entrytype>=.
17167
17168 - =:notcsltype <entrytype(,entrytype2...)>= :: Print only entries whose
17169 CSL entry type (possibly based on a conversion from BibTeX/BibLaTeX
17170 to CSL) is not among the listed entry types.
17171
17172 - =:filter <predicate>= :: Print only entries for which the given
17173 Emacs Lisp predicate returns a non-~nil~ value.
1664417174
1664517175 * Working with Source Code
1664617176 :PROPERTIES:
1680217332 Optional. Heading arguments control many aspects of evaluation,
1680317333 export and tangling of code blocks (see [[*Using Header Arguments]]).
1680417334 Using Org's properties feature, header arguments can be selectively
16805 applied to the entire buffer or specific sub-trees of the Org
17335 applied to the entire buffer or specific subtrees of the Org
1680617336 document.
1680717337
1680817338 - =<body>= ::
1684217372 :exports => "code"
1684317373 :cache => "no"
1684417374 :noweb => "no"
17375 :hlines => "no"
17376 :tangle => "no"
1684517377 #+end_example
17378
17379 #+vindex: org-babel-default-inline-header-args
17380 Inline source blocks (see [[*Structure of Code Blocks]]) use slightly
17381 different default header arguments defined in
17382 ~org-babel-default-inline-header-args~:
17383
17384 #+begin_example
17385 :session => "none"
17386 :results => "replace"
17387 :exports => "results"
17388 :hlines => "yes"
17389 #+end_example
17390
17391 The most notable difference between default header arguments for
17392 inline and normal source blocks is =:exports= argument. For inline
17393 source blocks, results of evaluation are exported by default; not the
17394 code.
17395
17396 Unlike the default values, header arguments set using Org mode
17397 properties (see [[*Header arguments in Org mode properties]]) do apply to
17398 both the normal source blocks and inline source blocks.
1684617399
1684717400 The example below sets =:noweb= header arguments to =yes=, which makes
1684817401 Org expand =:noweb= references by default.
1688117434
1688217435 #+vindex: org-use-property-inheritance
1688317436 Header arguments set through Org's property drawers (see [[*Property
16884 Syntax]]) apply at the sub-tree level on down. Since these property
17437 Syntax]]) apply at the subtree level on down. Since these property
1688517438 drawers can appear anywhere in the file hierarchy, Org uses outermost
1688617439 call or source block to resolve the values. Org ignores
1688717440 ~org-use-property-inheritance~ setting.
1688817441
1688917442 In this example, =:cache= defaults to =yes= for all code blocks in the
16890 sub-tree.
17443 subtree.
1689117444
1689217445 #+begin_example
1689317446 ,* sample header
1717617729 : 4
1717717730 #+end_example
1717817731
17179 - literal example ::
17180
17181 A literal example block named with a =NAME= keyword.
17732 - literal example, or code block contents ::
17733
17734 A code block or literal example block named with a =NAME= keyword,
17735 followed by brackets (optional for example blocks).
1718217736
1718317737 #+begin_example
1718417738 ,#+NAME: literal-example
1718817742 ,#+END_EXAMPLE
1718917743
1719017744 ,#+NAME: read-literal-example
17191 ,#+BEGIN_SRC emacs-lisp :var x=literal-example
17745 ,#+BEGIN_SRC emacs-lisp :var x=literal-example[]
1719217746 (concatenate #'string x " for you.")
1719317747 ,#+END_SRC
1719417748
1737117925 variable ~default-directory~. Setting =mkdirp= header argument to
1737217926 a non-~nil~ value creates the directory, if necessary.
1737317927
17928 Setting =dir= to the symbol ~attach~ or the string ~"'attach"~ will
17929 set =dir= to the directory returned by ~(org-attach-dir)~, set =:mkdir
17930 yes=, and insert any file paths, as when using =:results file=, which
17931 are under the node's attachment directory using =attachment:= links
17932 instead of the usual =file:= links. Any returned path outside of the
17933 attachment directory will use =file:= links as per usual.
17934
1737417935 For example, to save the plot file in the =Work/= folder of the home
1737517936 directory---notice tilde is expanded:
1737617937
1744918010 Org captures the results of the code block evaluation and inserts them
1745018011 in the Org file, right after the code block. The insertion point is
1745118012 after a newline and the =RESULTS= keyword. Org creates the =RESULTS=
17452 keyword if one is not already there.
18013 keyword if one is not already there. More details in [[*Results of
18014 Evaluation]].
1745318015
1745418016 By default, Org enables only Emacs Lisp code blocks for execution.
1745518017 See [[*Languages]] to enable other languages.
1745818020 #+kindex: C-c C-v e
1745918021 #+findex: org-babel-execute-src-block
1746018022 Org provides many ways to execute code blocks. {{{kbd(C-c C-c)}}} or
17461 {{{kbd(C-c C-v e)}}} with the point on a code block[fn:142] calls the
18023 {{{kbd(C-c C-v e)}}} with the point on a code block[fn:: The option
18024 ~org-babel-no-eval-on-ctrl-c-ctrl-c~ can be used to remove code
18025 evaluation from the {{{kbd(C-c C-c)}}} key binding.] calls the
1746218026 ~org-babel-execute-src-block~ function, which executes the code in the
1746318027 block, collects the results, and inserts them in the buffer.
1746418028
1746518029 #+cindex: @samp{CALL}, keyword
1746618030 #+vindex: org-babel-inline-result-wrap
17467 By calling a named code block[fn:143] from an Org mode buffer or
18031 By calling a named code block[fn:48] from an Org mode buffer or
1746818032 a table. Org can call the named code blocks from the current Org mode
1746918033 buffer or from the "Library of Babel" (see [[*Library of Babel]]).
1747018034
1753418098 The =eval= header argument can limit evaluation of specific code
1753518099 blocks and =CALL= keyword. It is useful for protection against
1753618100 evaluating untrusted code blocks by prompting for a confirmation.
18101
18102 - =yes= ::
18103
18104 Org evaluates the source code, possibly asking permission according
18105 to ~org-confirm-babel-evaluate~.
1753718106
1753818107 - =never= or =no= ::
1753918108
1760718176 In this example, both functions are cached. But =caller= runs only if
1760818177 the result from =random= has changed since the last run.
1760918178
18179 # +1 here is to work around Emacs bug#59293.
18180 # Otherwise, (1) is recognized as footnote reference by info.el.
1761018181 #+begin_example
1761118182 ,#+NAME: random
1761218183 ,#+BEGIN_SRC R :cache yes
17613 runif(1)
18184 runif(+1)
1761418185 ,#+END_SRC
1761518186
1761618187 ,#+RESULTS[a2a72cd647ad44515fab62e144796432793d68e1]: random
1766518236
1766618237 - =value= ::
1766718238
17668 Default for most Babel libraries[fn:143]. Functional mode. Org
18239 Default for most Babel libraries[fn:48]. Functional mode. Org
1766918240 gets the value by wrapping the code in a function definition in the
1767018241 language of the source block. That is why when using =:results
1767118242 value=, code should execute like a function and return a value. For
1769618267 :END:
1769718268
1769818269 Type tells what result types to expect from the execution of the code
17699 block. Choose one of the options; they are mutually exclusive. The
17700 default behavior is to automatically determine the result type.
18270 block. Choose one of the options; they are mutually exclusive.
18271
18272 The default behavior is to automatically determine the result type.
18273 The result type detection depends on the code block language, as
18274 described in the documentation for individual languages. See
18275 [[*Languages]].
1770118276
1770218277 #+attr_texinfo: :sep ,
1770318278 - =table=, =vector= ::
1784818423
1784918424 When used along with =file= type, the result is a link to the file
1785018425 specified in =:file= header argument. However, unlike plain =file=
17851 type, nothing is written to the disk. The block is used for its
17852 side-effects only, as in the following example:
18426 type, code block output is not written to the disk. The block is
18427 expected to generate the file by its side-effects only, as in the
18428 following example:
1785318429
1785418430 #+begin_example
17855 ,#+begin_src shell :results file link :file "download.tar.gz"
17856 wget -c "https://example.com/download.tar.gz"
18431 ,#+begin_src shell :results file link :file "org-mode-unicorn.svg"
18432 wget -c "https://orgmode.org/resources/img/org-mode-unicorn.svg"
1785718433 ,#+end_src
18434
18435 ,#+RESULTS:
18436 [[file:org-mode-unicorn.svg]]
1785818437 #+end_example
1785918438
1786018439 - =org= ::
1789718476 :UNNUMBERED: notoc
1789818477 :END:
1789918478
17900 Handling options after collecting the results.
18479 Handling options after collecting the results. Choose one of the
18480 options; they are mutually exclusive.
1790118481
1790218482 - =replace= ::
1790318483
1791118491
1791218492 - =none= ::
1791318493
17914 Do not process results at all. No inserting in the Org mode buffer
17915 nor echo them in the minibuffer. Usage example: =:results none=.
18494 Compute results, but do not do anything with them. No inserting in
18495 the Org mode buffer nor echo them in the minibuffer. The results
18496 can still be used when referenced from another code block.
18497 Usage example: =:results none=.
18498
18499 - =discard= ::
18500
18501 Ignore the results completely. This option is similar to =none=,
18502 but no processing is performed on the return value. Calling the
18503 code block programmatically (see [[*How to evaluate source code]]) or by
18504 reference (see [[*Passing arguments]] and [[*Noweb Reference Syntax]]) will
18505 always yield nil.
1791618506
1791718507 - =append= ::
1791818508
1800318593 It is possible to export the /code/ of code blocks, the /results/ of
1800418594 code block evaluation, /both/ the code and the results of code block
1800518595 evaluation, or /none/. Org defaults to exporting /code/ for most
18006 languages. For some languages, such as ditaa, Org defaults to
18007 /results/. To export just the body of code blocks, see [[*Literal
18008 Examples]]. To selectively export sub-trees of an Org document, see
18009 [[*Exporting]].
18596 languages and /results/ for inline code blocks. For some languages,
18597 such as ditaa, Org defaults to /results/ both in ordinary source
18598 blocks and in inline source blocks. To export just the body of code
18599 blocks, see [[*Literal Examples]]. To selectively export subtrees of an
18600 Org document, see [[*Exporting]].
1801018601
1801118602 #+cindex: @samp{exports}, header argument
1801218603 The =exports= header argument is to specify if that part of the Org
1803218623 Neither the code nor the results of evaluation is included in the
1803318624 exported file. Whether the code is evaluated at all depends on
1803418625 other options. Example: =:exports none=.
18626
18627 If a source block is named using =NAME= keyword, the same name will be
18628 assigned to the results of evaluation. This way, fuzzy links pointing
18629 to the named source blocks exported using =:exports results= will
18630 remain valid and point to the results of evaluation.
18631
18632 Results of evaluation of a named block can also be explicitly named
18633 using a separate =NAME= keyword. The name value set via =NAME=
18634 keyword will be preferred over the parent source block.
18635
18636 : #+NAME: code name
18637 : #+BEGIN_SRC emacs-lisp :exports both value
18638 : (+ 1 2)
18639 : #+END_SRC
18640 :
18641 : #+NAME: results name
18642 : #+RESULTS: code name
18643 : 3
18644 :
18645 : This [[code name][link]] will point to the code block.
18646 : Another [[results name][link]] will point to the results.
18647
18648 Explicit setting of the result name may be necessary when a named code
18649 block is exported using =:exports both=. Links to such block may
18650 arbitrarily point either to the code block or to its results when
18651 results do not have a distinct name.
18652
18653 Note that all the links pointing to a source block exported using
18654 =:exports none= will be broken. This will make export process fail,
18655 unless broken links are allowed during export (see [[*Export Settings]]).
1803518656
1803618657 #+vindex: org-export-use-babel
1803718658 To stop Org from evaluating code blocks to speed exports, use the
1804818669 the header arguments but not any code evaluation in the source block,
1804918670 set =:eval never-export= (see [[*Evaluating Code Blocks]]).
1805018671
18051 Org never evaluates code blocks in commented sub-trees when exporting
18672 Org never evaluates code blocks in commented subtrees when exporting
1805218673 (see [[*Comment Lines]]). On the other hand, Org does evaluate code
18053 blocks in sub-trees excluded from export (see [[*Export Settings]]).
18674 blocks in subtrees excluded from export (see [[*Export Settings]]).
1805418675
1805518676 ** Extracting Source Code
1805618677 :PROPERTIES:
1816418785
1816518786 #+cindex: @samp{tangle-mode}, header argument
1816618787 The =tangle-mode= header argument specifies what permissions to set
18167 for tangled files by ~set-file-modes~. For example, to make
18168 a read-only tangled file, use =:tangle-mode (identity #o444)=. To
18169 make it executable, use =:tangle-mode (identity #o755)=. It also
18170 overrides executable permission granted by =shebang=. When multiple
18171 source code blocks tangle to a single file with different and
18172 conflicting =tangle-mode= header arguments, Org's behavior is
18173 undefined.
18788 for tangled files by ~set-file-modes~. Permissions are given by an
18789 octal value, which can be provided calling the ~identity~ function on
18790 an elisp octal value. For instance, to create a read-only file one may
18791 use =:tangle-mode (identity #o444)=. To reduce the verbosity required,
18792 a octal shorthand is defined, =oXXX= (=o= for octal). Using this, our
18793 read-only example is =:tangle-mode o444=. Omitting the =o= prefix will
18794 cause the argument to be interpreted as an integer, which can lead to
18795 unexpected results (=444= is the same as =o674=).
18796 Two other shorthands are recognized, ls-style strings like
18797 =rw-r--r--=, and chmod-style permissions like =g+w=.
18798 Note that chmod-style permissions are based on
18799 ~org-babel-tangle-default-file-mode~, which is =#o544= by default.
18800
18801 When =:tangle-mode= and =:shebang= are both specified, the give
18802 =:tangle-mode= will override the permissions from =:shebang=. When
18803 multiple source code blocks tangle to a single file with conflicting
18804 =:tangle-mode= header arguments, Org's behavior is undefined.
1817418805
1817518806 #+cindex: @samp{no-expand}, header argument
1817618807 By default Org expands code blocks during tangling. The =no-expand=
1820718838 :UNNUMBERED: notoc
1820818839 :END:
1820918840
18841 - ~org-babel-pre-tangle-hook~ ::
18842
18843 #+vindex: org-babel-pre-tangle-hook
18844 This hook is run before the tangle process begins. The active
18845 buffer is buffer to be tangled.
18846
18847 - ~org-babel-tangle-body-hook~ ::
18848
18849 #+vindex: org-babel-tangle-body-hook
18850 This hook is run from a temporary buffer containing expanded code of
18851 every tangled code block. The hook can modify the expanded code as
18852 needed. The contents of the current buffer will be used as actual
18853 code block expansion.
18854
1821018855 - ~org-babel-post-tangle-hook~ ::
1821118856
1821218857 #+vindex: org-babel-post-tangle-hook
1821318858 This hook is run from within code files tangled by
1821418859 ~org-babel-tangle~, making it suitable for post-processing,
1821518860 compilation, and evaluation of code in the tangled files.
18861
18862 - ~org-babel-tangle-finished-hook~ ::
18863 #+vindex: org-babel-tangle-finished-hook
18864 This hook is run after post-tangle hooks, in the original buffer.
1821618865
1821718866 *** Jumping between code and Org
1821818867 :PROPERTIES:
1823818887 #+cindex: source code, languages
1823918888 #+cindex: code block, languages
1824018889
18241 Code blocks in dozens of languages are supported. See Worg for
18242 [[https://orgmode.org/worg/org-contrib/babel/languages/index.html][language specific documentation]].
18890 Code blocks in dozens of languages are supported. See Worg website
18891 for [[https://orgmode.org/worg/org-contrib/babel/languages/index.html][language specific documentation]].
1824318892
1824418893 #+vindex: org-babel-load-languages
1824518894 By default, only Emacs Lisp is enabled for evaluation. To enable or
1835319002
1835419003 #+cindex: @samp{noweb-ref}, header argument
1835519004 Source code blocks can include references to other source code blocks,
18356 using a noweb[fn:144] style syntax:
19005 using a noweb[fn:: For noweb literate programming details, see
19006 https://www.cs.tufts.edu/~nr/noweb/.] style syntax:
1835719007
1835819008 : <<CODE-BLOCK-ID>>
1835919009
1838619036 Expansion of noweb syntax references in the body of the code block
1838719037 when tangling. No expansion when evaluating or exporting.
1838819038
19039 - =strip-tangle= ::
19040
19041 Expansion of noweb syntax references in the body of the code block
19042 when evaluating or exporting. Removes noweb syntax references
19043 when exporting.
19044
1838919045 - =no-export= ::
1839019046
1839119047 Expansion of noweb syntax references in the body of the code block
1842819084 #+end_example
1842919085
1843019086 You may also include the contents of multiple blocks sharing a common
18431 =noweb-ref= header argument, which can be set at the file, sub-tree,
19087 =noweb-ref= header argument, which can be set at the file, subtree,
1843219088 or code block level. In the example Org file shown next, the body of
1843319089 the source code in each block is extracted for concatenation to a pure
1843419090 code file when tangled.
1858419240 print('do things when true')
1858519241 else:
1858619242 print('do things when false')
19243 #+end_example
19244
19245 This prefix behavior can be turned off in a block by setting the
19246 =noweb-prefix= header argument to =no=, as in:
19247
19248 #+begin_example
19249 ,#+BEGIN_SRC elisp :noweb-prefix no
19250 (setq example-data "<<example>>")
19251 ,#+END_SRC
19252 #+end_example
19253
19254 #+texinfo: @noindent
19255 which expands to:
19256
19257 #+begin_example
19258 (setq example-data "this is the
19259 multi-line body of example")
1858719260 #+end_example
1858819261
1858919262 When in doubt about the outcome of a source code block expansion, you
1886419537 ~org-structure-template-alist~ and ~org-tempo-keywords-alist~. For
1886519538 example, {{{kbd(< s TAB)}}} creates a code block. Enable it by
1886619539 customizing ~org-modules~ or add =(require 'org-tempo)= to your Emacs
18867 init file[fn:145].
19540 init file[fn:: For more information, please refer to the commentary
19541 section in =org-tempo.el=.].
1886819542
1886919543 #+attr_texinfo: :columns 0.1 0.9
1887019544 | {{{kbd(a)}}} | =#+BEGIN_EXPORT ascii= ... =#+END_EXPORT= |
1894419618 To display the buffer in the indented view, activate Org Indent minor
1894519619 mode, using {{{kbd(M-x org-indent-mode)}}}. Text lines that are not
1894619620 headlines are prefixed with virtual spaces to vertically align with
18947 the headline text[fn:146].
19621 the headline text[fn:49].
1894819622
1894919623 #+vindex: org-indent-indentation-per-level
1895019624 To make more horizontal space, the headlines are shifted by two
1897219646
1897319647 It is possible to use hard spaces to achieve the indentation instead,
1897419648 if the bare ASCII file should have the indented look also outside
18975 Emacs[fn:147]. With Org's support, you have to indent all lines to
18976 line up with the outline headers. You would use these
18977 settings[fn:148]:
19649 Emacs[fn:50]. With Org's support, you have to indent all lines to
19650 line up with the outline headers. You would use these settings[fn::
19651 ~org-adapt-indentation~ can also be set to ='headline-data=, in which
19652 case only data lines below the headline will be indented.]:
1897819653
1897919654 #+begin_src emacs-lisp
1898019655 (setq org-adapt-indentation t
1913719812 #+cindex: special keywords
1913819813
1913919814 In-buffer settings start with =#+=, followed by a keyword, a colon,
19140 and then a word for each setting. Org accepts multiple settings on
19141 the same line. Org also accepts multiple lines for a keyword. This
19142 manual describes these settings throughout. A summary follows here.
19815 one or more spaces, and then a word for each setting. Org accepts
19816 multiple settings on the same line. Org also accepts multiple lines
19817 for a keyword. This manual describes these settings throughout. A
19818 summary follows here.
1914319819
1914419820 #+cindex: refresh set-up
1914519821 {{{kbd(C-c C-c)}}} activates any changes to the in-buffer settings.
1924519921
1924619922 #+vindex: org-startup-indented
1924719923 Dynamic virtual indentation is controlled by the variable
19248 ~org-startup-indented~[fn:149].
19924 ~org-startup-indented~[fn:: Note that Org Indent mode also sets the
19925 ~wrap-prefix~ property, such that Visual Line mode (or purely
19926 setting ~word-wrap~) wraps long lines, including headlines,
19927 correctly indented.].
1924919928
1925019929 | =indent= | Start with Org Indent mode turned on. |
1925119930 | =noindent= | Start with Org Indent mode turned off. |
1935120030 | =nofnadjust= | Do not renumber and sort automatically. |
1935220031
1935320032 #+vindex: org-hide-block-startup
19354 To hide blocks on startup, use these keywords. The
19355 corresponding variable is ~org-hide-block-startup~.
19356
19357 | =hideblocks= | Hide all begin/end blocks on startup. |
19358 | =nohideblocks= | Do not hide blocks on startup. |
20033 #+vindex: org-hide-drawer-startup
20034 To hide blocks or drawers on startup, use these keywords. The
20035 corresponding variables are ~org-hide-block-startup~ and
20036 ~org-hide-drawer-startup~.
20037
20038 | =hideblocks= | Hide all begin/end blocks on startup. |
20039 | =nohideblocks= | Do not hide blocks on startup. |
20040 | =hidedrawers= | Hide all begin/end blocks on startup. |
20041 | =nohidedrawers= | Do not hide blocks on startup. |
20042
1935920043
1936020044 #+vindex: org-pretty-entities
1936120045 The display of entities as UTF-8 characters is governed by the
1977420458 (add-to-list 'org-tab-first-hook 'yas/org-very-safe-expand)
1977520459 (define-key yas/keymap [tab] 'yas/next-field)))
1977620460 #+end_src
20461
1977720462 ** Using Org on a TTY
1977820463 :PROPERTIES:
1977920464 :DESCRIPTION: Using Org on a tty.
2004420729 (setq org-tags-exclude-from-inheritance '("crypt"))
2004520730
2004620731 (setq org-crypt-key nil)
20047 ;; GPG key to use for encryption
20048 ;; Either the Key ID or set to nil to use symmetric encryption.
20732 ;; GPG key to use for encryption.
20733 ;; nil means use symmetric encryption unconditionally.
20734 ;; "" means use symmetric encryption unless heading sets CRYPTKEY property.
2004920735
2005020736 (setq auto-save-default nil)
2005120737 ;; Auto-saving does not cooperate with org-crypt.el: so you need to
2006620752 :CRYPTKEY: 0x0123456789012345678901234567890123456789
2006720753 :END:
2006820754 #+end_example
20755
20756 Note that =CRYPTKEY= property is only effective when ~org-crypt-key~
20757 is set to non-nil. ~nil~ value of ~org-crypt-key~ makes Org use
20758 symmetric encryption unconditionally.
2006920759
2007020760 Excluding the =crypt= tag from inheritance prevents already encrypted
2007120761 text from being encrypted again.
2010220792
2010320793 #+vindex: org-mobile-directory
2010420794 The mobile application needs access to a file directory on
20105 a server[fn:150] to interact with Emacs. Pass its location through
20795 a server[fn:51] to interact with Emacs. Pass its location through
2010620796 the ~org-mobile-directory~ variable. If you can mount that directory
2010720797 locally just set the variable to point to that directory:
2010820798
2012320813 requires OpenSSL installed on the local computer. To turn on
2012420814 encryption, set the same password in the mobile application and in
2012520815 Emacs. Set the password in the variable
20126 ~org-mobile-use-encryption~[fn:151]. Note that even after the mobile
20127 application encrypts the file contents, the file name remains visible
20128 on the file systems of the local computer, the server, and the mobile
20129 device.
20816 ~org-mobile-use-encryption~[fn:: If Emacs is configured for safe
20817 storing of passwords, then configure the variable
20818 ~org-mobile-encryption-password~; please read the docstring of that
20819 variable.]. Note that even after the mobile application encrypts the
20820 file contents, the file name remains visible on the file systems of
20821 the local computer, the server, and the mobile device.
2013020822
2013120823 *** Pushing to the mobile application
2013220824 :PROPERTIES:
2013920831 ~org-mobile-files~ into the staging area. Files include agenda files
2014020832 (as listed in ~org-agenda-files~). Customize ~org-mobile-files~ to
2014120833 add other files. File names are staged with paths relative to
20142 ~org-directory~, so all files should be inside this directory[fn:152].
20834 ~org-directory~, so all files should be inside this directory[fn::
20835 Symbolic links in ~org-directory~ need to have the same name as their
20836 targets.].
2014320837
2014420838 Push creates a special Org file =agendas.org= with custom agenda views
20145 defined by the user[fn:153].
20839 defined by the user[fn:52].
2014620840
2014720841 Finally, Org writes the file =index.org=, containing links to other
2014820842 files. The mobile application reads this file first from the server
2014920843 to determine what other files to download for agendas. For faster
20150 downloads, it is expected to only read files whose checksums[fn:154]
20151 have changed.
20844 downloads, it is expected to only read files whose checksums[fn::
20845 Checksums are stored automatically in the file =checksums.dat=.] have
20846 changed.
2015220847
2015320848 *** Pulling from the mobile application
2015420849 :PROPERTIES:
2016420859
2016520860 1.
2016620861 #+vindex: org-mobile-inbox-for-pull
20167 Org moves all entries found in =mobileorg.org=[fn:155] and appends
20168 them to the file pointed to by the variable
20169 ~org-mobile-inbox-for-pull~. It should reside neither in the
20170 staging area nor on the server. Each captured entry and each
20171 editing event is a top-level entry in the inbox file.
20862 Org moves all entries found in =mobileorg.org=[fn:: The file will
20863 be empty after this operation.] and appends them to the file
20864 pointed to by the variable ~org-mobile-inbox-for-pull~. It should
20865 reside neither in the staging area nor on the server. Each
20866 captured entry and each editing event is a top-level entry in the
20867 inbox file.
2017220868
2017320869 2.
2017420870 #+cindex: @samp{FLAGGED}, tag
2045821154 #+cindex: @LaTeX{}, and Orgtbl mode
2045921155
2046021156 To wrap a source table in LaTeX, use the =comment= environment
20461 provided by =comment.sty=[fn:156]. To activate it, put
20462 ~\usepackage{comment}~ in the document header. Orgtbl mode inserts
20463 a radio table skeleton[fn:157] with the command {{{kbd(M-x
20464 orgtbl-insert-radio-table)}}}, which prompts for a table name. For
20465 example, if =salesfigures= is the name, the template inserts:
21157 provided by =comment.sty=[fn:: https://www.ctan.org/pkg/comment]. To
21158 activate it, put ~\usepackage{comment}~ in the document header.
21159 Orgtbl mode inserts a radio table skeleton[fn:53] with the command
21160 {{{kbd(M-x orgtbl-insert-radio-table)}}}, which prompts for a table
21161 name. For example, if =salesfigures= is the name, the template
21162 inserts:
2046621163
2046721164 #+begin_example
2046821165 % BEGIN RECEIVE ORGTBL salesfigures
2047921176 ~orgtbl-to-latex~ to convert the table to LaTeX format, then insert
2048021177 the table at the target (receive) location named =salesfigures=. Now
2048121178 the table is ready for data entry. It can even use spreadsheet
20482 features[fn:158]:
21179 features[fn:54]:
2048321180
2048421181 #+begin_example
2048521182 % BEGIN RECEIVE ORGTBL salesfigures
2069521392 #+vindex: org-agenda-skip-function
2069621393 #+vindex: org-agenda-skip-function-global
2069721394 Org provides a special hook to further limit items in agenda views:
20698 ~agenda~, ~agenda*~[fn:159], ~todo~, ~alltodo~, ~tags~, ~tags-todo~,
20699 ~tags-tree~. Specify a custom function that tests inclusion of every
20700 matched item in the view. This function can also skip as much as is
20701 needed.
21395 ~agenda~, ~agenda*~[fn:: The ~agenda*~ view is the same as ~agenda~
21396 except that it only considers /appointments/, i.e., scheduled and
21397 deadline items that have a time specification =[h]h:mm= in their
21398 time-stamps.], ~todo~, ~alltodo~, ~tags~, ~tags-todo~, ~tags-tree~.
21399 Specify a custom function that tests inclusion of every matched item
21400 in the view. This function can also skip as much as is needed.
2070221401
2070321402 For a global condition applicable to agenda views, use the
2070421403 ~org-agenda-skip-function-global~ variable. Org uses a global
2073621435
2073721436 #+vindex: org-odd-levels-only
2073821437 #+vindex: org-agenda-skip-function
21438 #+findex: org-agenda-skip-entry-if
21439 #+findex: org-agenda-skip-subtree-if
2073921440 Search for entries with a limit set on levels for the custom search.
2074021441 This is a general approach to creating custom searches in Org. To
20741 include all levels, use =LEVEL>0=[fn:160]. Then to selectively pick
20742 the matched entries, use ~org-agenda-skip-function~, which also
20743 accepts Lisp forms, such as ~org-agenda-skip-entry-if~ and
21442 include all levels, use =LEVEL>0=[fn:: Note that, for
21443 ~org-odd-levels-only~, a level number corresponds to order in the
21444 hierarchy, not to the number of stars.]. Then to selectively pick the
21445 matched entries, use ~org-agenda-skip-function~, which also accepts
21446 Lisp forms, such as ~org-agenda-skip-entry-if~ and
2074421447 ~org-agenda-skip-subtree-if~. For example:
2074521448
2074621449 - =(org-agenda-skip-entry-if 'scheduled)= ::
2083221535 #+begin_src emacs-lisp
2083321536 (setq org-agenda-use-tag-inheritance nil)
2083421537 #+end_src
21538
21539 #+vindex: org-agenda-ignore-properties
21540 - Disable parsing of some drawer properties:
21541
21542 #+begin_src emacs-lisp
21543 (setq org-agenda-ignore-properties '(effort appt stats category))
21544 #+end_src
21545
21546 The drawer properties you can disable in the agenda are effort
21547 estimates (~effort~), appointments (~appt~), statistics (~stats~)
21548 and subtree-local categories (~category~).
2083521549
2083621550 These options can be applied to selected agenda views. For more
2083721551 details about generation of agenda views, see the docstrings for the
2106621780
2106721781 {{{var(FUNC)}}} is a function or a Lisp form. With point positioned
2106821782 at the beginning of the headline, call the function without arguments.
21069 Org returns an alist of return values of calls to the function.
21783 Org returns a list of return values of calls to the function.
2107021784
2107121785 To avoid preserving point, Org wraps the call to {{{var(FUNC)}}} in
2107221786 ~save-excursion~ form. After evaluation, Org moves point to the end
2107321787 of the line that was just processed. Search continues from that point
2107421788 forward. This may not always work as expected under some conditions,
21075 such as if the current sub-tree was removed by a previous archiving
21789 such as if the current subtree was removed by a previous archiving
2107621790 operation. In such rare circumstances, Org skips the next entry
2107721791 entirely when it should not. To stop Org from such skips, make
2107821792 {{{var(FUNC)}}} set the variable ~org-map-continue-from~ to a specific
2160022314
2160122315 This manual is for Org version {{{version}}}.
2160222316
21603 Copyright \copy 2004--2021 Free Software Foundation, Inc.
22317 Copyright \copy 2004--2023 Free Software Foundation, Inc.
2160422318
2160522319 #+begin_quote
2160622320 Permission is granted to copy, distribute and/or modify this document
2162622340
2162722341 * Footnotes
2162822342
21629 [fn:1] If you do not use Font Lock globally turn it on in Org buffer
21630 with =(add-hook 'org-mode-hook #'turn-on-font-lock)=.
21631
21632 [fn:2] Please consider subscribing to the mailing list in order to
21633 minimize the work the mailing list moderators have to do.
21634
21635 [fn:3] See the variables ~org-special-ctrl-a/e~, ~org-special-ctrl-k~,
22343 [fn:1] See the variables ~org-special-ctrl-a/e~, ~org-special-ctrl-k~,
2163622344 and ~org-ctrl-k-protect-subtree~ to configure special behavior of
2163722345 {{{kbd(C-a)}}}, {{{kbd(C-e)}}}, and {{{kbd(C-k)}}} in headlines. Note
2163822346 also that clocking only works with headings indented less than 30
2163922347 stars.
2164022348
21641 [fn:4] See, however, the option ~org-cycle-emulate-tab~.
21642
21643 [fn:5] The indirect buffer contains the entire buffer, but is narrowed
22349 [fn:2] The indirect buffer contains the entire buffer, but is narrowed
2164422350 to the current tree. Editing the indirect buffer also changes the
2164522351 original buffer, but without affecting visibility in that buffer. For
2164622352 more information about indirect buffers, see [[info:emacs#Indirect Buffers][GNU Emacs Manual]].
2164722353
21648 [fn:6] When ~org-agenda-inhibit-startup~ is non-~nil~, Org does not
21649 honor the default visibility state when first opening a file for the
21650 agenda (see [[*Speeding Up Your Agendas]]).
21651
21652 [fn:7] See also the variable ~org-show-context-detail~ to decide how
21653 much context is shown around each match.
21654
21655 [fn:8] This depends on the option ~org-remove-highlights-with-change~.
21656
21657 [fn:9] When using =*= as a bullet, lines must be indented so that they
22354 [fn:3] When using =*= as a bullet, lines must be indented so that they
2165822355 are not interpreted as headlines. Also, when you are hiding leading
2165922356 stars to get a clean outline view, plain list items starting with
2166022357 a star may be hard to distinguish from true headlines. In short: even
2166122358 though =*= is supported, it may be better to not use it for plain list
2166222359 items.
2166322360
21664 [fn:10] You can filter out any of them by configuring
21665 ~org-plain-list-ordered-item-terminator~.
21666
21667 [fn:11] You can also get =a.=, =A.=, =a)= and =A)= by configuring
22361 [fn:4] You can also get =a.=, =A.=, =a)= and =A)= by configuring
2166822362 ~org-list-allow-alphabetical~. To minimize confusion with normal
2166922363 text, those are limited to one character only. Beyond that limit,
2167022364 bullets automatically become numbers.
2167122365
21672 [fn:12] If there's a checkbox in the item, the cookie must be put
22366 [fn:5] If there's a checkbox in the item, the cookie must be put
2167322367 /before/ the checkbox. If you have activated alphabetical lists, you
2167422368 can also use counters like =[@b]=.
2167522369
21676 [fn:13] If you do not want the item to be split, customize the
21677 variable ~org-M-RET-may-split-line~.
21678
21679 [fn:14] If you want to cycle around items that way, you may customize
21680 ~org-list-use-circular-motion~.
21681
21682 [fn:15] See ~org-list-use-circular-motion~ for a cyclic behavior.
21683
21684 [fn:16] Many desktops intercept {{{kbd(M-TAB)}}} to switch windows.
22370 [fn:6] Many desktops intercept {{{kbd(M-TAB)}}} to switch windows.
2168522371 Use {{{kbd(C-M-i)}}} or {{{kbd(ESC TAB)}}} instead.
2168622372
21687 [fn:17] To insert a vertical bar into a table field, use =\vert= or,
21688 inside a word =abc\vert{}def=.
21689
21690 [fn:18] Org understands references typed by the user as =B4=, but it
22373 [fn:7] Org understands references typed by the user as =B4=, but it
2169122374 does not use this syntax when offering a formula for editing. You can
2169222375 customize this behavior using the variable
2169322376 ~org-table-use-standard-references~.
2169422377
21695 [fn:19] The computation time scales as O(N^2) because table
21696 {{{var(FOO)}}} is parsed for each field to be copied.
21697
21698 [fn:20] The file =constants.el= can supply the values of constants in
22378 [fn:8] The file =constants.el= can supply the values of constants in
2169922379 two different unit systems, =SI= and =cgs=. Which one is used depends
2170022380 on the value of the variable ~constants-unit-system~. You can use the
2170122381 =STARTUP= options =constSI= and =constcgs= to set this value for the
2170222382 current buffer.
2170322383
21704 [fn:21] The printf reformatting is limited in precision because the
22384 [fn:9] The printf reformatting is limited in precision because the
2170522385 value passed to it is converted into an "integer" or "double". The
2170622386 "integer" is limited in size by truncating the signed value to 32
2170722387 bits. The "double" is limited in precision to 64 bits overall which
2170822388 leaves approximately 16 significant decimal digits.
2170922389
21710 [fn:22] Such names must start with an alphabetic character and use
21711 only alphanumeric/underscore characters.
21712
21713 [fn:23] Plain URIs are recognized only for a well-defined set of
22390 [fn:10] Plain URIs are recognized only for a well-defined set of
2171422391 schemes. See [[*External Links]]. Unlike URI syntax, they cannot contain
2171522392 parenthesis or white spaces, either. URIs within angle brackets have
2171622393 no such limitation.
2171722394
21718 [fn:24] More accurately, the precise behavior depends on how point
21719 arrived there---see [[info:elisp#Invisible Text][Invisible Text]].
21720
21721 [fn:25] To insert a link targeting a headline, in-buffer completion
22395 [fn:11] To insert a link targeting a headline, in-buffer completion
2172222396 can be used. Just type a star followed by a few optional letters into
2172322397 the buffer and press {{{kbd(M-TAB)}}}. All headlines in the current
2172422398 buffer are offered as completions.
2172522399
21726 [fn:26] When targeting a =NAME= keyword, the =CAPTION= keyword is
21727 mandatory in order to get proper numbering (see [[*Captions]]).
21728
21729 [fn:27] The actual behavior of the search depends on the value of the
22400 [fn:12] The actual behavior of the search depends on the value of the
2173022401 variable ~org-link-search-must-match-exact-headline~. If its value is
2173122402 ~nil~, then a fuzzy text search is done. If it is ~t~, then only the
2173222403 exact headline is matched, ignoring spaces and statistic cookies. If
2173322404 the value is ~query-to-create~, then an exact headline is searched; if
2173422405 it is not found, then the user is queried to create it.
2173522406
21736 [fn:28] If the headline contains a timestamp, it is removed from the
21737 link, which results in a wrong link---you should avoid putting
21738 a timestamp in the headline.
21739
21740 [fn:29] The Org Id library must first be loaded, either through
21741 ~org-customize~, by enabling ~id~ in ~org-modules~, or by adding
21742 =(require 'org-id)= in your Emacs init file.
21743
21744 [fn:30] Note that you do not have to use this command to insert
22407 [fn:13] Note that you do not have to use this command to insert
2174522408 a link. Links in Org are plain text, and you can type or paste them
2174622409 straight into the buffer. By using this command, the links are
2174722410 automatically enclosed in double brackets, and you will be asked for
2174822411 the optional descriptive text.
2174922412
21750 [fn:31] After insertion of a stored link, the link will be removed
22413 [fn:14] After insertion of a stored link, the link will be removed
2175122414 from the list of stored links. To keep it in the list for later use,
2175222415 use a triple {{{kbd(C-u)}}} prefix argument to {{{kbd(C-c C-l)}}}, or
2175322416 configure the option ~org-link-keep-stored-after-insertion~.
2175422417
21755 [fn:32] This works if a function has been defined in the ~:complete~
21756 property of a link in ~org-link-parameters~.
21757
21758 [fn:33] See the variable ~org-link-use-indirect-buffer-for-internals~.
21759
21760 [fn:34] For backward compatibility, line numbers can also follow a
21761 single colon.
21762
21763 [fn:35] Of course, you can make a document that contains only long
21764 lists of TODO items, but this is not required.
21765
21766 [fn:36] Changing the variable ~org-todo-keywords~ only becomes
21767 effective after restarting Org mode in a buffer.
21768
21769 [fn:37] This is also true for the {{{kbd(t)}}} command in the agenda
21770 buffer.
21771
21772 [fn:38] All characters are allowed except =@=, =^= and =!=, which have
21773 a special meaning here.
21774
21775 [fn:39] Check also the variable ~org-fast-tag-selection-include-todo~,
22418 [fn:15] Check also the variable ~org-fast-tag-selection-include-todo~,
2177622419 it allows you to change the TODO state through the tags interface (see
2177722420 [[*Setting Tags]]), in case you like to mingle the two concepts. Note
2177822421 that this means you need to come up with unique keys across both sets
2177922422 of keywords.
2178022423
21781 [fn:40] Org mode parses these lines only when Org mode is activated
21782 after visiting a file. {{{kbd(C-c C-c)}}} with point in a line
21783 starting with =#+= is simply restarting Org mode for the current
21784 buffer.
21785
21786 [fn:41] The corresponding in-buffer setting is: =#+STARTUP: logdone=.
21787
21788 [fn:42] The corresponding in-buffer setting is: =#+STARTUP:
21789 lognotedone=.
21790
21791 [fn:43] See the variable ~org-log-states-order-reversed~.
21792
21793 [fn:44] Note that the =LOGBOOK= drawer is unfolded when pressing
21794 {{{kbd(SPC)}}} in the agenda to show an entry---use {{{kbd(C-u
21795 SPC)}}} to keep it folded here.
21796
21797 [fn:45] It is possible that Org mode records two timestamps when you
22424 [fn:16] It is possible that Org mode records two timestamps when you
2179822425 are using both ~org-log-done~ and state change logging. However, it
2179922426 never prompts for two notes: if you have configured both, the state
2180022427 change recording note takes precedence and cancel the closing note.
2180122428
21802 [fn:46] See also the option ~org-priority-start-cycle-with-default~.
21803
21804 [fn:47] To keep subtasks out of the global TODO list, see the option
21805 ~org-agenda-todo-list-sublevels~.
21806
21807 [fn:48] With the exception of description lists. But you can allow it
22429 [fn:17] With the exception of description lists. But you can allow it
2180822430 by modifying ~org-list-automatic-rules~ accordingly.
2180922431
21810 [fn:49] Set the variable ~org-hierarchical-checkbox-statistics~ if you
21811 want such cookies to count all checkboxes below the cookie, not just
21812 those belonging to direct children.
21813
21814 [fn:50] {{{kbd(C-u C-c C-c)}}} on the /first/ item of a list with no
21815 checkbox adds checkboxes to the rest of the list.
21816
21817 [fn:51] As with all these in-buffer settings, pressing {{{kbd(C-c
21818 C-c)}}} activates any changes in the line.
21819
21820 [fn:52] This is only true if the search does not involve more complex
21821 tests including properties (see [[*Property Searches]]).
21822
21823 [fn:53] To extend this default list to all tags used in all agenda
21824 files (see [[*Agenda Views]]), customize the variable
21825 ~org-complete-tags-always-offer-all-agenda-tags~.
21826
21827 [fn:54] Keys are automatically assigned to tags that have no
21828 configured keys.
21829
21830 [fn:55] If more than one summary type applies to the same property,
21831 the parent values are computed according to the first of them.
21832
21833 [fn:56] An age can be defined as a duration, using units defined in
22432 [fn:18] An age can be defined as a duration, using units defined in
2183422433 ~org-duration-units~, e.g., =3d 1h=. If any value in the column is as
2183522434 such, the summary is also expressed as a duration.
2183622435
21837 [fn:57] Please note that the =COLUMNS= definition must be on a single
21838 line; it is wrapped here only because of formatting constraints.
21839
21840 [fn:58] Contributed packages are not part of Emacs, but are
21841 distributed with the main distribution of Org---visit
21842 [[https://orgmode.org]].
21843
21844 [fn:59] The Org date format is inspired by the standard ISO 8601
22436 [fn:19] The Org date format is inspired by the standard ISO 8601
2184522437 date/time format. To use an alternative format, see [[*Custom time
2184622438 format]]. The day name is optional when you type the date yourself.
2184722439 However, any date inserted or modified by Org adds that day name, for
2184822440 reading convenience.
2184922441
21850 [fn:60] When working with the standard diary expression functions, you
22442 [fn:20] When working with the standard diary expression functions, you
2185122443 need to be very careful with the order of the arguments. That order
2185222444 depends evilly on the variable ~calendar-date-style~. For example, to
21853 specify a date December 12, 2005, the call might look like
22445 specify a date December 1, 2005, the call might look like
2185422446 =(diary-date 12 1 2005)= or =(diary-date 1 12 2005)= or =(diary-date
2185522447 2005 12 1)=, depending on the settings. This has been the source of
2185622448 much confusion. Org mode users can resort to special versions of
21857 these functions like ~org-date~ or ~org-anniversary~. These work just
21858 like the corresponding ~diary-~ functions, but with stable ISO order
21859 of arguments (year, month, day) wherever applicable, independent of
21860 the value of ~calendar-date-style~.
21861
21862 [fn:61] See the variable ~org-read-date-prefer-future~. You may set
22449 these functions, namely ~org-date~, ~org-anniversary~, ~org-cyclic, and
22450 ~org-block~. These work just like the corresponding ~diary-~
22451 functions, but with stable ISO order of arguments (year, month, day)
22452 wherever applicable, independent of the value of
22453 ~calendar-date-style~.
22454
22455 [fn:21] See the variable ~org-read-date-prefer-future~. You may set
2186322456 that variable to the symbol ~time~ to even make a time before now
2186422457 shift the date to tomorrow.
2186522458
21866 [fn:62] If you do not need/want the calendar, configure the variable
21867 ~org-popup-calendar-for-date-prompt~.
21868
21869 [fn:63] You can also use the calendar command {{{kbd(.)}}} to jump to
22459 [fn:22] You can also use the calendar command {{{kbd(.)}}} to jump to
2187022460 today's date, but if you are inserting an hour specification for your
2187122461 timestamp, {{{kbd(.)}}} will then insert a dot after the hour. By contrast,
2187222462 {{{kbd(C-.)}}} will always jump to today's date.
2187322463
21874 [fn:64] If you find this distracting, turn off the display with
21875 ~org-read-date-display-live~.
21876
21877 [fn:65] It will still be listed on that date after it has been marked
22464 [fn:23] It will still be listed on that date after it has been marked
2187822465 as done. If you do not like this, set the variable
2187922466 ~org-agenda-skip-scheduled-if-done~.
2188022467
21881 [fn:66] The =SCHEDULED= and =DEADLINE= dates are inserted on the line
22468 [fn:24] The =SCHEDULED= and =DEADLINE= dates are inserted on the line
2188222469 right below the headline. Do not put any text between this line and
2188322470 the headline.
2188422471
21885 [fn:67] Note the corresponding =STARTUP= options =logredeadline=,
21886 =lognoteredeadline=, and =nologredeadline=.
21887
21888 [fn:68] Note the corresponding =STARTUP= options =logreschedule=,
21889 =lognotereschedule=, and =nologreschedule=.
21890
21891 [fn:69] Org does not repeat inactive timestamps, however. See
22472 [fn:25] Org does not repeat inactive timestamps, however. See
2189222473 [[*Timestamps]].
2189322474
21894 [fn:70] In fact, the target state is taken from, in this sequence, the
21895 =REPEAT_TO_STATE= property, the variable ~org-todo-repeat-to-state~ if
21896 it is a string, the previous TODO state if ~org-todo-repeat-to-state~
21897 is ~t~, or the first state of the TODO state sequence.
21898
21899 [fn:71] You can change this using the option ~org-log-repeat~, or the
22475 [fn:26] You can change this using the option ~org-log-repeat~, or the
2190022476 =STARTUP= options =logrepeat=, =lognoterepeat=, and =nologrepeat=.
2190122477 With =lognoterepeat=, you will also be prompted for a note.
2190222478
21903 [fn:72] Clocking only works if all headings are indented with less
22479 [fn:27] Clocking only works if all headings are indented with less
2190422480 than 30 stars. This is a hard-coded limitation of ~lmax~ in
2190522481 ~org-clock-sum~.
2190622482
21907 [fn:73] To resume the clock under the assumption that you have worked
21908 on this task while outside Emacs, use =(setq org-clock-persist t)=.
21909
21910 [fn:74] To add an effort estimate "on the fly", hook a function doing
21911 this to ~org-clock-in-prepare-hook~.
21912
21913 [fn:75] The last reset of the task is recorded by the =LAST_REPEAT=
21914 property.
21915
21916 [fn:76] See also the variable ~org-clock-mode-line-total~.
21917
21918 [fn:77] The corresponding in-buffer setting is: =#+STARTUP:
21919 lognoteclock-out=.
21920
21921 [fn:78] When using ~:step~, ~untilnow~ starts from the beginning of
21922 2003, not the beginning of time.
21923
21924 [fn:79] Language terms can be set through the variable
21925 ~org-clock-clocktable-language-setup~.
21926
21927 [fn:80] Note that all parameters must be specified in a single
21928 line---the line is broken here only to fit it into the manual.
21929
21930 [fn:81] On computers using macOS, idleness is based on actual user
22483 [fn:28] On computers using macOS, idleness is based on actual user
2193122484 idleness, not just Emacs' idle time. For X11, you can install a
2193222485 utility program =x11idle.c=, available in the =org-contrib/=
2193322486 repository, or install the xprintidle package and set it to the
2193522488 to get the same general treatment of idleness. On other systems, idle
2193622489 time refers to Emacs idle time only.
2193722490
21938 [fn:82] Please note the pitfalls of summing hierarchical data in
21939 a flat list (see [[*Using Column View in the Agenda]]).
21940
21941 [fn:83] Note the corresponding =STARTUP= options =logrefile=,
21942 =lognoterefile=, and =nologrefile=.
21943
21944 [fn:84] Org used to offer four different targets for date/week tree
22491 [fn:29] Org used to offer four different targets for date/week tree
2194522492 capture. Now, Org automatically translates these to use
2194622493 ~file+olp+datetree~, applying the ~:time-prompt~ and ~:tree-type~
2194722494 properties. Please rewrite your date/week-tree targets using
2194822495 ~file+olp+datetree~ since the older targets are now deprecated.
2194922496
21950 [fn:85] A date tree is an outline structure with years on the highest
22497 [fn:30] A date tree is an outline structure with years on the highest
2195122498 level, months or ISO weeks as sublevels and then dates on the lowest
21952 level. Tags are allowed in the tree structure.
21953
21954 [fn:86] When the file name is not absolute, Org assumes it is relative
21955 to ~org-directory~.
21956
21957 [fn:87] If you need one of these sequences literally, escape the =%=
21958 with a backslash.
21959
21960 [fn:88] If you define your own link types (see [[*Adding Hyperlink
21961 Types]]), any property you store with ~org-store-link-props~ can be
21962 accessed in capture templates in a similar way.
21963
21964 [fn:89] This is always the other, not the user. See the variable
22499 level.
22500
22501 #+begin_example
22502 ,* 2022
22503 ,** 2022-10 October
22504 ,*** 2022-10-07 Friday
22505 ,*** 2022-10-08 Saturday
22506 #+end_example
22507
22508 Tags are allowed in the tree structure.
22509
22510 [fn:31] This is always the other, not the user. See the variable
2196522511 ~org-link-from-user-regexp~.
2196622512
21967 [fn:90] If you move entries or Org files from one directory to
21968 another, you may want to configure ~org-attach-id-dir~ to contain
21969 an absolute path.
21970
21971 [fn:91] If the value of that variable is not a list, but a single file
21972 name, then the list of agenda files in maintained in that external
21973 file.
21974
21975 [fn:92] When using the dispatcher, pressing {{{kbd(<)}}} before
21976 selecting a command actually limits the command to the current file,
21977 and ignores ~org-agenda-files~ until the next dispatcher command.
21978
21979 [fn:93] For backward compatibility, you can also press {{{kbd(1)}}} to
21980 restrict to the current buffer.
21981
21982 [fn:94] For backward compatibility, you can also press {{{kbd(0)}}} to
21983 restrict to the current region/subtree.
21984
21985 [fn:95] For backward compatibility, the universal prefix argument
22513 [fn:32] For backward compatibility, the universal prefix argument
2198622514 {{{kbd(C-u)}}} causes all TODO entries to be listed before the agenda.
2198722515 This feature is deprecated, use the dedicated TODO list, or a block
2198822516 agenda instead (see [[*Block agenda]]).
2198922517
21990 [fn:96] The variable ~org-anniversary~ used in the example is just
21991 like ~diary-anniversary~, but the argument order is always according
21992 to ISO and therefore independent of the value of
21993 ~calendar-date-style~.
21994
21995 [fn:97] You can, however, disable this by setting
21996 ~org-agenda-search-headline-for-time~ variable to a ~nil~ value.
21997
21998 [fn:98] Custom agenda commands can preset a filter by binding one of
22518 [fn:33] Custom agenda commands can preset a filter by binding one of
2199922519 the variables ~org-agenda-tag-filter-preset~,
2200022520 ~org-agenda-category-filter-preset~, ~org-agenda-effort-filter-preset~
2200122521 or ~org-agenda-regexp-filter-preset~ as an option. This filter is
2200522525 only set this in the global options section, not in the section of an
2200622526 individual block.
2200722527
22008 [fn:99] Only tags filtering is respected here, effort filtering is
22009 ignored.
22010
22011 [fn:100] You can also create persistent custom functions through
22012 ~org-agenda-bulk-custom-functions~.
22013
22014 [fn:101] This file is parsed for the agenda when
22015 ~org-agenda-include-diary~ is set.
22016
22017 [fn:102] You can provide a description for a prefix key by inserting
22018 a cons cell with the prefix and the description.
22019
22020 [fn:103] /Planned/ means here that these entries have some planning
22528 [fn:34] /Planned/ means here that these entries have some planning
2202122529 information attached to them, like a time-stamp, a scheduled or
2202222530 a deadline string. See ~org-agenda-entry-types~ on how to set what
2202322531 planning information is taken into account.
2202422532
22025 [fn:104] For HTML you need to install Hrvoje Nikšić's =htmlize.el=
22026 as an Emacs package from MELPA or from [[https://github.com/hniksic/emacs-htmlize][Hrvoje Nikšić's repository]].
22027
22028 [fn:105] To create PDF output, the Ghostscript ps2pdf utility must be
22533 [fn:35] To create PDF output, the Ghostscript ps2pdf utility must be
2202922534 installed on the system. Selecting a PDF file also creates the
2203022535 postscript file.
2203122536
22032 [fn:106] If you want to store standard views like the weekly agenda or
22033 the global TODO list as well, you need to define custom commands for
22034 them in order to be able to specify file names.
22035
22036 [fn:107] Quoting depends on the system you use, please check the FAQ
22037 for examples.
22038
22039 [fn:108] You can turn this on by default by setting the variable
22040 ~org-pretty-entities~, or on a per-file base with the =STARTUP= option
22041 =entitiespretty=.
22042
22043 [fn:109] This behavior can be disabled with =-= export setting (see
22044 [[*Export Settings]]).
22045
22046 [fn:110] LaTeX is a macro system based on Donald\nbsp{}E.\nbsp{}Knuth's TeX
22537 [fn:36] LaTeX is a macro system based on Donald\nbsp{}E.\nbsp{}Knuth's TeX
2204722538 system. Many of the features described here as "LaTeX" are really
2204822539 from TeX, but for simplicity I am blurring this distinction.
2204922540
22050 [fn:111] When MathJax is used, only the environments recognized by
22541 [fn:37] When MathJax is used, only the environments recognized by
2205122542 MathJax are processed. When dvipng, dvisvgm, or ImageMagick suite is
2205222543 used to create images, any LaTeX environment is handled.
2205322544
22054 [fn:112] These are respectively available at
22055 [[http://sourceforge.net/projects/dvipng/]], [[http://dvisvgm.bplaced.net/]]
22545 [fn:38] These are respectively available at
22546 [[https://sourceforge.net/projects/dvipng/]], [[http://dvisvgm.bplaced.net/]]
2205622547 and from the ImageMagick suite. Choose the converter by setting the
2205722548 variable ~org-preview-latex-default-process~ accordingly.
2205822549
22059 [fn:113] Org mode has a method to test if point is inside such
22060 a fragment, see the documentation of the function
22061 ~org-inside-LaTeX-fragment-p~.
22062
22063 [fn:114] This works automatically for the HTML backend (it requires
22550 [fn:39] This works automatically for the HTML backend (it requires
2206422551 version 1.34 of the =htmlize.el= package, which you need to install).
2206522552 Fontified code chunks in LaTeX can be achieved using either the
22066 [[https://www.ctan.org/pkg/listings][listings]] package or the [[https://www.ctan.org/pkg/minted][minted]] package. Refer to
22067 ~org-latex-listings~ for details.
22068
22069 [fn:115] Source code in code blocks may also be evaluated either
22553 [[https://www.ctan.org/pkg/listings][listings]] LaTeX package, [[https://www.ctan.org/pkg/minted][minted]] LaTeX package, or by using
22554 [[https://elpa.gnu.org/packages/engrave-faces.html][engrave-faces]] . Refer to ~org-latex-src-block-backend~ for details.
22555
22556 [fn:40] Source code in code blocks may also be evaluated either
2207022557 interactively or on export. See [[*Working with Source Code]] for more
2207122558 information on evaluating code blocks.
2207222559
22073 [fn:116] Adding =-k= to =-n -r= /keeps/ the labels in the source code
22074 while using line numbers for the links, which might be useful to
22075 explain those in an Org mode example code.
22076
22077 [fn:117] You may select a different mode with the variable
22078 ~org-edit-fixed-width-region-mode~.
22079
22080 [fn:118] What Emacs considers to be an image depends on
22081 ~image-file-name-extensions~ and ~image-file-name-regexps~.
22082
22083 [fn:119] The variable ~org-startup-with-inline-images~ can be set
22084 within a buffer with the =STARTUP= options =inlineimages= and
22085 =noinlineimages=.
22086
22087 [fn:120] The corresponding in-buffer setting is: =#+STARTUP: fninline=
22088 or =#+STARTUP: nofninline=.
22089
22090 [fn:121] The corresponding in-buffer options are =#+STARTUP: fnadjust=
22091 and =#+STARTUP: nofnadjust=.
22092
22093 [fn:122] The variable ~org-export-date-timestamp-format~ defines how
22094 this timestamp are exported.
22095
22096 [fn:123] For export to LaTeX format---or LaTeX-related formats such as
22560 [fn:41] For export to LaTeX format---or LaTeX-related formats such as
2209722561 Beamer---, the =org-latex-package-alist= variable needs further
2209822562 configuration. See [[LaTeX specific export settings]].
2209922563
22100 [fn:124] At the moment, some export back-ends do not obey this
22564 [fn:42] At the moment, some export back-ends do not obey this
2210122565 specification. For example, LaTeX export excludes every unnumbered
2210222566 headline from the table of contents.
2210322567
22104 [fn:125] Note that ~org-link-search-must-match-exact-headline~ is
22568 [fn:43] Note that ~org-link-search-must-match-exact-headline~ is
2210522569 locally bound to non-~nil~. Therefore, ~org-link-search~ only matches
2210622570 headlines and named elements.
2210722571
22108 [fn:126] Since commas separate the arguments, commas within arguments
22572 [fn:44] Since commas separate the arguments, commas within arguments
2210922573 have to be escaped with the backslash character. So only those
2211022574 backslash characters before a comma need escaping with another
2211122575 backslash character.
2211222576
22113 [fn:127] For a less drastic behavior, consider using a select tag (see
22114 [[*Export Settings]]) instead.
22115
22116 [fn:128] If =BEAMER_ENV= is set, Org export adds =B_environment= tag
22577 [fn:45] If =BEAMER_ENV= is set, Org export adds =B_environment= tag
2211722578 to make it visible. The tag serves as a visual aid and has no
2211822579 semantic relevance.
2211922580
22120 [fn:129] By default Org loads MathJax from [[https://cdnjs.com][cdnjs.com]] as recommended by
22121 [[https://www.mathjax.org][MathJax]].
22122
22123 [fn:130] Please note that exported formulas are part of an HTML
22581 [fn:46] Please note that exported formulas are part of an HTML
2212422582 document, and that signs such as =<=, =>=, or =&= have special
22125 meanings. See [[http://docs.mathjax.org/en/latest/tex.html#tex-and-latex-in-html-documents][MathJax TeX and LaTeX support]].
22126
22127 [fn:131] See [[http://docs.mathjax.org/en/latest/tex.html#tex-extensions][TeX and LaTeX extensions]] in the [[http://docs.mathjax.org][MathJax manual]] to learn
22128 about extensions.
22129
22130 [fn:132] If the classes on TODO keywords and tags lead to conflicts,
22131 use the variables ~org-html-todo-kwd-class-prefix~ and
22132 ~org-html-tag-class-prefix~ to make them unique.
22133
22134 [fn:133] This does not allow setting different bibliography compilers
22583 meanings. See [[https://docs.mathjax.org/en/latest/input/tex/html.html#tex-and-latex-in-html-documents][MathJax TeX and LaTeX in HTML documents]].
22584
22585 [fn:47] This does not allow setting different bibliography compilers
2213522586 for different files. However, "smart" LaTeX compilation systems, such
2213622587 as latexmk, can select the correct bibliography compiler.
2213722588
22138 [fn:134] Minted uses an external Python package for code highlighting,
22139 which requires the flag =-shell-escape= to be added to
22140 ~org-latex-pdf-process~.
22141
22142 [fn:135] See [[http://docs.oasis-open.org/office/v1.2/OpenDocument-v1.2.html][Open Document Format for Office Applications
22143 (OpenDocument) Version 1.2]].
22144
22145 [fn:136] See [[http://www.mathtoweb.com/cgi-bin/mathtoweb_home.pl][MathToWeb]].
22146
22147 [fn:137] See [[http://dlmf.nist.gov/LaTeXML/]].
22148
22149 [fn:138] [[http://docs.oasis-open.org/office/v1.2/OpenDocument-v1.2.html][OpenDocument-v1.2 Specification]]
22150
22151 [fn:139] See the =<table:table-template>= element of the
22152 OpenDocument-v1.2 specification.
22153
22154 [fn:140] See the attributes =table:template-name=,
22155 =table:use-first-row-styles=, =table:use-last-row-styles=,
22156 =table:use-first-column-styles=, =table:use-last-column-styles=,
22157 =table:use-banding-rows-styles=, and =table:use-banding-column-styles=
22158 of the =<table:table>= element in the OpenDocument-v1.2 specification.
22159
22160 [fn:141] If the publishing directory is the same as the source
22161 directory, =file.org= is exported as =file.org.org=, so you probably
22162 do not want to do this.
22163
22164 [fn:142] The option ~org-babel-no-eval-on-ctrl-c-ctrl-c~ can be used
22165 to remove code evaluation from the {{{kbd(C-c C-c)}}} key binding.
22166
22167 [fn:143] Actually, the constructs =call_<name>()= and =src_<lang>{}=
22589 [fn:48] Actually, the constructs =call_<name>()= and =src_<lang>{}=
2216822590 are not evaluated when they appear in a keyword (see [[*Summary of
2216922591 In-Buffer Settings]]).
2217022592
22171 [fn:144] For noweb literate programming details, see
22172 http://www.cs.tufts.edu/~nr/noweb/.
22173
22174 [fn:145] For more information, please refer to the commentary section
22175 in =org-tempo.el=.
22176
22177 [fn:146] Org Indent mode also sets ~wrap-prefix~ correctly for
22593 [fn:49] Org Indent mode also sets ~wrap-prefix~ correctly for
2217822594 indenting and wrapping long lines of headlines or text. This minor
2217922595 mode also handles Visual Line mode and directly applied settings
2218022596 through ~word-wrap~.
2218122597
22182 [fn:147] This works, but requires extra effort. Org Indent mode is
22598 [fn:50] This works, but requires extra effort. Org Indent mode is
2218322599 more convenient for most applications.
2218422600
22185 [fn:148] ~org-adapt-indentation~ can also be set to ='headline-data=,
22186 in which case only data lines below the headline will be indented.
22187
22188 [fn:149] Note that Org Indent mode also sets the ~wrap-prefix~
22189 property, such that Visual Line mode (or purely setting ~word-wrap~)
22190 wraps long lines, including headlines, correctly indented.
22191
22192 [fn:150] For a server to host files, consider using a WebDAV server,
22601 [fn:51] For a server to host files, consider using a WebDAV server,
2219322602 such as [[https://nextcloud.com][Nextcloud]]. Additional help is at this [[https://orgmode.org/worg/org-faq.html#mobileorg_webdav][FAQ entry]].
2219422603
22195 [fn:151] If Emacs is configured for safe storing of passwords, then
22196 configure the variable ~org-mobile-encryption-password~; please read
22197 the docstring of that variable.
22198
22199 [fn:152] Symbolic links in ~org-directory~ need to have the same name
22200 as their targets.
22201
22202 [fn:153] While creating the agendas, Org mode forces =ID= properties
22604 [fn:52] While creating the agendas, Org mode forces =ID= properties
2220322605 on all referenced entries, so that these entries can be uniquely
2220422606 identified if Org Mobile flags them for further action. To avoid
2220522607 setting properties configure the variable
2220622608 ~org-mobile-force-id-on-agenda-items~ to ~nil~. Org mode then relies
2220722609 on outline paths, assuming they are unique.
2220822610
22209 [fn:154] Checksums are stored automatically in the file
22210 =checksums.dat=.
22211
22212 [fn:155] The file will be empty after this operation.
22213
22214 [fn:156] https://www.ctan.org/pkg/comment
22215
22216 [fn:157] By default this works only for LaTeX, HTML, and Texinfo.
22611 [fn:53] By default this works only for LaTeX, HTML, and Texinfo.
2221722612 Configure the variable ~orgtbl-radio-table-templates~ to install
2221822613 templates for other modes.
2221922614
22220 [fn:158] If the =TBLFM= keyword contains an odd number of dollar
22615 [fn:54] If the =TBLFM= keyword contains an odd number of dollar
2222122616 characters, this may cause problems with Font Lock in LaTeX mode. As
2222222617 shown in the example you can fix this by adding an extra line inside
2222322618 the =comment= environment that is used to balance the dollar
2222422619 expressions. If you are using AUCTeX with the font-latex library,
2222522620 a much better solution is to add the =comment= environment to the
2222622621 variable ~LaTeX-verbatim-environments~.
22227
22228 [fn:159] The ~agenda*~ view is the same as ~agenda~ except that it
22229 only considers /appointments/, i.e., scheduled and deadline items that
22230 have a time specification =[h]h:mm= in their time-stamps.
22231
22232 [fn:160] Note that, for ~org-odd-levels-only~, a level number
22233 corresponds to order in the hierarchy, not to the number of stars.
1414 \pdflayout=(0l)
1515
1616 % Nothing else needs to be changed below this line.
17 % Copyright (C) 1987, 1993, 1996--1997, 2001--2021 Free Software
17 % Copyright (C) 1987, 1993, 1996--1997, 2001--2023 Free Software
1818 % Foundation, Inc.
1919
2020 % This document is free software: you can redistribute it and/or modify
323323 \key{archive subtree using the default command}{C-c C-x C-a}
324324 \key{move subtree to archive file}{C-c C-x C-s}
325325 \key{toggle ARCHIVE tag / to ARCHIVE sibling}{C-c C-x a/A}
326 \key{force cycling of an ARCHIVEd tree}{C-TAB}
326 \key{force cycling of an ARCHIVEd tree}{C-c C-TAB}
327327
328328 \section{Filtering and Sparse Trees}
329329
00 ;;; ob-C.el --- Babel Functions for C and Similar Languages -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Thierry Banel
6 ;; Maintainer: Thierry Banel
6 ;; Maintainer: Thierry Banel <tbanelwebmin@free.fr>
77 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: https://orgmode.org
8 ;; URL: https://orgmode.org
99
1010 ;; This file is part of GNU Emacs.
1111
3131 ;; - not much in the way of error feedback
3232
3333 ;;; Code:
34
35 (require 'org-macs)
36 (org-assert-version)
3437
3538 (require 'cc-mode)
3639 (require 'ob)
181184 (setq results (org-remove-indentation results))
182185 (org-babel-reassemble-table
183186 (org-babel-result-cond (cdr (assq :result-params params))
184 (org-babel-read results t)
187 results
185188 (let ((tmp-file (org-babel-temp-file "c-")))
186189 (with-temp-file tmp-file (insert results))
187190 (org-babel-import-elisp-from-file tmp-file)))
335338 (type
336339 (pcase basetype
337340 (`integerp '("int" "%d"))
338 (`floatp '("double" "%f"))
341 (`floatp '("double" "%s")) ;; %f rounds, use %s to print the float literally
339342 (`stringp
340343 (list
341344 (if (eq org-babel-c-variant 'd) "string" "const char*")
00 ;;; ob-R.el --- Babel Functions for R -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Dan Davison
6 ;; Maintainer: Jeremie Juste
6 ;; Maintainer: Jeremie Juste <jeremiejuste@gmail.com>
77 ;; Keywords: literate programming, reproducible research, R, statistics
8 ;; Homepage: https://orgmode.org
8 ;; URL: https://orgmode.org
99
1010 ;; This file is part of GNU Emacs.
1111
2828
2929 ;;; Code:
3030
31 (require 'org-macs)
32 (org-assert-version)
33
3134 (require 'cl-lib)
3235 (require 'ob)
3336
3437 (declare-function orgtbl-to-tsv "org-table" (table params))
35 (declare-function R "ext:essd-r" (&optional start-args))
38 (declare-function run-ess-r "ext:ess-r-mode" (&optional start-args))
3639 (declare-function inferior-ess-send-input "ext:ess-inf" ())
3740 (declare-function ess-make-buffer-current "ext:ess-inf" ())
3841 (declare-function ess-eval-buffer "ext:ess-inf" (vis))
3942 (declare-function ess-wait-for-process "ext:ess-inf"
4043 (&optional proc sec-prompt wait force-redisplay))
41
42 ;; FIXME: Temporary declaration to silence the byte-compiler
43 (defvar user-inject-src-param)
44 (defvar ess-eval-visibly-tmp)
45 (defvar ess-eval-visibly)
46 (defvar ess-inject-source)
47 (defvar user-inject-src-param)
4844
4945 (defconst org-babel-header-args:R
5046 '((width . :any)
244240 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
245241 "Construct R code assigning the elisp VALUE to a variable named NAME."
246242 (if (listp value)
247 (let* ((lengths (mapcar 'length (cl-remove-if-not 'sequencep value)))
243 (let* ((lengths (mapcar 'length (cl-remove-if-not 'listp value)))
248244 (max (if lengths (apply 'max lengths) 0))
249245 (min (if lengths (apply 'min lengths) 0)))
250246 ;; Ensure VALUE has an orgtbl structure (depth of at least 2).
251 (unless (listp (car value)) (setq value (list value)))
247 (unless (listp (car value)) (setq value (mapcar 'list value)))
252248 (let ((file (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
253249 (header (if (or (eq (nth 1 value) 'hline) colnames-p)
254250 "TRUE" "FALSE"))
279275 (when (get-buffer session)
280276 ;; Session buffer exists, but with dead process
281277 (set-buffer session))
282 (require 'ess) (R)
278 (require 'ess-r-mode)
279 (set-buffer (run-ess-r))
283280 (let ((R-proc (get-process (or ess-local-process-name
284281 ess-current-process-name))))
285282 (while (process-get R-proc 'callbacks)
384381 (if session
385382 (if async
386383 (ob-session-async-org-babel-R-evaluate-session
387 session body result-type result-params column-names-p row-names-p)
384 session body result-type column-names-p row-names-p)
388385 (org-babel-R-evaluate-session
389386 session body result-type result-params column-names-p row-names-p))
390387 (org-babel-R-evaluate-external-process
485482 (defconst ob-session-async-R-indicator "'ob_comint_async_R_%s_%s'")
486483
487484 (defun ob-session-async-org-babel-R-evaluate-session
488 (session body result-type _ column-names-p row-names-p)
485 (session body result-type column-names-p row-names-p)
489486 "Asynchronously evaluate BODY in SESSION.
490487 Returns a placeholder string for insertion, to later be replaced
491488 by `org-babel-comint-async-filter'."
524521 (output
525522 (let ((uuid (md5 (number-to-string (random 100000000))))
526523 (ess-local-process-name
527 (process-name (get-buffer-process session))))
524 (process-name (get-buffer-process session)))
525 (ess-eval-visibly-p nil))
528526 (with-temp-buffer
529527 (insert (format ob-session-async-R-indicator
530528 "start" uuid))
533531 (insert "\n")
534532 (insert (format ob-session-async-R-indicator
535533 "end" uuid))
536 (setq ess-eval-visibly-tmp ess-eval-visibly)
537 (setq user-inject-src-param ess-inject-source)
538 (setq ess-eval-visibly nil)
539 (setq ess-inject-source 'function-and-buffer)
540 (ess-eval-buffer nil))
541 (setq ess-eval-visibly ess-eval-visibly-tmp)
542 (setq ess-inject-source user-inject-src-param)
534 (ess-eval-buffer nil ))
543535 uuid))))
544536
545537 (defun ob-session-async-R-value-callback (params tmp-file)
546538 "Callback for async value results.
547 Assigned locally to `ob-session-async-file-callback' in R
539 Assigned locally to `org-babel-comint-async-file-callback' in R
548540 comint buffers used for asynchronous Babel evaluation."
549541 (let* ((graphics-file (and (member "graphics" (assq :result-params params))
550542 (org-babel-graphical-output-file params)))
00 ;;; ob-awk.el --- Babel Functions for Awk -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2011-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2011-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Maintainer: Tyler Smith <tyler@plantarum.ca>
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
3131 ;; which will be passed to the awk process through STDIN
3232
3333 ;;; Code:
34
35 (require 'org-macs)
36 (org-assert-version)
37
3438 (require 'ob)
3539 (require 'org-compat)
3640
5054 (defun org-babel-execute:awk (body params)
5155 "Execute a block of Awk code with org-babel.
5256 This function is called by `org-babel-execute-src-block'."
53 (message "executing Awk source code block")
57 (message "Executing Awk source code block")
5458 (let* ((result-params (cdr (assq :result-params params)))
5559 (cmd-line (cdr (assq :cmd-line params)))
5660 (in-file (cdr (assq :in-file params)))
00 ;;; ob-calc.el --- Babel Functions for Calc -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Maintainer: Tom Gillespie <tgbugs@gmail.com>
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
2626 ;; Org-Babel support for evaluating calc code
2727
2828 ;;; Code:
29
30 (require 'org-macs)
31 (org-assert-version)
32
2933 (require 'ob)
3034 (require 'org-macs)
3135 (require 'calc)
00 ;;; ob-clojure.el --- Babel Functions for Clojure -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Joel Boehland, Eric Schulte, Oleh Krehel, Frederick Giasson
5 ;; Maintainer: Bastien Guerry <bzg@gnu.org>
5 ;; Maintainer: Daniel Kraus <daniel@kraus.my>
66 ;;
77 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: https://orgmode.org
8 ;; URL: https://orgmode.org
99
1010 ;; This file is part of GNU Emacs.
1111
2424
2525 ;;; Commentary:
2626
27 ;; Support for evaluating clojure code
27 ;; Support for evaluating Clojure code
2828
2929 ;; Requirements:
3030
31 ;; - clojure (at least 1.2.0)
31 ;; - Clojure (at least 1.2.0)
3232 ;; - clojure-mode
33 ;; - inf-clojure, cider or SLIME
33 ;; - inf-clojure, Cider, SLIME, babashka or nbb
3434
3535 ;; For clojure-mode, see https://github.com/clojure-emacs/clojure-mode
36 ;; For cider, see https://github.com/clojure-emacs/cider
37 ;; For inf-clojure, see https://github.com/clojure-emacs/cider
38
39 ;; For SLIME, the best way to install these components is by following
36 ;; For inf-clojure, see https://github.com/clojure-emacs/inf-clojure
37 ;; For Cider, see https://github.com/clojure-emacs/cider
38 ;; For SLIME, see https://slime.common-lisp.dev
39 ;; For babashka, see https://github.com/babashka/babashka
40 ;; For nbb, see https://github.com/babashka/nbb
41
42 ;; For SLIME, the best way to install its components is by following
4043 ;; the directions as set out by Phil Hagelberg (Technomancy) on the
4144 ;; web page: https://technomancy.us/126
4245
4346 ;;; Code:
47
48 (require 'org-macs)
49 (org-assert-version)
50
4451 (require 'ob)
4552
4653 (declare-function cider-current-connection "ext:cider-client" (&optional type))
6168 (add-to-list 'org-babel-tangle-lang-exts '("clojurescript" . "cljs"))
6269
6370 (defvar org-babel-default-header-args:clojure '())
64 (defvar org-babel-header-args:clojure '((ns . :any) (package . :any)))
71 (defvar org-babel-header-args:clojure
72 '((ns . :any)
73 (package . :any)
74 (backend . ((inf-clojure cider slime babashka nbb)))))
6575 (defvar org-babel-default-header-args:clojurescript '())
6676 (defvar org-babel-header-args:clojurescript '((package . :any)))
6777
68 (defcustom org-babel-clojure-backend nil
78 (defcustom org-babel-clojure-backend (cond
79 ((executable-find "bb") 'babashka)
80 ((executable-find "nbb") 'nbb)
81 ((featurep 'cider) 'cider)
82 ((featurep 'inf-clojure) 'inf-clojure)
83 ((featurep 'slime) 'slime)
84 (t nil))
6985 "Backend used to evaluate Clojure code blocks."
7086 :group 'org-babel
87 :package-version '(Org . "9.6")
7188 :type '(choice
7289 (const :tag "inf-clojure" inf-clojure)
7390 (const :tag "cider" cider)
7491 (const :tag "slime" slime)
92 (const :tag "babashka" babashka)
93 (const :tag "nbb" nbb)
7594 (const :tag "Not configured yet" nil)))
7695
7796 (defcustom org-babel-clojure-default-ns "user"
7998 :type 'string
8099 :group 'org-babel)
81100
101 (defcustom ob-clojure-babashka-command (executable-find "bb")
102 "Path to the babashka executable."
103 :type '(choice file (const nil))
104 :group 'org-babel
105 :package-version '(Org . "9.6"))
106
107 (defcustom ob-clojure-nbb-command (executable-find "nbb")
108 "Path to the nbb executable."
109 :type '(choice file (const nil))
110 :group 'org-babel
111 :package-version '(Org . "9.6"))
112
82113 (defun org-babel-expand-body:clojure (body params)
83114 "Expand BODY according to PARAMS, return the expanded body."
84115 (let* ((vars (org-babel--get-vars params))
116 (backend-override (cdr (assq :backend params)))
117 (org-babel-clojure-backend
118 (cond
119 (backend-override (intern backend-override))
120 (org-babel-clojure-backend org-babel-clojure-backend)
121 (t (user-error "You need to customize `org-babel-clojure-backend'
122 or set the `:backend' header argument"))))
85123 (ns (or (cdr (assq :ns params))
86124 (if (eq org-babel-clojure-backend 'cider)
87125 (or cider-buffer-ns
103141 (format "(let [%s]\n%s)"
104142 (mapconcat
105143 (lambda (var)
106 (format "%S %S" (car var) (cdr var)))
144 (format "%S '%S" (car var) (cdr var)))
107145 vars
108146 "\n ")
109147 body))))))
209247 "value")))
210248 result0)))
211249 (ob-clojure-string-or-list
250 ;; Filter out s-expressions that return nil (string "nil"
251 ;; from nrepl eval) or comment forms (actual nil from nrepl)
212252 (reverse (delete "" (mapcar (lambda (r)
213 (replace-regexp-in-string "nil" "" r))
253 (replace-regexp-in-string "nil" "" (or r "")))
214254 result0)))))))
215255
216256 (defun ob-clojure-eval-with-slime (expanded params)
224264 ,(buffer-substring-no-properties (point-min) (point-max)))
225265 (cdr (assq :package params)))))
226266
267 (defun ob-clojure-eval-with-babashka (bb expanded)
268 "Evaluate EXPANDED code block using BB (babashka or nbb)."
269 (let ((script-file (org-babel-temp-file "clojure-bb-script-" ".clj")))
270 (with-temp-file script-file
271 (insert expanded))
272 (org-babel-eval
273 (format "%s %s" bb (org-babel-process-file-name script-file))
274 "")))
275
227276 (defun org-babel-execute:clojure (body params)
228 "Execute a block of Clojure code with Babel."
229 (unless org-babel-clojure-backend
230 (user-error "You need to customize org-babel-clojure-backend"))
231 (let* ((expanded (org-babel-expand-body:clojure body params))
232 (result-params (cdr (assq :result-params params)))
233 result)
234 (setq result
235 (cond
236 ((eq org-babel-clojure-backend 'inf-clojure)
237 (ob-clojure-eval-with-inf-clojure expanded params))
238 ((eq org-babel-clojure-backend 'cider)
239 (ob-clojure-eval-with-cider expanded params))
240 ((eq org-babel-clojure-backend 'slime)
241 (ob-clojure-eval-with-slime expanded params))))
242 (org-babel-result-cond result-params
243 result
244 (condition-case nil (org-babel-script-escape result)
245 (error result)))))
277 "Execute the BODY block of Clojure code with PARAMS using Babel."
278 (let* ((backend-override (cdr (assq :backend params)))
279 (org-babel-clojure-backend
280 (cond
281 (backend-override (intern backend-override))
282 (org-babel-clojure-backend org-babel-clojure-backend)
283 (t (user-error "You need to customize `org-babel-clojure-backend'
284 or set the `:backend' header argument")))))
285 (let* ((expanded (org-babel-expand-body:clojure body params))
286 (result-params (cdr (assq :result-params params)))
287 result)
288 (setq result
289 (cond
290 ((eq org-babel-clojure-backend 'inf-clojure)
291 (ob-clojure-eval-with-inf-clojure expanded params))
292 ((eq org-babel-clojure-backend 'babashka)
293 (ob-clojure-eval-with-babashka ob-clojure-babashka-command expanded))
294 ((eq org-babel-clojure-backend 'nbb)
295 (ob-clojure-eval-with-babashka ob-clojure-nbb-command expanded))
296 ((eq org-babel-clojure-backend 'cider)
297 (ob-clojure-eval-with-cider expanded params))
298 ((eq org-babel-clojure-backend 'slime)
299 (ob-clojure-eval-with-slime expanded params))))
300 (org-babel-result-cond result-params
301 result
302 (condition-case nil (org-babel-script-escape result)
303 (error result))))))
246304
247305 (defun org-babel-execute:clojurescript (body params)
248306 "Evaluate BODY with PARAMS as ClojureScript code."
00 ;;; ob-comint.el --- Babel Functions for Interaction with Comint Buffers -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research, comint
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2929 ;; org-babel at large.
3030
3131 ;;; Code:
32
33 (require 'org-macs)
34 (org-assert-version)
35
3236 (require 'ob-core)
3337 (require 'org-compat)
3438 (require 'comint)
6973 (let ((buffer (nth 0 meta))
7074 (eoe-indicator (nth 1 meta))
7175 (remove-echo (nth 2 meta))
72 (full-body (nth 3 meta)))
76 (full-body (nth 3 meta))
77 (org-babel-comint-prompt-separator
78 "org-babel-comint-prompt-separator"))
7379 `(org-babel-comint-in-buffer ,buffer
7480 (let* ((string-buffer "")
7581 (comint-output-filter-functions
76 (cons (lambda (text) (setq string-buffer (concat string-buffer text)))
82 (cons (lambda (text)
83 (setq string-buffer (concat string-buffer text)))
7784 comint-output-filter-functions))
7885 dangling-text)
7986 ;; got located, and save dangling text
8895 (while (progn
8996 (goto-char comint-last-input-end)
9097 (not (save-excursion
91 (and (re-search-forward
92 (regexp-quote ,eoe-indicator) nil t)
93 (re-search-forward
94 comint-prompt-regexp nil t)))))
98 (and (re-search-forward
99 (regexp-quote ,eoe-indicator) nil t)
100 (re-search-forward
101 comint-prompt-regexp nil t)))))
95102 (accept-process-output (get-buffer-process (current-buffer))))
96103 ;; replace cut dangling text
97104 (goto-char (process-mark (get-buffer-process (current-buffer))))
98105 (insert dangling-text)
99106
107 ;; Filter out prompts.
108 (setq string-buffer
109 (replace-regexp-in-string
110 ;; Sometimes, we get multiple agglomerated
111 ;; prompts together in a single output:
112 ;; "prompt prompt prompt output"
113 ;; Remove them progressively, so that
114 ;; possible "^" in the prompt regexp gets to
115 ;; work as we remove the heading prompt
116 ;; instance.
117 (if (string-prefix-p "^" comint-prompt-regexp)
118 (format "^\\(%s\\)+" (substring comint-prompt-regexp 1))
119 comint-prompt-regexp)
120 ,org-babel-comint-prompt-separator
121 string-buffer))
100122 ;; remove echo'd FULL-BODY from input
101123 (when (and ,remove-echo ,full-body
102124 (string-match
104126 "\n" "[\r\n]+" (regexp-quote (or ,full-body "")))
105127 string-buffer))
106128 (setq string-buffer (substring string-buffer (match-end 0))))
107 (split-string string-buffer comint-prompt-regexp)))))
129 (delete "" (split-string
130 string-buffer
131 ,org-babel-comint-prompt-separator))))))
108132
109133 (defun org-babel-comint-input-command (buffer cmd)
110134 "Pass CMD to BUFFER.
123147 (while (progn
124148 (goto-char comint-last-input-end)
125149 (not (and (re-search-forward comint-prompt-regexp nil t)
126 (goto-char (match-beginning 0))
127 (string= (face-name (face-at-point))
128 "comint-highlight-prompt"))))
150 (goto-char (match-beginning 0)))))
129151 (accept-process-output (get-buffer-process buffer)))))
130152
131153 (defun org-babel-comint-eval-invisibly-and-wait-for-file
165187 (defvar-local org-babel-comint-async-chunk-callback nil
166188 "Callback function to clean Babel async output results before insertion.
167189 Its single argument is a string consisting of output from the
168 comint process. It should return a string that will be be passed
190 comint process. It should return a string that will be passed
169191 to `org-babel-insert-result'.")
170192
171193 (defvar-local org-babel-comint-async-dangling nil
00 ;;; ob-core.el --- Working with Code Blocks -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Eric Schulte
55 ;; Dan Davison
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
2222 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
2323
2424 ;;; Code:
25
26 (require 'org-macs)
27 (org-assert-version)
28
2529 (require 'cl-lib)
2630 (require 'ob-eval)
2731 (require 'org-macs)
32 (require 'org-fold)
2833 (require 'org-compat)
34 (require 'org-cycle)
2935
3036 (defconst org-babel-exeext
3137 (if (memq system-type '(windows-nt cygwin))
3945 (defvar org-src-preserve-indentation)
4046 (defvar org-babel-tangle-uncomment-comments)
4147
48 (declare-function org-attach-dir "org-attach" (&optional create-if-not-exists-p no-fs-check))
4249 (declare-function org-at-item-p "org-list" ())
4350 (declare-function org-at-table-p "org" (&optional table-type))
4451 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
4956 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
5057 (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
5158 (declare-function org-current-level "org" ())
52 (declare-function org-cycle "org" (&optional arg))
59 (declare-function org-cycle "org-cycle" (&optional arg))
5360 (declare-function org-edit-src-code "org-src" (&optional code edit-buffer-name))
5461 (declare-function org-edit-src-exit "org-src" ())
55 (declare-function org-element-at-point "org-element" ())
62 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
63 (declare-function org-element-at-point-no-context "org-element" (&optional pom))
5664 (declare-function org-element-context "org-element" (&optional element))
5765 (declare-function org-element-normalize-string "org-element" (s))
5866 (declare-function org-element-property "org-element" (property element))
6775 (declare-function org-list-struct "org-list" ())
6876 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
6977 (declare-function org-list-to-lisp "org-list" (&optional delete))
78 (declare-function org-list-to-org "org-list" (list &optional params))
7079 (declare-function org-macro-escape-arguments "org-macro" (&rest args))
7180 (declare-function org-mark-ring-push "org" (&optional pos buffer))
72 (declare-function org-narrow-to-subtree "org" ())
81 (declare-function org-narrow-to-subtree "org" (&optional element))
7382 (declare-function org-next-block "org" (arg &optional backward block-regexp))
7483 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
7584 (declare-function org-previous-block "org" (arg &optional block-regexp))
76 (declare-function org-show-context "org" (&optional key))
85 (declare-function org-fold-show-context "org-fold" (&optional key))
7786 (declare-function org-src-coderef-format "org-src" (&optional element))
7887 (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
7988 (declare-function org-src-get-lang-mode "org-src" (lang))
135144 :type 'string
136145 :safe (lambda (v)
137146 (and (stringp v)
138 (eq (compare-strings "RESULTS" nil nil v nil nil t)
139 t))))
147 (org-string-equal-ignore-case "RESULTS" v))))
140148
141149 (defcustom org-babel-noweb-wrap-start "<<"
142150 "String used to begin a noweb reference in a code block.
331339 This includes header arguments, language and name, and is largely
332340 a window into the `org-babel-get-src-block-info' function."
333341 (interactive)
334 (let ((info (org-babel-get-src-block-info 'light))
342 (let ((info (org-babel-get-src-block-info 'no-eval))
335343 (full (lambda (it) (> (length it) 0)))
336344 (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
337345 (when info
406414 (mkdirp . ((yes no)))
407415 (no-expand)
408416 (noeval)
409 (noweb . ((yes no tangle no-export strip-export)))
417 (noweb . ((yes no tangle strip-tangle no-export strip-export)))
410418 (noweb-ref . :any)
411419 (noweb-sep . :any)
420 (noweb-prefix . ((no yes)))
412421 (output-dir . :any)
413422 (padline . ((yes no)))
414423 (post . :any)
415424 (prologue . :any)
416425 (results . ((file list vector table scalar verbatim)
417426 (raw html latex org code pp drawer link graphics)
418 (replace silent none append prepend)
427 (replace silent none discard append prepend)
419428 (output value)))
420429 (rownames . ((no yes)))
421430 (sep . :any)
434443
435444 (defconst org-babel-safe-header-args
436445 '(:cache :colnames :comments :exports :epilogue :hlines :noeval
437 :noweb :noweb-ref :noweb-sep :padline :prologue :rownames
438 :sep :session :tangle :wrap
446 :noweb :noweb-ref :noweb-sep :noweb-prefix :padline
447 :prologue :rownames :sep :session :tangle :wrap
439448 (:eval . ("never" "query"))
440449 (:results . (lambda (str) (not (string-match "file" str)))))
441450 "A list of safe header arguments for babel source blocks.
476485 This is a list in which each element is an alist. Each key
477486 corresponds to a header argument, and each value to that header's
478487 value. The value can either be a string or a closure that
479 evaluates to a string. The closure is evaluated when the source
480 block is being evaluated (e.g. during execution or export), with
481 point at the source block. It is not possible to use an
482 arbitrary function symbol (e.g. 'some-func), since org uses
483 lexical binding. To achieve the same functionality, call the
484 function within a closure (e.g. (lambda () (some-func))).
488 evaluates to a string.
489
490 A closure is evaluated when the source block is being
491 evaluated (e.g. during execution or export), with point at the
492 source block. It is not possible to use an arbitrary function
493 symbol (e.g. `some-func'), since org uses lexical binding. To
494 achieve the same functionality, call the function within a
495 closure (e.g. (lambda () (some-func))).
485496
486497 To understand how closures can be used as default header
487498 arguments, imagine you'd like to set the file name output of a
488499 latex source block to a sha1 of its contents. We could achieve
489500 this with:
490501
491 (defun org-src-sha ()
492 (let ((elem (org-element-at-point)))
493 (concat (sha1 (org-element-property :value elem)) \".svg\")))
494
495 (setq org-babel-default-header-args:latex
496 `((:results . \"file link replace\")
497 (:file . (lambda () (org-src-sha)))))
502 (defun org-src-sha ()
503 (let ((elem (org-element-at-point)))
504 (concat (sha1 (org-element-property :value elem)) \".svg\")))
505
506 (setq org-babel-default-header-args:latex
507 `((:results . \"file link replace\")
508 (:file . (lambda () (org-src-sha)))))
498509
499510 Because the closure is evaluated with point at the source block,
500511 the call to `org-element-at-point' above will always retrieve
501 information about the current source block.")
512 information about the current source block.
513
514 Some header arguments can be provided multiple times for a source
515 block. An example of such a header argument is :var. This
516 functionality is also supported for default header arguments by
517 providing the header argument multiple times in the alist. For
518 example:
519
520 ((:var . \"foo=\\\"bar\\\"\")
521 (:var . \"bar=\\\"foo\\\"\"))")
502522
503523 (put 'org-babel-default-header-args 'safe-local-variable
504524 (org-babel-header-args-safe-fn org-babel-safe-header-args))
620640 (push elem lst)))
621641 (reverse lst)))
622642
623 (defun org-babel-get-src-block-info (&optional light datum)
643 (defun org-babel-get-src-block-info (&optional no-eval datum)
624644 "Extract information from a source block or inline source block.
625645
626 When optional argument LIGHT is non-nil, Babel does not resolve
646 When optional argument NO-EVAL is non-nil, Babel does not resolve
627647 remote variable references; a process which could likely result
628648 in the execution of other code blocks, and do not evaluate Lisp
629649 values in parameters.
657677 ;; properties applicable to its location within
658678 ;; the document.
659679 (org-with-point-at (org-element-property :begin datum)
660 (org-babel-params-from-properties lang light))
680 (org-babel-params-from-properties lang no-eval))
661681 (mapcar (lambda (h)
662 (org-babel-parse-header-arguments h light))
682 (org-babel-parse-header-arguments h no-eval))
663683 (cons (org-element-property :parameters datum)
664684 (org-element-property :header datum)))))
665685 (or (org-element-property :switches datum) "")
667687 (org-element-property (if inline :begin :post-affiliated)
668688 datum)
669689 (and (not inline) (org-src-coderef-format datum)))))
670 (unless light
690 (unless no-eval
671691 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
672692 (setf (nth 2 info) (org-babel-generate-file-param name (nth 2 info)))
673693 info))))
694714 ; and `org-babel-read'
695715
696716 ;;;###autoload
697 (defun org-babel-execute-src-block (&optional arg info params)
698 "Execute the current source code block.
717 (defun org-babel-execute-src-block (&optional arg info params executor-type)
718 "Execute the current source code block and return the result.
699719 Insert the results of execution into the buffer. Source code
700720 execution and the collection and formatting of results can be
701721 controlled through a variety of header arguments.
708728
709729 Optionally supply a value for PARAMS which will be merged with
710730 the header arguments specified at the front of the source code
711 block."
731 block.
732
733 EXECUTOR-TYPE is the type of the org element responsible for the
734 execution of the source block. If not provided then informed
735 guess will be made."
712736 (interactive)
713737 (let* ((org-babel-current-src-block-location
714 (or org-babel-current-src-block-location
715 (nth 5 info)
716 (org-babel-where-is-src-block-head)))
717 (info (if info (copy-tree info) (org-babel-get-src-block-info))))
738 (or org-babel-current-src-block-location
739 (nth 5 info)
740 (org-babel-where-is-src-block-head)))
741 (info (if info (copy-tree info) (org-babel-get-src-block-info)))
742 (executor-type
743 (or executor-type
744 ;; If `executor-type' is unset, then we will make an
745 ;; informed guess.
746 (pcase (and
747 ;; When executing virtual src block, no location
748 ;; is known.
749 org-babel-current-src-block-location
750 (char-after org-babel-current-src-block-location))
751 (?s 'inline-src-block)
752 (?c 'inline-babel-call)
753 (?# (pcase (char-after (+ 2 org-babel-current-src-block-location))
754 (?b 'src-block)
755 (?c 'call-block)
756 (_ 'unknown)))
757 (_ 'unknown)))))
718758 ;; Merge PARAMS with INFO before considering source block
719759 ;; evaluation since both could disagree.
720760 (cl-callf org-babel-merge-params (nth 2 info) params)
733773 (forward-line)
734774 (skip-chars-forward " \t")
735775 (let ((result (org-babel-read-result)))
736 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
776 (message (format "Cached: %s"
777 (replace-regexp-in-string "%" "%%" (format "%S" result))))
737778 result)))
738779 ((org-babel-confirm-evaluate info)
739780 (let* ((lang (nth 0 info))
751792 (make-directory d 'parents)
752793 d))))
753794 (cmd (intern (concat "org-babel-execute:" lang)))
754 result)
795 result exec-start-time)
755796 (unless (fboundp cmd)
756797 (error "No org-babel-execute function for %s!" lang))
757 (message "executing %s code block%s..."
798 (message "Executing %s %s %s..."
758799 (capitalize lang)
800 (pcase executor-type
801 ('src-block "code block")
802 ('inline-src-block "inline code block")
803 ('babel-call "call")
804 ('inline-babel-call "inline call")
805 (e (symbol-name e)))
759806 (let ((name (nth 4 info)))
760 (if name (format " (%s)" name) "")))
761 (if (member "none" result-params)
762 (progn (funcall cmd body params)
763 (message "result silenced"))
764 (setq result
765 (let ((r (funcall cmd body params)))
766 (if (and (eq (cdr (assq :result-type params)) 'value)
767 (or (member "vector" result-params)
768 (member "table" result-params))
769 (not (listp r)))
770 (list (list r))
771 r)))
772 (let ((file (and (member "file" result-params)
773 (cdr (assq :file params)))))
774 ;; If non-empty result and :file then write to :file.
775 (when file
776 ;; If `:results' are special types like `link' or
777 ;; `graphics', don't write result to `:file'. Only
778 ;; insert a link to `:file'.
779 (when (and result
780 (not (or (member "link" result-params)
781 (member "graphics" result-params))))
782 (with-temp-file file
783 (insert (org-babel-format-result
784 result
785 (cdr (assq :sep params)))))
786 ;; Set file permissions if header argument
787 ;; `:file-mode' is provided.
788 (when (assq :file-mode params)
789 (set-file-modes file (cdr (assq :file-mode params)))))
790 (setq result file))
791 ;; Possibly perform post process provided its
792 ;; appropriate. Dynamically bind "*this*" to the
793 ;; actual results of the block.
794 (let ((post (cdr (assq :post params))))
795 (when post
796 (let ((*this* (if (not file) result
797 (org-babel-result-to-file
798 file
799 (org-babel--file-desc params result)))))
800 (setq result (org-babel-ref-resolve post))
801 (when file
802 (setq result-params (remove "file" result-params))))))
803 (org-babel-insert-result
804 result result-params info new-hash lang)))
807 (if name
808 (format "(%s)" name)
809 (format "at position %S" (nth 5 info)))))
810 (setq exec-start-time (current-time)
811 result
812 (let ((r (save-current-buffer (funcall cmd body params))))
813 (if (and (eq (cdr (assq :result-type params)) 'value)
814 (or (member "vector" result-params)
815 (member "table" result-params))
816 (not (listp r)))
817 (list (list r))
818 r)))
819 (let ((file (and (member "file" result-params)
820 (cdr (assq :file params)))))
821 ;; If non-empty result and :file then write to :file.
822 (when file
823 ;; If `:results' are special types like `link' or
824 ;; `graphics', don't write result to `:file'. Only
825 ;; insert a link to `:file'.
826 (when (and result
827 (not (or (member "link" result-params)
828 (member "graphics" result-params))))
829 (with-temp-file file
830 (insert (org-babel-format-result
831 result
832 (cdr (assq :sep params)))))
833 ;; Set file permissions if header argument
834 ;; `:file-mode' is provided.
835 (when (assq :file-mode params)
836 (set-file-modes file (cdr (assq :file-mode params)))))
837 (setq result file))
838 ;; Possibly perform post process provided its
839 ;; appropriate. Dynamically bind "*this*" to the
840 ;; actual results of the block.
841 (let ((post (cdr (assq :post params))))
842 (when post
843 (let ((*this* (if (not file) result
844 (org-babel-result-to-file
845 file
846 (org-babel--file-desc params result)
847 'attachment))))
848 (setq result (org-babel-ref-resolve post))
849 (when file
850 (setq result-params (remove "file" result-params))))))
851 (if (member "none" result-params)
852 (message "result silenced")
853 (org-babel-insert-result
854 result result-params info new-hash lang
855 (time-subtract (current-time) exec-start-time))))
805856 (run-hooks 'org-babel-after-execute-hook)
806857 result)))))))
807858
886937 (defun org-babel-insert-header-arg (&optional header-arg value)
887938 "Insert a header argument selecting from lists of common args and values."
888939 (interactive)
889 (let* ((info (org-babel-get-src-block-info 'light))
940 (let* ((info (org-babel-get-src-block-info 'no-eval))
890941 (lang (car info))
891942 (begin (nth 5 info))
892943 (lang-headers (intern (concat "org-babel-header-args:" lang)))
917968 vals ""))))))
918969 (save-excursion
919970 (goto-char begin)
920 (goto-char (point-at-eol))
971 (goto-char (line-end-position))
921972 (unless (= (char-before (point)) ?\ ) (insert " "))
922973 (insert ":" header-arg) (when value (insert " " value)))))
923974
943994 (insert (concat header " " (or arg "")))
944995 (cons header arg)))
945996
946 (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
997 (add-hook 'org-cycle-tab-first-hook 'org-babel-header-arg-expand)
947998
948999 ;;;###autoload
9491000 (defun org-babel-load-in-session (&optional _arg info)
10831134 RE-RUN the source-code block is evaluated even if results already
10841135 exist."
10851136 (interactive "P")
1086 (pcase (org-babel-get-src-block-info 'light)
1137 (pcase (org-babel-get-src-block-info 'no-eval)
10871138 (`(,_ ,_ ,arguments ,_ ,_ ,start ,_)
10881139 (save-excursion
10891140 ;; Go to the results, if there aren't any then run the block.
12931344 (lambda (a b) (string< (car a) (car b)))))
12941345 (let* ((rm (lambda (lst)
12951346 (dolist (p '("replace" "silent" "none"
1296 "append" "prepend"))
1347 "discard" "append" "prepend"))
12971348 (setq lst (remove p lst)))
12981349 lst))
12991350 (norm (lambda (arg)
13011352 (copy-sequence (cdr arg))
13021353 (cdr arg))))
13031354 (when (and v (not (and (sequencep v)
1304 (not (consp v))
1305 (= (length v) 0))))
1355 (not (consp v))
1356 (= (length v) 0))))
13061357 (cond
13071358 ((and (listp v) ; lists are sorted
13081359 (member (car arg) '(:result-params)))
13301381 (mapconcat
13311382 #'identity
13321383 (delq nil (mapcar (lambda (arg)
1333 (let ((normalized (funcall norm arg)))
1334 (when normalized
1335 (format "%S" normalized))))
1336 (nth 2 info))) ":")
1384 (let ((normalized (funcall norm arg)))
1385 (when normalized
1386 (format "%S" normalized))))
1387 (nth 2 info))) ":")
13371388 expanded))
13381389 (hash (sha1 it)))
13391390 (when (called-interactively-p 'interactive) (message hash))
14671518 (push ov org-babel-hide-result-overlays)))))
14681519
14691520 ;; org-tab-after-check-for-cycling-hook
1470 (add-hook 'org-tab-first-hook #'org-babel-hide-result-toggle-maybe)
1521 (add-hook 'org-cycle-tab-first-hook #'org-babel-hide-result-toggle-maybe)
14711522 ;; Remove overlays when changing major mode
14721523 (add-hook 'org-mode-hook
14731524 (lambda () (add-hook 'change-major-mode-hook
16381689 (append
16391690 (split-string (if (stringp raw-result)
16401691 raw-result
1692 ;; FIXME: Arbitrary code evaluation.
16411693 (eval raw-result t)))
16421694 (cdr (assq :result-params params))))))
16431695 (append
17661818 Return the point at the beginning of the current source block.
17671819 Specifically at the beginning of the #+BEGIN_SRC line. Also set
17681820 match-data relatively to `org-babel-src-block-regexp', which see.
1769 If the point is not on a source block then return nil."
1821 If the point is not on a source block or within blank lines after an
1822 src block, then return nil."
17701823 (let ((element (or src-block (org-element-at-point))))
17711824 (when (eq (org-element-type element) 'src-block)
17721825 (let ((end (org-element-property :end element)))
18151868 (let ((point (org-babel-find-named-block name)))
18161869 (if point
18171870 ;; Taken from `org-open-at-point'.
1818 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1871 (progn (org-mark-ring-push) (goto-char point) (org-fold-show-context))
18191872 (message "source-code block `%s' not found in this buffer" name))))
18201873
18211874 (defun org-babel-find-named-block (name)
18551908 (let ((point (org-babel-find-named-result name)))
18561909 (if point
18571910 ;; taken from `org-open-at-point'
1858 (progn (goto-char point) (org-show-context))
1911 (progn (goto-char point) (org-fold-show-context))
18591912 (message "result `%s' not found in this buffer" name))))
18601913
18611914 (defun org-babel-find-named-result (name)
19181971 When called from inside of a code block the current block is
19191972 split. When called from outside of a code block a new code block
19201973 is created. In both cases if the region is demarcated and if the
1921 region is not active then the point is demarcated."
1974 region is not active then the point is demarcated.
1975
1976 When called within blank lines after a code block, create a new code
1977 block of the same language with the previous."
19221978 (interactive "P")
1923 (let* ((info (org-babel-get-src-block-info 'light))
1979 (let* ((info (org-babel-get-src-block-info 'no-eval))
19241980 (start (org-babel-where-is-src-block-head))
1981 ;; `start' will be nil when within space lines after src block.
19251982 (block (and start (match-string 0)))
19261983 (headers (and start (match-string 4)))
19271984 (stars (concat (make-string (or (org-current-level) 1) ?*) " "))
19281985 (upper-case-p (and block
19291986 (let (case-fold-search)
19301987 (string-match-p "#\\+BEGIN_SRC" block)))))
1931 (if info
1988 (if (and info start) ;; At src block, but not within blank lines after it.
19321989 (mapc
19331990 (lambda (place)
19341991 (save-excursion
19351992 (goto-char place)
19361993 (let ((lang (nth 0 info))
1937 (indent (make-string (current-indentation) ?\s)))
1994 (indent (make-string (org-current-text-indentation) ?\s)))
19381995 (when (string-match "^[[:space:]]*$"
1939 (buffer-substring (point-at-bol)
1940 (point-at-eol)))
1941 (delete-region (point-at-bol) (point-at-eol)))
1996 (buffer-substring (line-beginning-position)
1997 (line-end-position)))
1998 (delete-region (line-beginning-position) (line-end-position)))
19421999 (insert (concat
1943 (if (looking-at "^") "" "\n")
1944 indent (if upper-case-p "#+END_SRC\n" "#+end_src\n")
1945 (if arg stars indent) "\n"
1946 indent (if upper-case-p "#+BEGIN_SRC " "#+begin_src ")
1947 lang
1948 (if (> (length headers) 1)
2000 (if (looking-at "^") "" "\n")
2001 indent (if upper-case-p "#+END_SRC\n" "#+end_src\n")
2002 (if arg stars indent) "\n"
2003 indent (if upper-case-p "#+BEGIN_SRC " "#+begin_src ")
2004 lang
2005 (if (> (length headers) 1)
19492006 (concat " " headers) headers)
1950 (if (looking-at "[\n\r]")
2007 (if (looking-at "[\n\r]")
19512008 ""
19522009 (concat "\n" (make-string (current-column) ? )))))))
19532010 (move-end-of-line 2))
19542011 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
19552012 (let ((start (point))
1956 (lang (completing-read
1957 "Lang: "
1958 (mapcar #'symbol-name
1959 (delete-dups
1960 (append (mapcar #'car org-babel-load-languages)
1961 (mapcar (lambda (el) (intern (car el)))
1962 org-src-lang-modes))))))
2013 (lang (or (car info) ; Reuse language from previous block.
2014 (completing-read
2015 "Lang: "
2016 (mapcar #'symbol-name
2017 (delete-dups
2018 (append (mapcar #'car org-babel-load-languages)
2019 (mapcar (lambda (el) (intern (car el)))
2020 org-src-lang-modes)))))))
19632021 (body (delete-and-extract-region
19642022 (if (org-region-active-p) (mark) (point)) (point))))
19652023 (insert (concat (if (looking-at "^") "" "\n")
20542112 ((or `inline-babel-call `inline-src-block)
20552113 ;; Results for inline objects are located right after them.
20562114 ;; There is no RESULTS line to insert either.
2057 (let ((limit (org-element-property
2058 :contents-end (org-element-property :parent context))))
2115 (let ((limit (pcase (org-element-type (org-element-property :parent context))
2116 (`section (org-element-property
2117 :end (org-element-property :parent context)))
2118 (_ (org-element-property
2119 :contents-end (org-element-property :parent context))))))
20592120 (goto-char (org-element-property :end context))
20602121 (skip-chars-forward " \t\n" limit)
20612122 (throw :found
20882149 ;; No possible anonymous results at the very end of
20892150 ;; buffer or outside CONTEXT parent.
20902151 ((eq (point)
2091 (or (org-element-property
2092 :contents-end (org-element-property :parent context))
2152 (or (pcase (org-element-type (org-element-property :parent context))
2153 ((or `section `org-data) (org-element-property
2154 :end (org-element-property :parent context)))
2155 (_ (org-element-property
2156 :contents-end (org-element-property :parent context))))
20932157 (point-max))))
20942158 ;; Check if next element is an anonymous result below
20952159 ;; the current block.
21322196 (or (org-babel--string-to-number v) v)))
21332197 (`table (org-babel-read-table))
21342198 (`plain-list (org-babel-read-list))
2135 (`example-block
2199 ((or `example-block `src-block)
21362200 (let ((v (org-element-property :value element)))
21372201 (if (or org-src-preserve-indentation
21382202 (org-element-property :preserve-indent element))
21752239 (org-table-to-lisp)))
21762240
21772241 (defun org-babel-read-list ()
2178 "Read the list at point into emacs-lisp."
2179 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
2242 "Read the list at point into emacs-lisp.
2243
2244 Return the list of strings representing top level items:
2245
2246 (item1 item2 ...)
2247
2248 Only consider top level items. See Info node
2249 `(org)Environment of a Code Block'."
2250 (mapcar (lambda (el) (org-babel-read (car el) 'inhibit-lisp-eval))
21802251 (cdr (org-list-to-lisp))))
21812252
21822253 (defvar org-link-types-re)
22062277 ;; scalar result
22072278 (funcall echo-res result))))
22082279
2209 (defun org-babel-insert-result (result &optional result-params info hash lang)
2280 (defun org-babel-insert-result (result &optional result-params info hash lang exec-time)
22102281 "Insert RESULT into the current buffer.
22112282
22122283 By default RESULT is inserted after the end of the current source
22142285 wrapped inside a `results' macro and placed on the same line as
22152286 the inline source block. The macro is stripped upon export.
22162287 Multiline and non-scalar RESULTS from inline source blocks are
2217 not allowed. With optional argument RESULT-PARAMS controls
2288 not allowed. When EXEC-TIME is provided it may be included in a
2289 generated message. With optional argument RESULT-PARAMS controls
22182290 insertion of results in the Org mode file. RESULT-PARAMS can
22192291 take the following values:
22202292
22872359 (cond ((stringp result)
22882360 (setq result (org-no-properties result))
22892361 (when (member "file" result-params)
2290 (setq result (org-babel-result-to-file
2291 result
2292 (org-babel--file-desc (nth 2 info) result)))))
2362 (setq result
2363 (org-babel-result-to-file
2364 result
2365 (org-babel--file-desc (nth 2 info) result)
2366 'attachment))))
22932367 ((listp result))
22942368 (t (setq result (format "%S" result))))
2369
22952370 (if (and result-params (member "silent" result-params))
22962371 (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
22972372 result)
23022377 (when inline
23032378 (let ((warning
23042379 (or (and (member "table" result-params) "`:results table'")
2305 (and (listp result) "list result")
2306 (and (string-match-p "\n." result) "multiline result")
2380 (and result (listp result) "list result")
2381 (and result (string-match-p "\n." result) "multiline result")
23072382 (and (member "list" result-params) "`:results list'"))))
23082383 (when warning
23092384 (user-error "Inline error: %s cannot be used" warning))))
23502425 (delete-region (point) (org-babel-result-end)))
23512426 ((member "append" result-params)
23522427 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2353 ((member "prepend" result-params))) ; already there
2428 ;; ((member "prepend" result-params)) ; already there
2429 )
23542430 (setq results-switches
23552431 (if results-switches (concat " " results-switches) ""))
23562432 (let ((wrap
23852461 ((member "list" result-params)
23862462 (insert
23872463 (org-trim
2388 (org-list-to-generic
2464 (org-list-to-org
2465 ;; We arbitrarily choose to format non-strings
2466 ;; as %S.
23892467 (cons 'unordered
23902468 (mapcar
23912469 (lambda (e)
2392 (list (if (stringp e) e (format "%S" e))))
2470 (cond
2471 ((stringp e) (list e))
2472 ((listp e)
2473 (mapcar
2474 (lambda (x)
2475 (if (stringp x) x (format "%S" x)))
2476 e))
2477 (t (list (format "%S" e)))))
23932478 (if (listp result) result
23942479 (split-string result "\n" t))))
23952480 '(:splicep nil :istart "- " :iend "\n")))
24342519 ;; Escape contents from "export" wrap. Wrap
24352520 ;; inline results within an export snippet with
24362521 ;; appropriate value.
2437 ((eq t (compare-strings type nil nil "export" nil nil t))
2522 ((org-string-equal-ignore-case type "export")
24382523 (let ((backend (pcase split
24392524 (`(,_) "none")
24402525 (`(,_ ,b . ,_) b))))
24452530 backend) "@@)}}}")))
24462531 ;; Escape contents from "example" wrap. Mark
24472532 ;; inline results as verbatim.
2448 ((eq t (compare-strings type nil nil "example" nil nil t))
2533 ((org-string-equal-ignore-case type "example")
24492534 (funcall wrap
24502535 opening-line closing-line
24512536 nil nil
24522537 "{{{results(=" "=)}}}"))
24532538 ;; Escape contents from "src" wrap. Mark
24542539 ;; inline results as inline source code.
2455 ((eq t (compare-strings type nil nil "src" nil nil t))
2540 ((org-string-equal-ignore-case type "src")
24562541 (let ((inline-open
24572542 (pcase split
24582543 (`(,_)
25162601 (not (and (listp result)
25172602 (member "append" result-params))))
25182603 (indent-rigidly beg end indent))
2519 (if (null result)
2520 (if (member "value" result-params)
2521 (message "Code block returned no value.")
2522 (message "Code block produced no output."))
2523 (message "Code block evaluation complete.")))
2524 (set-marker end nil)
2604 (let ((time-info
2605 ;; Only show the time when something other than
2606 ;; 0s will be shown, i.e. check if the time is at
2607 ;; least half of the displayed precision.
2608 (if (and exec-time (> (float-time exec-time) 0.05))
2609 (format " (took %.1fs)" (float-time exec-time))
2610 "")))
2611 (if (null result)
2612 (if (member "value" result-params)
2613 (message "Code block returned no value%s." time-info)
2614 (message "Code block produced no output%s." time-info))
2615 (message "Code block evaluation complete%s." time-info))))
2616 (when end (set-marker end nil))
25252617 (when outside-scope (narrow-to-region visible-beg visible-end))
25262618 (set-marker visible-beg nil)
25272619 (set-marker visible-end nil)))))))
25942686 (line-beginning-position 2))
25952687 (point))))))
25962688
2597 (defun org-babel-result-to-file (result &optional description)
2689 (defun org-babel-result-to-file (result &optional description type)
25982690 "Convert RESULT into an Org link with optional DESCRIPTION.
25992691 If the `default-directory' is different from the containing
2600 file's directory then expand relative links."
2692 file's directory then expand relative links.
2693
2694 If the optional TYPE is passed as `attachment' and the path is a
2695 descendant of the DEFAULT-DIRECTORY, the generated link will be
2696 specified as an an \"attachment:\" style link."
26012697 (when (stringp result)
2602 (let ((same-directory?
2603 (and (buffer-file-name (buffer-base-buffer))
2604 (not (string= (expand-file-name default-directory)
2605 (expand-file-name
2606 (file-name-directory
2607 (buffer-file-name (buffer-base-buffer)))))))))
2608 (format "[[file:%s]%s]"
2609 (if (and default-directory
2610 (buffer-file-name (buffer-base-buffer)) same-directory?)
2611 (if (eq org-link-file-path-type 'adaptive)
2612 (file-relative-name
2613 (expand-file-name result default-directory)
2614 (file-name-directory
2615 (buffer-file-name (buffer-base-buffer))))
2616 (expand-file-name result default-directory))
2617 result)
2698 (let* ((result-file-name (expand-file-name result))
2699 (base-file-name (buffer-file-name (buffer-base-buffer)))
2700 (base-directory (and buffer-file-name
2701 (file-name-directory base-file-name)))
2702 (same-directory?
2703 (and base-file-name
2704 (not (string= (expand-file-name default-directory)
2705 (expand-file-name
2706 base-directory)))))
2707 (request-attachment (eq type 'attachment))
2708 (attach-dir (let* ((default-directory base-directory)
2709 (dir (org-attach-dir nil t)))
2710 (when dir
2711 (expand-file-name dir))))
2712 (in-attach-dir (and request-attachment
2713 attach-dir
2714 (string-prefix-p
2715 attach-dir
2716 result-file-name))))
2717 (format "[[%s:%s]%s]"
2718 (pcase type
2719 ((and 'attachment (guard in-attach-dir)) "attachment")
2720 (_ "file"))
2721 (if (and request-attachment in-attach-dir)
2722 (file-relative-name
2723 result-file-name
2724 (file-name-as-directory attach-dir))
2725 (if (and default-directory
2726 base-file-name same-directory?)
2727 (if (eq org-link-file-path-type 'adaptive)
2728 (file-relative-name
2729 result-file-name
2730 (file-name-directory
2731 base-file-name))
2732 result-file-name)
2733 result))
26182734 (if description (concat "[" description "]") "")))))
26192735
26202736 (defun org-babel-examplify-region (beg end &optional results-switches inline)
26532769 (unless (eq (org-element-type element) 'src-block)
26542770 (error "Not in a source block"))
26552771 (goto-char (org-babel-where-is-src-block-head element))
2656 (let* ((ind (current-indentation))
2772 (let* ((ind (org-current-text-indentation))
26572773 (body-start (line-beginning-position 2))
26582774 (body (org-element-normalize-string
26592775 (if (or org-src-preserve-indentation
27102826 (pcase pair
27112827 (`(:var . ,value)
27122828 (let ((name (cond
2829 ;; Default header arguments can accept lambda
2830 ;; functions. We uniquely identify the var
2831 ;; according to the full string contents of
2832 ;; the lambda function.
2833 ((functionp value) value)
27132834 ((listp value) (car value))
27142835 ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value)
27152836 (intern (match-string 1 value)))
27402861 (split-string
27412862 (cond ((stringp value) value)
27422863 ((functionp value) (funcall value))
2864 ;; FIXME: Arbitrary code evaluation.
27432865 (t (eval value t)))))))
27442866 (`(:exports . ,value)
27452867 (setq exports (funcall merge
27462868 exports-exclusive-groups
27472869 exports
2748 (split-string
2870 (split-string
27492871 (cond ((and value (functionp value)) (funcall value))
27502872 (value value)
27512873 (t ""))))))
2874 ((or '(:dir . attach) '(:dir . "'attach"))
2875 (unless (org-attach-dir nil t)
2876 (error "No attachment directory for element (add :ID: or :DIR: property)"))
2877 (setq params (append
2878 `((:dir . ,(org-attach-dir nil t))
2879 (:mkdirp . "yes"))
2880 (assq-delete-all :dir (assq-delete-all :mkdir params)))))
27522881 ;; Regular keywords: any value overwrites the previous one.
27532882 (_ (setq params (cons pair (assq-delete-all (car pair) params)))))))
27542883 ;; Handle `:var' and clear out colnames and rownames for replaced
27762905 "Check if PARAMS require expansion in CONTEXT.
27772906 CONTEXT may be one of :tangle, :export or :eval."
27782907 (let ((allowed-values (cl-case context
2779 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2780 (:eval '("yes" "no-export" "strip-export" "eval"))
2781 (:export '("yes")))))
2908 (:tangle '("yes" "tangle" "no-export" "strip-export" "strip-tangle"))
2909 (:eval '("yes" "no-export" "strip-export" "eval" "strip-tangle"))
2910 (:export '("yes" "strip-tangle")))))
27822911 (cl-some (lambda (v) (member v allowed-values))
27832912 (split-string (or (cdr (assq :noweb params)) "")))))
27842913
2914 (defvar org-babel-expand-noweb-references--cache nil
2915 "Noweb reference cache used during expansion.")
2916 (defvar org-babel-expand-noweb-references--cache-buffer nil
2917 "Cons (BUFFER . MODIFIED-TICK) for cached noweb references.
2918 See `org-babel-expand-noweb-references--cache'.")
27852919 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
27862920 "Expand Noweb references in the body of the current source code block.
27872921
28132947 these arguments are not evaluated in the current source-code
28142948 block but are passed literally to the \"example-block\"."
28152949 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2816 (info (or info (org-babel-get-src-block-info 'light)))
2950 (info (or info (org-babel-get-src-block-info 'no-eval)))
28172951 (lang (nth 0 info))
28182952 (body (nth 1 info))
28192953 (comment (string= "noweb" (cdr (assq :comments (nth 2 info)))))
2954 (noweb-prefix (let ((v (assq :noweb-prefix (nth 2 info))))
2955 (or (not v)
2956 (and (org-not-nil (cdr v))
2957 (not (equal (cdr v) "no"))))))
28202958 (noweb-re (format "\\(.*?\\)\\(%s\\)"
28212959 (with-current-buffer parent-buffer
2822 (org-babel-noweb-wrap))))
2823 (cache nil)
2824 (c-wrap
2825 (lambda (s)
2826 ;; Comment string S, according to LANG mode. Return new
2827 ;; string.
2828 (unless org-babel-tangle-uncomment-comments
2829 (with-temp-buffer
2830 (funcall (org-src-get-lang-mode lang))
2831 (comment-region (point)
2832 (progn (insert s) (point)))
2833 (org-trim (buffer-string))))))
2834 (expand-body
2835 (lambda (i)
2836 ;; Expand body of code represented by block info I.
2837 (let ((b (if (org-babel-noweb-p (nth 2 i) :eval)
2838 (org-babel-expand-noweb-references i)
2839 (nth 1 i))))
2840 (if (not comment) b
2841 (let ((cs (org-babel-tangle-comment-links i)))
2842 (concat (funcall c-wrap (car cs)) "\n"
2843 b "\n"
2844 (funcall c-wrap (cadr cs))))))))
2845 (expand-references
2846 (lambda (ref cache)
2847 (pcase (gethash ref cache)
2848 (`(,last . ,previous)
2849 ;; Ignore separator for last block.
2850 (let ((strings (list (funcall expand-body last))))
2851 (dolist (i previous)
2852 (let ((parameters (nth 2 i)))
2853 ;; Since we're operating in reverse order, first
2854 ;; push separator, then body.
2855 (push (or (cdr (assq :noweb-sep parameters)) "\n")
2856 strings)
2857 (push (funcall expand-body i) strings)))
2858 (mapconcat #'identity strings "")))
2859 ;; Raise an error about missing reference, or return the
2860 ;; empty string.
2861 ((guard (or org-babel-noweb-error-all-langs
2862 (member lang org-babel-noweb-error-langs)))
2863 (error "Cannot resolve %s (see `org-babel-noweb-error-langs')"
2864 (org-babel-noweb-wrap ref)))
2865 (_ "")))))
2866 (replace-regexp-in-string
2867 noweb-re
2868 (lambda (m)
2869 (with-current-buffer parent-buffer
2870 (save-match-data
2871 (let* ((prefix (match-string 1 m))
2872 (id (match-string 3 m))
2873 (evaluate (string-match-p "(.*)" id))
2874 (expansion
2875 (cond
2876 (evaluate
2877 ;; Evaluation can potentially modify the buffer
2878 ;; and invalidate the cache: reset it.
2879 (setq cache nil)
2880 (let ((raw (org-babel-ref-resolve id)))
2881 (if (stringp raw) raw (format "%S" raw))))
2882 ;; Return the contents of headlines literally.
2883 ((org-babel-ref-goto-headline-id id)
2884 (org-babel-ref-headline-body))
2885 ;; Look for a source block named SOURCE-NAME. If
2886 ;; found, assume it is unique; do not look after
2887 ;; `:noweb-ref' header argument.
2888 ((org-with-point-at 1
2889 (let ((r (org-babel-named-src-block-regexp-for-name id)))
2890 (and (re-search-forward r nil t)
2891 (not (org-in-commented-heading-p))
2892 (funcall expand-body
2893 (org-babel-get-src-block-info t))))))
2894 ;; Retrieve from the Library of Babel.
2895 ((nth 2 (assoc-string id org-babel-library-of-babel)))
2896 ;; All Noweb references were cached in a previous
2897 ;; run. Extract the information from the cache.
2898 ((hash-table-p cache)
2899 (funcall expand-references id cache))
2900 ;; Though luck. We go into the long process of
2901 ;; checking each source block and expand those
2902 ;; with a matching Noweb reference. Since we're
2903 ;; going to visit all source blocks in the
2904 ;; document, cache information about them as well.
2905 (t
2906 (setq cache (make-hash-table :test #'equal))
2907 (org-with-wide-buffer
2908 (org-babel-map-src-blocks nil
2909 (if (org-in-commented-heading-p)
2910 (org-forward-heading-same-level nil t)
2911 (let* ((info (org-babel-get-src-block-info t))
2912 (ref (cdr (assq :noweb-ref (nth 2 info)))))
2913 (push info (gethash ref cache))))))
2914 (funcall expand-references id cache)))))
2915 ;; Interpose PREFIX between every line.
2916 (mapconcat #'identity
2917 (split-string expansion "[\n\r]")
2918 (concat "\n" prefix))))))
2919 body t t 2)))
2960 (org-babel-noweb-wrap)))))
2961 (unless (equal (cons parent-buffer
2962 (with-current-buffer parent-buffer
2963 (buffer-chars-modified-tick)))
2964 org-babel-expand-noweb-references--cache-buffer)
2965 (setq org-babel-expand-noweb-references--cache nil
2966 org-babel-expand-noweb-references--cache-buffer
2967 (cons parent-buffer
2968 (with-current-buffer parent-buffer
2969 (buffer-chars-modified-tick)))))
2970 (cl-macrolet ((c-wrap
2971 (s)
2972 ;; Comment string S, according to LANG mode. Return new
2973 ;; string.
2974 `(unless org-babel-tangle-uncomment-comments
2975 (with-temp-buffer
2976 (funcall (org-src-get-lang-mode lang))
2977 (comment-region (point)
2978 (progn (insert ,s) (point)))
2979 (org-trim (buffer-string)))))
2980 (expand-body
2981 (i)
2982 ;; Expand body of code represented by block info I.
2983 `(let ((b (if (org-babel-noweb-p (nth 2 ,i) :eval)
2984 (org-babel-expand-noweb-references ,i)
2985 (nth 1 ,i))))
2986 (if (not comment) b
2987 (let ((cs (org-babel-tangle-comment-links ,i)))
2988 (concat (c-wrap (car cs)) "\n"
2989 b "\n"
2990 (c-wrap (cadr cs)))))))
2991 (expand-references
2992 (ref)
2993 `(pcase (gethash ,ref org-babel-expand-noweb-references--cache)
2994 (`(,last . ,previous)
2995 ;; Ignore separator for last block.
2996 (let ((strings (list (expand-body last))))
2997 (dolist (i previous)
2998 (let ((parameters (nth 2 i)))
2999 ;; Since we're operating in reverse order, first
3000 ;; push separator, then body.
3001 (push (or (cdr (assq :noweb-sep parameters)) "\n")
3002 strings)
3003 (push (expand-body i) strings)))
3004 (mapconcat #'identity strings "")))
3005 ;; Raise an error about missing reference, or return the
3006 ;; empty string.
3007 ((guard (or org-babel-noweb-error-all-langs
3008 (member lang org-babel-noweb-error-langs)))
3009 (error "Cannot resolve %s (see `org-babel-noweb-error-langs')"
3010 (org-babel-noweb-wrap ,ref)))
3011 (_ ""))))
3012 (replace-regexp-in-string
3013 noweb-re
3014 (lambda (m)
3015 (with-current-buffer parent-buffer
3016 (save-match-data
3017 (let* ((prefix (match-string 1 m))
3018 (id (match-string 3 m))
3019 (evaluate (string-match-p "(.*)" id))
3020 (expansion
3021 (cond
3022 (evaluate
3023 (prog1
3024 (let ((raw (org-babel-ref-resolve id)))
3025 (if (stringp raw) raw (format "%S" raw)))
3026 ;; Evaluation can potentially modify the buffer
3027 ;; and invalidate the cache: reset it.
3028 (unless (equal org-babel-expand-noweb-references--cache-buffer
3029 (cons parent-buffer
3030 (buffer-chars-modified-tick)))
3031 (setq org-babel-expand-noweb-references--cache nil
3032 org-babel-expand-noweb-references--cache-buffer
3033 (cons parent-buffer
3034 (with-current-buffer parent-buffer
3035 (buffer-chars-modified-tick)))))))
3036 ;; Already cached.
3037 ((and (hash-table-p org-babel-expand-noweb-references--cache)
3038 (gethash id org-babel-expand-noweb-references--cache))
3039 (expand-references id))
3040 ;; Return the contents of headlines literally.
3041 ((org-babel-ref-goto-headline-id id)
3042 (org-babel-ref-headline-body))
3043 ;; Look for a source block named SOURCE-NAME. If
3044 ;; found, assume it is unique; do not look after
3045 ;; `:noweb-ref' header argument.
3046 ((org-with-point-at 1
3047 (let ((r (org-babel-named-src-block-regexp-for-name id)))
3048 (and (re-search-forward r nil t)
3049 (not (org-in-commented-heading-p))
3050 (let ((info (org-babel-get-src-block-info t)))
3051 (unless (hash-table-p org-babel-expand-noweb-references--cache)
3052 (setq org-babel-expand-noweb-references--cache (make-hash-table :test #'equal)))
3053 (push info (gethash id org-babel-expand-noweb-references--cache))
3054 (expand-body info))))))
3055 ;; Retrieve from the Library of Babel.
3056 ((nth 2 (assoc-string id org-babel-library-of-babel)))
3057 ;; All Noweb references were cached in a previous
3058 ;; run. Yet, ID is not in cache (see the above
3059 ;; condition). Process missing reference in
3060 ;; `expand-references'.
3061 ((and (hash-table-p org-babel-expand-noweb-references--cache)
3062 (gethash 'buffer-processed org-babel-expand-noweb-references--cache))
3063 (expand-references id))
3064 ;; Though luck. We go into the long process of
3065 ;; checking each source block and expand those
3066 ;; with a matching Noweb reference. Since we're
3067 ;; going to visit all source blocks in the
3068 ;; document, cache information about them as well.
3069 (t
3070 (setq org-babel-expand-noweb-references--cache (make-hash-table :test #'equal))
3071 (org-with-wide-buffer
3072 (org-babel-map-src-blocks nil
3073 (if (org-in-commented-heading-p)
3074 (org-forward-heading-same-level nil t)
3075 (let* ((info (org-babel-get-src-block-info t))
3076 (ref (cdr (assq :noweb-ref (nth 2 info)))))
3077 (push info (gethash ref org-babel-expand-noweb-references--cache))))))
3078 (puthash 'buffer-processed t org-babel-expand-noweb-references--cache)
3079 (expand-references id)))))
3080 ;; Interpose PREFIX between every line.
3081 (if noweb-prefix
3082 (mapconcat #'identity
3083 (split-string expansion "[\n\r]")
3084 (concat "\n" prefix))
3085 expansion)))))
3086 body t t 2))))
29203087
29213088 (defun org-babel--script-escape-inner (str)
29223089 (let (in-single in-double backslash out)
29883155 (error "`org-babel-script-escape' expects a string"))
29893156 (let ((escaped
29903157 (cond
2991 ((and (> (length str) 2)
3158 ((and (>= (length str) 2)
29923159 (or (and (string-equal "[" (substring str 0 1))
29933160 (string-equal "]" (substring str -1)))
29943161 (and (string-equal "{" (substring str 0 1))
30233190 ((and (not inhibit-lisp-eval)
30243191 (or (memq (string-to-char cell) '(?\( ?' ?` ?\[))
30253192 (string= cell "*this*")))
3193 ;; FIXME: Arbitrary code evaluation.
30263194 (eval (read cell) t))
3027 ((eq (string-to-char cell) ?\") (read cell))
3195 ((save-match-data
3196 (and (string-match "^[[:space:]]*\"\\(.*\\)\"[[:space:]]*$" cell)
3197 (not (string-match "[^\\]\"" (match-string 1 cell)))))
3198 (read cell))
30283199 (t (org-no-properties cell))))
30293200
30303201 (defun org-babel--string-to-number (string)
30693240 (defun org-babel-string-read (cell)
30703241 "Strip nested \"s from around strings."
30713242 (org-babel-read (or (and (stringp cell)
3072 (string-match "\"\\(.+\\)\"" cell)
3243 (string-match "^[[:space:]]*\"\\(.+\\)\"[[:space:]]*$" cell)
30733244 (match-string 1 cell))
30743245 cell) t))
30753246
30933264 (let ((f (org-babel-local-file-name (expand-file-name name))))
30943265 (if no-quote-p f (shell-quote-argument f))))
30953266
3096 (defvar org-babel-temporary-directory)
3097 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
3098 (defvar org-babel-temporary-directory
3099 (or (and (boundp 'org-babel-temporary-directory)
3100 (file-exists-p org-babel-temporary-directory)
3101 org-babel-temporary-directory)
3102 (make-temp-file "babel-" t))
3103 "Directory to hold temporary files created to execute code blocks.
3267 (defvar org-babel-temporary-directory
3268 (unless noninteractive
3269 (make-temp-file "babel-" t))
3270 "Directory to hold temporary files created to execute code blocks.
31043271 Used by `org-babel-temp-file'. This directory will be removed on
3105 Emacs shutdown."))
3272 Emacs shutdown.")
3273
3274 (defvar org-babel-temporary-stable-directory
3275 (unless noninteractive
3276 (let (dir)
3277 (while (or (not dir) (file-exists-p dir))
3278 (setq dir (expand-file-name
3279 (format "babel-stable-%d" (random 1000))
3280 temporary-file-directory)))
3281 (make-directory dir)
3282 dir))
3283 "Directory to hold temporary files created to execute code blocks.
3284 Used by `org-babel-temp-file'. This directory will be removed on
3285 Emacs shutdown.")
31063286
31073287 (defcustom org-babel-remote-temporary-directory "/tmp/"
31083288 "Directory to hold temporary files on remote hosts."
31143294 (declare (indent 1) (debug t))
31153295 (org-with-gensyms (params)
31163296 `(let ((,params ,result-params))
3117 (unless (member "none" ,params)
3118 (if (or (member "scalar" ,params)
3119 (member "verbatim" ,params)
3120 (member "html" ,params)
3121 (member "code" ,params)
3122 (member "pp" ,params)
3123 (member "file" ,params)
3124 (and (or (member "output" ,params)
3297 (unless (member "discard" ,params)
3298 (if (or (member "scalar" ,params)
3299 (member "verbatim" ,params)
3300 (member "html" ,params)
3301 (member "code" ,params)
3302 (member "pp" ,params)
3303 (member "file" ,params)
3304 (and (or (member "output" ,params)
31253305 (member "raw" ,params)
31263306 (member "org" ,params)
31273307 (member "drawer" ,params))
31293309 ,scalar-form
31303310 ,@table-forms)))))
31313311
3312 (defmacro org-babel-temp-directory ()
3313 "Return temporary directory suitable for `default-directory'."
3314 `(if (file-remote-p default-directory)
3315 (concat (file-remote-p default-directory)
3316 org-babel-remote-temporary-directory)
3317 (or (and org-babel-temporary-directory
3318 (file-exists-p org-babel-temporary-directory)
3319 org-babel-temporary-directory)
3320 temporary-file-directory)))
3321
31323322 (defun org-babel-temp-file (prefix &optional suffix)
31333323 "Create a temporary file in the `org-babel-temporary-directory'.
31343324 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
31353325 value of `temporary-file-directory' temporarily set to the value
31363326 of `org-babel-temporary-directory'."
3137 (if (file-remote-p default-directory)
3138 (let ((prefix
3139 (concat (file-remote-p default-directory)
3140 (expand-file-name
3141 prefix org-babel-remote-temporary-directory))))
3142 (make-temp-file prefix nil suffix))
3143 (let ((temporary-file-directory
3144 (or (and (boundp 'org-babel-temporary-directory)
3145 (file-exists-p org-babel-temporary-directory)
3146 org-babel-temporary-directory)
3147 temporary-file-directory)))
3148 (make-temp-file prefix nil suffix))))
3327 (make-temp-file
3328 (concat (file-name-as-directory (org-babel-temp-directory)) prefix)
3329 nil
3330 suffix))
3331
3332 (defmacro org-babel-temp-stable-directory ()
3333 "Return temporary stable directory."
3334 `(let ((org-babel-temporary-directory org-babel-temporary-stable-directory))
3335 (org-babel-temp-directory)))
3336
3337 (defun org-babel-temp-stable-file (data prefix &optional suffix)
3338 "Create a temporary file in the `org-babel-remove-temporary-stable-directory'.
3339 The file name is stable with respect to DATA. The file name is
3340 constructed like the following: PREFIXDATAhashSUFFIX."
3341 (let ((path
3342 (format
3343 "%s%s%s%s"
3344 (file-name-as-directory (org-babel-temp-stable-directory))
3345 prefix
3346 (sxhash data)
3347 (or suffix ""))))
3348 ;; Create file.
3349 (with-temp-file path)
3350 ;; Return it.
3351 path))
31493352
31503353 (defun org-babel-remove-temporary-directory ()
31513354 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3152 (when (and (boundp 'org-babel-temporary-directory)
3355 (when (and org-babel-temporary-directory
31533356 (file-exists-p org-babel-temporary-directory))
31543357 ;; taken from `delete-directory' in files.el
31553358 (condition-case nil
31663369 (delete-directory org-babel-temporary-directory))
31673370 (error
31683371 (message "Failed to remove temporary Org-babel directory %s"
3169 (if (boundp 'org-babel-temporary-directory)
3170 org-babel-temporary-directory
3171 "[directory not defined]"))))))
3372 (or org-babel-temporary-directory
3373 "[directory not defined]"))))))
3374
3375 (defun org-babel-remove-temporary-stable-directory ()
3376 "Remove `org-babel-temporary-stable-directory' and on Emacs shutdown."
3377 (when (and org-babel-temporary-stable-directory
3378 (file-exists-p org-babel-temporary-stable-directory))
3379 (let ((org-babel-temporary-directory
3380 org-babel-temporary-stable-directory))
3381 (org-babel-remove-temporary-directory))))
31723382
31733383 (add-hook 'kill-emacs-hook #'org-babel-remove-temporary-directory)
3384 (add-hook 'kill-emacs-hook #'org-babel-remove-temporary-stable-directory)
31743385
31753386 (defun org-babel-one-header-arg-safe-p (pair safe-list)
31763387 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
00 ;;; ob-css.el --- Babel Functions for CSS -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2626 ;; CSS from Org files.
2727
2828 ;;; Code:
29
30 (require 'org-macs)
31 (org-assert-version)
32
2933 (require 'ob)
3034
3135 (defvar org-babel-default-header-args:css '())
00 ;;; ob-ditaa.el --- Babel Functions for ditaa -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
3535 ;; 4) there are no variables (at least for now)
3636
3737 ;;; Code:
38
39 (require 'org-macs)
40 (org-assert-version)
41
3842 (require 'ob)
3943 (require 'org-compat)
4044
00 ;;; ob-dot.el --- Babel Functions for dot -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
5 ;; Maintainer: Justin Abrahms
5 ;; Maintainer: Justin Abrahms <justin@abrah.ms>
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
3838 ;; 4) there are no variables (at least for now)
3939
4040 ;;; Code:
41
42 (require 'org-macs)
43 (org-assert-version)
44
4145 (require 'ob)
4246
4347 (defvar org-babel-default-header-args:dot
00 ;;; ob-emacs-lisp.el --- Babel Functions for Emacs-lisp Code -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2525 ;; Org-Babel support for evaluating emacs-lisp code
2626
2727 ;;; Code:
28
29 (require 'org-macs)
30 (org-assert-version)
2831
2932 (require 'ob-core)
3033
5457 (format "(let (%s)\n%s\n)"
5558 (mapconcat
5659 (lambda (var)
57 (format "%S" (print `(,(car var) ',(cdr var)))))
60 (format "%S" `(,(car var) ',(cdr var))))
5861 vars "\n ")
5962 body))))
6063
00 ;;; ob-eshell.el --- Babel Functions for Eshell -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2018-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2018-2023 Free Software Foundation, Inc.
33
44 ;; Author: stardiviner <numbchild@gmail.com>
55 ;; Maintainer: stardiviner <numbchild@gmail.com>
6 ;; Homepage: https://github.com/stardiviner/ob-eshell
6 ;; URL: https://github.com/stardiviner/ob-eshell
77 ;; Keywords: literate programming, reproducible research
88
99 ;; This file is part of GNU Emacs.
2626 ;; Org Babel support for evaluating Eshell source code.
2727
2828 ;;; Code:
29
30 (require 'org-macs)
31 (org-assert-version)
32
2933 (require 'ob)
3034 (require 'eshell)
3135
00 ;;; ob-eval.el --- Babel Functions for External Code Evaluation -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research, comint
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2626 ;; shell commands.
2727
2828 ;;; Code:
29
2930 (require 'org-macs)
31 (org-assert-version)
32
33 (eval-when-compile (require 'subr-x)) ; For `string-empty-p', Emacs < 29
3034
3135 (defvar org-babel-error-buffer-name "*Org-Babel Error Output*")
3236 (declare-function org-babel-temp-file "ob-core" (prefix &optional suffix))
3640 (let ((buf (get-buffer-create org-babel-error-buffer-name)))
3741 (with-current-buffer buf
3842 (goto-char (point-max))
39 (save-excursion (insert stderr)))
43 (save-excursion
44 (unless (bolp) (insert "\n"))
45 (insert stderr)
46 (insert (format "[ Babel evaluation exited with code %S ]" exit-code))))
4047 (display-buffer buf))
4148 (message "Babel evaluation exited with code %S" exit-code))
4249
4350 (defun org-babel-eval (command query)
4451 "Run COMMAND on QUERY.
52 Return standard output produced by COMMAND. If COMMAND exits
53 with a non-zero code or produces error output, show it with
54 `org-babel-eval-error-notify'.
55
4556 Writes QUERY into a temp-buffer that is processed with
46 `org-babel--shell-command-on-region'. If COMMAND succeeds then return
47 its results, otherwise display STDERR with
48 `org-babel-eval-error-notify'."
57 `org-babel--shell-command-on-region'."
4958 (let ((error-buffer (get-buffer-create " *Org-Babel Error*")) exit-code)
5059 (with-current-buffer error-buffer (erase-buffer))
5160 (with-temp-buffer
52 (insert query)
61 (insert query "\n")
5362 (setq exit-code
54 (org-babel--shell-command-on-region
55 command error-buffer))
56 (if (or (not (numberp exit-code)) (> exit-code 0))
57 (progn
58 (with-current-buffer error-buffer
59 (org-babel-eval-error-notify exit-code (buffer-string)))
60 (save-excursion
61 (when (get-buffer org-babel-error-buffer-name)
62 (with-current-buffer org-babel-error-buffer-name
63 (unless (derived-mode-p 'compilation-mode)
64 (compilation-mode))
65 ;; Compilation-mode enforces read-only, but Babel expects the buffer modifiable.
66 (setq buffer-read-only nil))))
67 nil)
68 (buffer-string)))))
63 (org-babel--shell-command-on-region
64 command error-buffer))
65 (let ((stderr (with-current-buffer error-buffer (buffer-string))))
66 (if (or (not (numberp exit-code))
67 (> exit-code 0)
68 (not (string-empty-p stderr)))
69 (progn
70 (org-babel-eval-error-notify exit-code stderr)
71 (save-excursion
72 (when (get-buffer org-babel-error-buffer-name)
73 (with-current-buffer org-babel-error-buffer-name
74 (unless (derived-mode-p 'compilation-mode)
75 (compilation-mode))
76 ;; Compilation-mode enforces read-only, but
77 ;; Babel expects the buffer modifiable.
78 (setq buffer-read-only nil))))
79 ;; Return output, if any.
80 (buffer-string))
81 (buffer-string))))))
6982
7083 (defun org-babel-eval-read-file (file)
7184 "Return the contents of FILE as a string."
145158 "Return system `shell-file-name', defaulting to /bin/sh.
146159 Unfortunately, `executable-find' does not support file name
147160 handlers. Therefore, we could use it in the local case only."
148 ;; FIXME: This is generic enough that it should probably be in emacs, not org-mode
161 ;; FIXME: Since Emacs 27, `executable-find' accepts optional second
162 ;; argument supporting remote hosts.
149163 (cond ((and (not (file-remote-p default-directory))
150164 (executable-find shell-file-name))
151165 shell-file-name)
00 ;;; ob-exp.el --- Exportation of Babel Source Blocks -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Eric Schulte
55 ;; Dan Davison
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
2222 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
2323
2424 ;;; Code:
25
26 (require 'org-macs)
27 (org-assert-version)
28
2529 (require 'ob-core)
2630
27 (declare-function org-babel-lob-get-info "ob-lob" (&optional datum))
28 (declare-function org-element-at-point "org-element" ())
31 (declare-function org-babel-lob-get-info "ob-lob" (&optional datum no-eval))
32 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
2933 (declare-function org-element-context "org-element" (&optional element))
3034 (declare-function org-element-property "org-element" (property element))
3135 (declare-function org-element-type "org-element" (element))
3236 (declare-function org-escape-code-in-string "org-src" (s))
33 (declare-function org-export-copy-buffer "ox" ())
34 (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
35 (declare-function org-in-archived-heading-p "org" (&optional no-inheritance))
37 (declare-function org-export-copy-buffer "ox"
38 (&optional buffer drop-visibility
39 drop-narrowing drop-contents
40 drop-locals))
41 (declare-function org-in-commented-heading-p "org" (&optional no-inheritance element))
42 (declare-function org-in-archived-heading-p "org" (&optional no-inheritance element))
3643
3744 (defvar org-src-preserve-indentation)
3845
6572 (when source (goto-char source))
6673 ,@body))))
6774
68 (defun org-babel-exp-src-block ()
75 (defun org-babel-exp-src-block (&optional element)
6976 "Process source block for export.
7077 Depending on the \":export\" header argument, replace the source
7178 code block like this:
8087
8188 none ---- do not display either code or results upon export
8289
90 Optional argument ELEMENT must contain source block element at point.
91
8392 Assume point is at block opening line."
8493 (interactive)
8594 (save-excursion
86 (let* ((info (org-babel-get-src-block-info))
95 (let* ((info (org-babel-get-src-block-info nil element))
8796 (lang (nth 0 info))
8897 (raw-params (nth 2 info))
8998 hash)
136145 ;; Get a pristine copy of current buffer so Babel
137146 ;; references are properly resolved and source block
138147 ;; context is preserved.
139 (org-babel-exp-reference-buffer (org-export-copy-buffer)))
148 (org-babel-exp-reference-buffer (org-export-copy-buffer))
149 element)
140150 (unwind-protect
141151 (save-excursion
142152 ;; First attach to every source block their original
156166 ;; Evaluate from top to bottom every Babel block
157167 ;; encountered.
158168 (goto-char (point-min))
159 (while (re-search-forward regexp nil t)
160 (unless (save-match-data (or (org-in-commented-heading-p)
161 (org-in-archived-heading-p)))
162 (let* ((object? (match-end 1))
163 (element (save-match-data
164 (if object? (org-element-context)
165 ;; No deep inspection if we're
166 ;; just looking for an element.
167 (org-element-at-point))))
168 (type
169 (pcase (org-element-type element)
170 ;; Discard block elements if we're looking
171 ;; for inline objects. False results
172 ;; happen when, e.g., "call_" syntax is
173 ;; located within affiliated keywords:
174 ;;
175 ;; #+name: call_src
176 ;; #+begin_src ...
177 ((and (or `babel-call `src-block) (guard object?))
178 nil)
179 (type type)))
180 (begin
181 (copy-marker (org-element-property :begin element)))
182 (end
183 (copy-marker
184 (save-excursion
185 (goto-char (org-element-property :end element))
186 (skip-chars-backward " \r\t\n")
187 (point)))))
188 (pcase type
189 (`inline-src-block
190 (let* ((info
191 (org-babel-get-src-block-info nil element))
192 (params (nth 2 info)))
193 (setf (nth 1 info)
194 (if (and (cdr (assq :noweb params))
195 (string= "yes"
196 (cdr (assq :noweb params))))
197 (org-babel-expand-noweb-references
198 info org-babel-exp-reference-buffer)
199 (nth 1 info)))
200 (goto-char begin)
201 (let ((replacement
202 (org-babel-exp-do-export info 'inline)))
203 (if (equal replacement "")
204 ;; Replacement code is empty: remove
205 ;; inline source block, including extra
206 ;; white space that might have been
207 ;; created when inserting results.
208 (delete-region begin
209 (progn (goto-char end)
210 (skip-chars-forward " \t")
211 (point)))
212 ;; Otherwise: remove inline source block
213 ;; but preserve following white spaces.
214 ;; Then insert value.
169 ;; We are about to do a large number of changes in
170 ;; buffer, but we do not care about folding in this
171 ;; buffer.
172 (org-fold-core-ignore-modifications
173 (while (re-search-forward regexp nil t)
174 (setq element (org-element-at-point))
175 (unless (save-match-data
176 (or (org-in-commented-heading-p nil element)
177 (org-in-archived-heading-p nil element)))
178 (let* ((object? (match-end 1))
179 (element (save-match-data
180 (if object?
181 (org-element-context element)
182 ;; No deep inspection if we're
183 ;; just looking for an element.
184 element)))
185 (type
186 (pcase (org-element-type element)
187 ;; Discard block elements if we're looking
188 ;; for inline objects. False results
189 ;; happen when, e.g., "call_" syntax is
190 ;; located within affiliated keywords:
191 ;;
192 ;; #+name: call_src
193 ;; #+begin_src ...
194 ((and (or `babel-call `src-block) (guard object?))
195 nil)
196 (type type)))
197 (begin
198 (copy-marker (org-element-property :begin element)))
199 (end
200 (copy-marker
201 (save-excursion
202 (goto-char (org-element-property :end element))
203 (skip-chars-backward " \r\t\n")
204 (point)))))
205 (pcase type
206 (`inline-src-block
207 (let* ((info
208 (org-babel-get-src-block-info nil element))
209 (params (nth 2 info)))
210 (setf (nth 1 info)
211 (if (and (cdr (assq :noweb params))
212 (string= "yes"
213 (cdr (assq :noweb params))))
214 (org-babel-expand-noweb-references
215 info org-babel-exp-reference-buffer)
216 (nth 1 info)))
217 (goto-char begin)
218 (let ((replacement
219 (org-babel-exp-do-export info 'inline)))
220 (if (equal replacement "")
221 ;; Replacement code is empty: remove
222 ;; inline source block, including extra
223 ;; white space that might have been
224 ;; created when inserting results.
225 (delete-region begin
226 (progn (goto-char end)
227 (skip-chars-forward " \t")
228 (point)))
229 ;; Otherwise: remove inline source block
230 ;; but preserve following white spaces.
231 ;; Then insert value.
232 (unless (string= replacement
233 (buffer-substring begin end))
234 (delete-region begin end)
235 (insert replacement))))))
236 ((or `babel-call `inline-babel-call)
237 (org-babel-exp-do-export
238 (or (org-babel-lob-get-info element)
239 (user-error "Unknown Babel reference: %s"
240 (org-element-property :call element)))
241 'lob)
242 (let ((rep
243 (org-fill-template
244 org-babel-exp-call-line-template
245 `(("line" .
246 ,(org-element-property :value element))))))
247 ;; If replacement is empty, completely remove
248 ;; the object/element, including any extra
249 ;; white space that might have been created
250 ;; when including results.
251 (if (equal rep "")
252 (delete-region
253 begin
254 (progn (goto-char end)
255 (if (not (eq type 'babel-call))
256 (progn (skip-chars-forward " \t")
257 (point))
258 (skip-chars-forward " \r\t\n")
259 (line-beginning-position))))
260 ;; Otherwise, preserve trailing
261 ;; spaces/newlines and then, insert
262 ;; replacement string.
263 (goto-char begin)
215264 (delete-region begin end)
216 (insert replacement)))))
217 ((or `babel-call `inline-babel-call)
218 (org-babel-exp-do-export
219 (or (org-babel-lob-get-info element)
220 (user-error "Unknown Babel reference: %s"
221 (org-element-property :call element)))
222 'lob)
223 (let ((rep
224 (org-fill-template
225 org-babel-exp-call-line-template
226 `(("line" .
227 ,(org-element-property :value element))))))
228 ;; If replacement is empty, completely remove
229 ;; the object/element, including any extra
230 ;; white space that might have been created
231 ;; when including results.
232 (if (equal rep "")
233 (delete-region
234 begin
235 (progn (goto-char end)
236 (if (not (eq type 'babel-call))
237 (progn (skip-chars-forward " \t")
238 (point))
239 (skip-chars-forward " \r\t\n")
240 (line-beginning-position))))
241 ;; Otherwise, preserve trailing
242 ;; spaces/newlines and then, insert
243 ;; replacement string.
244 (goto-char begin)
245 (delete-region begin end)
246 (insert rep))))
247 (`src-block
248 (let ((match-start (copy-marker (match-beginning 0)))
249 (ind (current-indentation)))
250 ;; Take care of matched block: compute
251 ;; replacement string. In particular, a nil
252 ;; REPLACEMENT means the block is left as-is
253 ;; while an empty string removes the block.
254 (let ((replacement
255 (progn (goto-char match-start)
256 (org-babel-exp-src-block))))
257 (cond ((not replacement) (goto-char end))
258 ((equal replacement "")
259 (goto-char end)
260 (skip-chars-forward " \r\t\n")
261 (beginning-of-line)
262 (delete-region begin (point)))
263 (t
264 (goto-char match-start)
265 (delete-region (point)
266 (save-excursion
267 (goto-char end)
268 (line-end-position)))
269 (insert replacement)
270 (if (or org-src-preserve-indentation
271 (org-element-property
272 :preserve-indent element))
273 ;; Indent only code block
274 ;; markers.
275 (save-excursion
276 (skip-chars-backward " \r\t\n")
277 (indent-line-to ind)
278 (goto-char match-start)
279 (indent-line-to ind))
280 ;; Indent everything.
281 (indent-rigidly
282 match-start (point) ind)))))
283 (set-marker match-start nil))))
284 (set-marker begin nil)
285 (set-marker end nil)))))
265 (insert rep))))
266 (`src-block
267 (let ((match-start (copy-marker (match-beginning 0)))
268 (ind (org-current-text-indentation)))
269 ;; Take care of matched block: compute
270 ;; replacement string. In particular, a nil
271 ;; REPLACEMENT means the block is left as-is
272 ;; while an empty string removes the block.
273 (let ((replacement
274 (progn (goto-char match-start)
275 (org-babel-exp-src-block element))))
276 (cond ((not replacement) (goto-char end))
277 ((equal replacement "")
278 (goto-char end)
279 (skip-chars-forward " \r\t\n")
280 (beginning-of-line)
281 (delete-region begin (point)))
282 (t
283 (if (or org-src-preserve-indentation
284 (org-element-property
285 :preserve-indent element))
286 ;; Indent only code block
287 ;; markers.
288 (with-temp-buffer
289 ;; Do not use tabs for block
290 ;; indentation.
291 (when (fboundp 'indent-tabs-mode)
292 (indent-tabs-mode -1)
293 ;; FIXME: Emacs 26
294 ;; compatibility.
295 (setq-local indent-tabs-mode nil))
296 (insert replacement)
297 (skip-chars-backward " \r\t\n")
298 (indent-line-to ind)
299 (goto-char 1)
300 (indent-line-to ind)
301 (setq replacement (buffer-string)))
302 ;; Indent everything.
303 (with-temp-buffer
304 ;; Do not use tabs for block
305 ;; indentation.
306 (when (fboundp 'indent-tabs-mode)
307 (indent-tabs-mode -1)
308 ;; FIXME: Emacs 26
309 ;; compatibility.
310 (setq-local indent-tabs-mode nil))
311 (insert replacement)
312 (indent-rigidly
313 1 (point) ind)
314 (setq replacement (buffer-string))))
315 (goto-char match-start)
316 (let ((rend (save-excursion
317 (goto-char end)
318 (line-end-position))))
319 (if (string-equal replacement
320 (buffer-substring match-start rend))
321 (goto-char rend)
322 (delete-region match-start
323 (save-excursion
324 (goto-char end)
325 (line-end-position)))
326 (insert replacement))))))
327 (set-marker match-start nil))))
328 (set-marker begin nil)
329 (set-marker end nil))))))
286330 (kill-buffer org-babel-exp-reference-buffer)
287331 (remove-text-properties (point-min) (point-max)
288332 '(org-reference nil)))))))
305349 (org-babel-exp-code info type)))))
306350
307351 (defcustom org-babel-exp-code-template
308 "#+BEGIN_SRC %lang%switches%flags\n%body\n#+END_SRC"
352 "#+begin_src %lang%switches%flags\n%body\n#+end_src"
309353 "Template used to export the body of code blocks.
310354 This template may be customized to include additional information
311355 such as the code block name, or the values of particular header
322366 defined for the code block may be used as a key and will be
323367 replaced with its value."
324368 :group 'org-babel
325 :type 'string)
369 :type 'string
370 :package-version '(Org . "9.6"))
326371
327372 (defcustom org-babel-exp-inline-code-template
328373 "src_%lang[%switches%flags]{%body}"
00 ;;; ob-forth.el --- Babel Functions for Forth -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2014-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2014-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research, forth
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
3131 ;; `forth-mode' which is distributed with gforth (in gforth.el).
3232
3333 ;;; Code:
34
35 (require 'org-macs)
36 (org-assert-version)
37
3438 (require 'ob)
3539 (require 'org-macs)
3640
00 ;;; ob-fortran.el --- Babel Functions for Fortran -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2011-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2011-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Sergey Litvinov
55 ;; Eric Schulte
66 ;; Keywords: literate programming, reproducible research, fortran
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010 ;;
2626 ;; Org-Babel support for evaluating fortran code.
2727
2828 ;;; Code:
29
30 (require 'org-macs)
31 (org-assert-version)
32
2933 (require 'ob)
3034 (require 'org-macs)
3135 (require 'cc-mode)
00 ;;; ob-gnuplot.el --- Babel Functions for Gnuplot -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Maintainer: Ihor Radchenko <yantar92@gmail.com>
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
3838 ;; - gnuplot-mode :: you can search the web for the latest active one.
3939
4040 ;;; Code:
41
42 (require 'org-macs)
43 (org-assert-version)
44
4145 (require 'ob)
4246 (require 'org-macs)
4347
9397 (let* ((first (car val))
9498 (tablep (or (listp first) (symbolp first))))
9599 (if tablep val (mapcar 'list val)))
96 (org-babel-temp-file "gnuplot-") params)
100 ;; Make temporary file name stable with respect to data.
101 ;; If we do not do it, :cache argument becomes useless.
102 (org-babel-temp-stable-file (cons val params) "gnuplot-")
103 params)
97104 (if (and (stringp val)
98105 (file-remote-p val) ;; check if val is a remote file
99106 (file-exists-p val)) ;; call to file-exists-p is slow, maybe remove it
100107 (let* ((local-name (concat ;; create a unique filename to avoid multiple downloads
101 org-babel-temporary-directory
108 (org-babel-temp-directory)
102109 "/gnuplot/"
103110 (file-remote-p val 'host)
104111 (org-babel-local-file-name val))))
128135 (title (cdr (assq :title params)))
129136 (lines (cdr (assq :line params)))
130137 (sets (cdr (assq :set params)))
138 (missing (cdr (assq :missing params)))
131139 (x-labels (cdr (assq :xlabels params)))
132140 (y-labels (cdr (assq :ylabels params)))
133141 (timefmt (cdr (assq :timefmt params)))
134142 (time-ind (or (cdr (assq :timeind params))
135143 (when timefmt 1)))
136 (directory (and (buffer-file-name)
137 (file-name-directory (buffer-file-name))))
144 (directory default-directory)
138145 (add-to-body (lambda (text) (setq body (concat text "\n" body)))))
139146 ;; append header argument settings to body
147 (when missing (funcall add-to-body (format "set datafile missing '%s'" missing)))
140148 (when title (funcall add-to-body (format "set title '%s'" title)))
141149 (when lines (mapc (lambda (el) (funcall add-to-body el)) lines))
142150 (when sets
283291 (defun org-babel-gnuplot-table-to-data (table data-file params)
284292 "Export TABLE to DATA-FILE in a format readable by gnuplot.
285293 Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
294 (require 'ox-org)
286295 (with-temp-file data-file
287296 (insert (let ((org-babel-gnuplot-timestamp-fmt
288297 (or (plist-get params :timefmt) "%Y-%m-%d-%H:%M:%S")))
289298 (orgtbl-to-generic
290299 table
291300 (org-combine-plists
292 '(:sep "\t" :fmt org-babel-gnuplot-quote-tsv-field :raw t :backend ascii)
301 '( :sep "\t" :fmt org-babel-gnuplot-quote-tsv-field
302 ;; Two setting below are needed to make :fmt work.
303 :raw t
304 :backend ascii)
293305 params)))))
294306 data-file)
295307
00 ;;; ob-groovy.el --- Babel Functions for Groovy -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2013-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2013-2023 Free Software Foundation, Inc.
33
4 ;; Author: Miro Bezjak
5 ;; Maintainer: Palak Mathur
4 ;; Author: Miro Bezjak <bezjak.miro@gmail.com>
5 ;; Maintainer: Palak Mathur <palakmathur@gmail.com>
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
3030 ;; https://github.com/russel/Emacs-Groovy-Mode
3131
3232 ;;; Code:
33
34 (require 'org-macs)
35 (org-assert-version)
36
3337 (require 'ob)
3438
3539 (defvar org-babel-tangle-lang-exts) ;; Autoloaded
4751 (defun org-babel-execute:groovy (body params)
4852 "Execute a block of Groovy code with org-babel.
4953 This function is called by `org-babel-execute-src-block'."
50 (message "executing Groovy source code block")
54 (message "Executing Groovy source code block")
5155 (let* ((processed-params (org-babel-process-params params))
5256 (session (org-babel-groovy-initiate-session (nth 0 processed-params)))
5357 (result-params (nth 2 processed-params))
00 ;;; ob-haskell.el --- Babel Functions for Haskell -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Maintainer: Lawrence Bottorff <borgauf@gmail.com>
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
3838 ;; - (optionally) lhs2tex: https://people.cs.uu.nl/andres/lhs2tex/
3939
4040 ;;; Code:
41
42 (require 'org-macs)
43 (org-assert-version)
44
4145 (require 'ob)
4246 (require 'org-macs)
4347 (require 'comint)
131135 (comint-preoutput-filter-functions
132136 (cons 'ansi-color-filter-apply comint-preoutput-filter-functions))
133137 (raw (org-babel-comint-with-output
134 (session org-babel-haskell-eoe t full-body)
138 (session org-babel-haskell-eoe nil full-body)
135139 (insert (org-trim full-body))
136140 (comint-send-input nil t)
137141 (insert org-babel-haskell-eoe)
145149 (`output (mapconcat #'identity (reverse results) "\n"))
146150 (`value (car results)))))
147151 (org-babel-result-cond (cdr (assq :result-params params))
148 result (org-babel-script-escape result)))
152 result (when result (org-babel-script-escape result))))
149153 (org-babel-pick-name (cdr (assq :colname-names params))
150154 (cdr (assq :colname-names params)))
151155 (org-babel-pick-name (cdr (assq :rowname-names params))
00 ;;; ob-java.el --- org-babel functions for java evaluation -*- lexical-binding: t -*-
11
2 ;; Copyright (C) 2011-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2011-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Eric Schulte
55 ;; Dan Davison
66 ;; Maintainer: Ian Martins <ianxm@jhu.edu>
77 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: https://orgmode.org
8 ;; URL: https://orgmode.org
99
1010 ;; This file is part of GNU Emacs.
1111
2727 ;; Org-Babel support for evaluating java source code.
2828
2929 ;;; Code:
30
31 (require 'org-macs)
32 (org-assert-version)
33
3034 (require 'ob)
3135
3236 (defvar org-babel-tangle-lang-exts)
4852
4953 [1] https://orgmode.org/manual/Results-of-Evaluation.html")
5054
51 (defconst org-babel-header-args:java '((imports . :any))
55 (defconst org-babel-header-args:java
56 '((dir . :any)
57 (classname . :any)
58 (imports . :any)
59 (cmpflag . :any)
60 (cmdline . :any)
61 (cmdarg . :any))
5262 "Java-specific header arguments.")
5363
5464 (defcustom org-babel-java-command "java"
183193 (packagename (if (string-match-p "\\." fullclassname)
184194 (file-name-base fullclassname)))
185195 ;; the base dir that contains the top level package dir
186 (basedir (file-name-as-directory (if run-from-temp
187 (if (file-remote-p default-directory)
188 (concat
189 (file-remote-p default-directory)
190 org-babel-remote-temporary-directory)
191 org-babel-temporary-directory)
192 default-directory)))
196 (basedir (file-name-as-directory
197 (if run-from-temp
198 (org-babel-temp-directory)
199 default-directory)))
193200 ;; the dir to write the source file
194201 (packagedir (if (and (not run-from-temp) packagename)
195202 (file-name-as-directory
00 ;;; ob-js.el --- Babel Functions for Javascript -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research, js
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
3737 ;; configuration instructions
3838
3939 ;;; Code:
40
41 (require 'org-macs)
42 (org-assert-version)
43
4044 (require 'ob)
4145
4246 (declare-function run-mozilla "ext:moz" (arg))
6468 :safe #'stringp)
6569
6670 (defvar org-babel-js-function-wrapper
67 "require('process').stdout.write(require('util').inspect(function(){%s}()));"
71 ;; Note that newline after %s - it makes sure that closing
72 ;; parenthesis are not shadowed if the last line of the body is a
73 ;; line comment.
74 "require('process').stdout.write(require('util').inspect(function(){%s\n}()));"
6875 "Javascript code to print value of body.")
6976
7077 (defun org-babel-execute:js (body params)
00 ;;; ob-julia.el --- org-babel functions for julia code evaluation -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2013-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2013-2023 Free Software Foundation, Inc.
33 ;; Authors: G. Jay Kerns
44 ;; Maintainer: Pedro Bruel <pedro.bruel@gmail.com>
55 ;; Keywords: literate programming, reproducible research, scientific computing
6 ;; Homepage: https://github.com/phrb/ob-julia
6 ;; URL: https://github.com/phrb/ob-julia
77
88 ;; This file is part of GNU Emacs.
99
2525 ;; Org-Babel support for evaluating julia code
2626 ;;
2727 ;; Based on ob-R.el by Eric Schulte and Dan Davison.
28 ;;
29 ;; Session support requires the installation of the DataFrames and CSV
30 ;; Julia packages.
2831
2932 ;;; Code:
33
34 (require 'org-macs)
35 (org-assert-version)
36
3037 (require 'cl-lib)
3138 (require 'ob)
3239
6168 (defvar ess-current-process-name) ; dynamically scoped
6269 (defvar ess-local-process-name) ; dynamically scoped
6370 (defvar ess-eval-visibly-p) ; dynamically scoped
71 (defvar ess-local-customize-alist); dynamically scoped
6472 (defun org-babel-edit-prep:julia (info)
6573 (let ((session (cdr (assq :session (nth 2 info)))))
6674 (when (and session
249257 (defun org-babel-julia-evaluate-external-process
250258 (body result-type result-params column-names-p)
251259 "Evaluate BODY in external julia process.
252 If RESULT-TYPE equals 'output then return standard output as a
253 string. If RESULT-TYPE equals 'value then return the value of the
260 If RESULT-TYPE equals `output' then return standard output as a
261 string. If RESULT-TYPE equals `value' then return the value of the
254262 last statement in BODY, as elisp."
255263 (cl-case result-type
256264 (value
273281 (defun org-babel-julia-evaluate-session
274282 (session body result-type result-params column-names-p)
275283 "Evaluate BODY in SESSION.
276 If RESULT-TYPE equals 'output then return standard output as a
277 string. If RESULT-TYPE equals 'value then return the value of the
284 If RESULT-TYPE equals `output' then return standard output as a
285 string. If RESULT-TYPE equals `value' then return the value of the
278286 last statement in BODY, as elisp."
279287 (cl-case result-type
280288 (value
281289 (with-temp-buffer
282290 (insert (org-babel-chomp body))
283 (let ((ess-local-process-name
291 (let ((ess-local-customize-alist t)
292 (ess-local-process-name
284293 (process-name (get-buffer-process session)))
285294 (ess-eval-visibly-p nil))
286295 (ess-eval-buffer nil)))
00 ;;; ob-latex.el --- Babel Functions for LaTeX -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2929 ;; be created directly form the latex source code.
3030
3131 ;;; Code:
32
33 (require 'org-macs)
34 (org-assert-version)
35
3236 (require 'ob)
3337 (require 'org-macs)
3438
3640 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
3741 (declare-function org-latex-guess-inputenc "ox-latex" (header))
3842 (declare-function org-splice-latex-header "org" (tpl def-pkg pkg snippets-p &optional extra))
43 (declare-function org-at-heading-p "org" (&optional _))
44 (declare-function org-back-to-heading "org" (&optional invisible-ok))
45 (declare-function org-next-visible-heading "org" (arg))
3946
4047 (defvar org-babel-tangle-lang-exts)
4148 (add-to-list 'org-babel-tangle-lang-exts '("latex" . "tex"))
6067 (pdfpng . :any)
6168 (pdfwidth . :any)
6269 (headers . :any)
63 (packages . :any)
6470 (buffer . ((yes no))))
6571 "LaTeX-specific header arguments.")
6672
103109 :type 'function)
104110
105111 (defcustom org-babel-latex-pdf-svg-process
106 "inkscape --pdf-poppler %f -T -l -o %O"
112 "inkscape \
113 --pdf-poppler \
114 --export-area-drawing \
115 --export-text-to-path \
116 --export-plain-svg \
117 --export-filename=%O \
118 %f"
107119 "Command to convert a PDF file to an SVG file."
108120 :group 'org-babel
109 :type 'string)
121 :type 'string
122 :package-version '(Org . "9.6"))
110123
111124 (defcustom org-babel-latex-htlatex-packages
112125 '("[usenames]{color}" "{tikz}" "{color}" "{listings}" "{amsmath}")
127140 (org-trim body))
128141
129142 (defun org-babel-execute:latex (body params)
130 "Execute a block of Latex code with Babel.
143 "Execute a block of LaTeX code with Babel.
131144 This function is called by `org-babel-execute-src-block'."
132145 (setq body (org-babel-expand-body:latex body params))
133146 (if (cdr (assq :file params))
166179 tmp-pdf
167180 (list org-babel-latex-pdf-svg-process)
168181 extension err-msg log-buf)))
169 (shell-command (format "mv %s %s" img-out out-file)))))
182 (rename-file img-out out-file t))))
170183 ((string-suffix-p ".tikz" out-file)
171184 (when (file-exists-p out-file) (delete-file out-file))
172185 (with-temp-file out-file
204217 (if (string-suffix-p ".svg" out-file)
205218 (progn
206219 (shell-command "pwd")
207 (shell-command (format "mv %s %s"
208 (concat (file-name-sans-extension tex-file) "-1.svg")
209 out-file)))
220 (rename-file (concat (file-name-sans-extension tex-file) "-1.svg")
221 out-file t))
210222 (error "SVG file produced but HTML file requested")))
211223 ((file-exists-p (concat (file-name-sans-extension tex-file) ".html"))
212224 (if (string-suffix-p ".html" out-file)
213 (shell-command "mv %s %s"
214 (concat (file-name-sans-extension tex-file)
215 ".html")
216 out-file)
217 (error "HTML file produced but SVG file requested")))))
225 (rename-file (concat (file-name-sans-extension tex-file) ".html")
226 out-file t)
227 (error "HTML file produced but SVG file requested")))))
218228 ((or (string= "pdf" extension) imagemagick)
219229 (with-temp-file tex-file
220230 (require 'ox-latex)
00 ;;; ob-lilypond.el --- Babel Functions for Lilypond -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Martyn Jago
55 ;; Keywords: babel language, literate programming
6 ;; Homepage: https://orgmode.org/worg/org-contrib/babel/languages/ob-doc-lilypond.html
6 ;; URL: https://orgmode.org/worg/org-contrib/babel/languages/ob-doc-lilypond.html
77
88 ;; This file is part of GNU Emacs.
99
3131 ;; This depends on epstopdf --- See https://www.ctan.org/pkg/epstopdf.
3232
3333 ;;; Code:
34
35 (require 'org-macs)
36 (org-assert-version)
37
3438 (require 'ob)
3539
36 (declare-function org-show-all "org" (&optional types))
37
40 (declare-function org-fold-show-all "org-fold" (&optional types))
41
42 ;; FIXME: Doesn't this rather belong in lilypond-mode.el?
3843 (defalias 'lilypond-mode 'LilyPond-mode)
3944
4045 (add-to-list 'org-babel-tangle-lang-exts '("LilyPond" . "ly"))
106111 :package-version '(Org . "8.2.7")
107112 :set
108113 (lambda (symbol value)
109 (set symbol value)
114 (set-default-toplevel-value symbol value)
110115 (setq
111116 org-babel-lilypond-ly-command (nth 0 value)
112117 org-babel-lilypond-pdf-command (nth 1 value)
278283 (setq case-fold-search nil)
279284 (if (search-forward line nil t)
280285 (progn
281 (org-show-all)
286 (org-fold-show-all)
282287 (set-mark (point))
283288 (goto-char (- (point) (length line))))
284289 (goto-char temp))))
310315 (progn
311316 (goto-char (point-min))
312317 (forward-line (- lineNo 1))
313 (buffer-substring (point) (point-at-eol)))
318 (buffer-substring (point) (line-end-position)))
314319 nil)))
315320
316321 (defun org-babel-lilypond-attempt-to-open-pdf (file-name &optional test)
00 ;;; ob-lisp.el --- Babel Functions for Common Lisp -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Joel Boehland
55 ;; Eric Schulte
66 ;; David T. O'Toole <dto@gnu.org>
77 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: https://orgmode.org
8 ;; URL: https://orgmode.org
99
1010 ;; This file is part of GNU Emacs.
1111
3535 ;; - https://common-lisp.net/project/slime/
3636
3737 ;;; Code:
38
39 (require 'org-macs)
40 (org-assert-version)
41
3842 (require 'ob)
3943 (require 'org-macs)
4044
00 ;;; ob-lob.el --- Functions Supporting the Library of Babel -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Eric Schulte
55 ;; Dan Davison
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
2222 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
2323
2424 ;;; Code:
25
26 (require 'org-macs)
27 (org-assert-version)
28
2529 (require 'cl-lib)
2630 (require 'ob-core)
2731 (require 'ob-table)
2832
2933 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
30 (declare-function org-element-at-point "org-element" ())
34 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
3135 (declare-function org-element-context "org-element" (&optional element))
3236 (declare-function org-element-property "org-element" (property element))
3337 (declare-function org-element-type "org-element" (element))
4953 (interactive "fFile: ")
5054 (let ((lob-ingest-count 0))
5155 (org-babel-map-src-blocks file
52 (let* ((info (org-babel-get-src-block-info 'light))
56 (let* ((info (org-babel-get-src-block-info 'no-eval))
5357 (source-name (nth 4 info)))
5458 (when source-name
5559 (setf (nth 1 info)
7377 Detect if this is context for a Library Of Babel source block and
7478 if so then run the appropriate source block from the Library."
7579 (interactive)
76 (let ((info (org-babel-lob-get-info)))
80 (let* ((datum (org-element-context))
81 (info (org-babel-lob-get-info datum)))
7782 (when info
78 (org-babel-execute-src-block nil info)
83 (org-babel-execute-src-block nil info nil (org-element-type datum))
7984 t)))
8085
8186 (defun org-babel-lob--src-info (ref)
113118 (cdr (assoc-string ref org-babel-library-of-babel))))))))
114119
115120 ;;;###autoload
116 (defun org-babel-lob-get-info (&optional datum)
121 (defun org-babel-lob-get-info (&optional datum no-eval)
117122 "Return internal representation for Library of Babel function call.
118123
119124 Consider DATUM, when provided, or element at point otherwise.
125
126 When optional argument NO-EVAL is non-nil, Babel does not resolve
127 remote variable references; a process which could likely result
128 in the execution of other code blocks, and do not evaluate Lisp
129 values in parameters.
120130
121131 Return nil when not on an appropriate location. Otherwise return
122132 a list compatible with `org-babel-get-src-block-info', which
138148 org-babel-default-lob-header-args
139149 (append
140150 (org-with-point-at begin
141 (org-babel-params-from-properties language))
151 (org-babel-params-from-properties language no-eval))
142152 (list
143153 (org-babel-parse-header-arguments
144 (org-element-property :inside-header context))
154 (org-element-property :inside-header context) no-eval)
145155 (let ((args (org-element-property :arguments context)))
146156 (and args
147157 (mapcar (lambda (ref) (cons :var ref))
148158 (org-babel-ref-split-args args))))
149159 (org-babel-parse-header-arguments
150 (org-element-property :end-header context)))))
160 (org-element-property :end-header context) no-eval))))
151161 nil
152162 (org-element-property :name context)
153163 begin
00 ;;; ob-lua.el --- Org Babel functions for Lua evaluation -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2014, 2016-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2014, 2016-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Dieter Schoen
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
3434 ;; However, sessions are not yet working.
3535
3636 ;;; Code:
37
38 (require 'org-macs)
39 (org-assert-version)
40
3741 (require 'ob)
3842 (require 'org-macs)
3943 (require 'cl-lib)
394398 (org-babel-lua-table-or-string results)))))
395399
396400 (defun org-babel-lua-read-string (string)
397 "Strip 's from around Lua string."
401 "Strip single quotes from around Lua string."
398402 (org-unbracket-string "'" "'" string))
399403
400404 (provide 'ob-lua)
00 ;;; ob-makefile.el --- Babel Functions for Makefile -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Thomas S. Dye
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
2626 ;; This file exists solely for tangling a Makefile from Org files.
2727
2828 ;;; Code:
29
30 (require 'org-macs)
31 (org-assert-version)
32
2933 (require 'ob)
3034
3135 (defvar org-babel-default-header-args:makefile '())
00 ;;; ob-matlab.el --- Babel support for Matlab -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Dan Davison
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
3131
3232 ;; matlab.el required for interactive emacs sessions and matlab-mode
3333 ;; major mode for source code editing buffer
34 ;; http://matlab-emacs.sourceforge.net/
34 ;; https://matlab-emacs.sourceforge.net/
3535
3636 ;;; Code:
37
38 (require 'org-macs)
39 (org-assert-version)
40
3741 (require 'ob)
3842 (require 'ob-octave)
3943
00 ;;; ob-maxima.el --- Babel Functions for Maxima -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric S Fraga
55 ;; Eric Schulte
66 ;; Keywords: literate programming, reproducible research, maxima
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
3030 ;; 2) we are adding the "cmdline" header argument
3131
3232 ;;; Code:
33
34 (require 'org-macs)
35 (org-assert-version)
36
3337 (require 'ob)
3438
3539 (defvar org-babel-tangle-lang-exts)
7175 (defun org-babel-execute:maxima (body params)
7276 "Execute a block of Maxima entries with org-babel.
7377 This function is called by `org-babel-execute-src-block'."
74 (message "executing Maxima source code block")
78 (message "Executing Maxima source code block")
7579 (let ((result-params (split-string (or (cdr (assq :results params)) "")))
7680 (result
7781 (let* ((cmdline (or (cdr (assq :cmdline params)) ""))
7882 (in-file (org-babel-temp-file "maxima-" ".max"))
79 (cmd (format "%s --very-quiet -r 'batchload(%S)$' %s"
80 org-babel-maxima-command in-file cmdline)))
83 (cmd (format "%s --very-quiet -r %s %s"
84 org-babel-maxima-command
85 (shell-quote-argument
86 (format "batchload(%S)$" in-file))
87 cmdline)))
8188 (with-temp-file in-file (insert (org-babel-maxima-expand body params)))
8289 (message cmd)
8390 ;; " | grep -v batch | grep -v 'replaced' | sed '/^$/d' "
00 ;;; ob-ocaml.el --- Babel Functions for Ocaml -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
3434 ;; - tuareg-mode :: https://elpa.nongnu.org/nongnu/tuareg.html
3535
3636 ;;; Code:
37
38 (require 'org-macs)
39 (org-assert-version)
40
3741 (require 'ob)
3842 (require 'comint)
3943 (require 'org-macs)
00 ;;; ob-octave.el --- Babel Functions for Octave and Matlab -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Dan Davison
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2828 ;; octave-mode.el and octave-inf.el come with GNU emacs
2929
3030 ;;; Code:
31
32 (require 'org-macs)
33 (org-assert-version)
34
3135 (require 'ob)
3236 (require 'org-macs)
3337
5660 ")
5761 (defvar org-babel-octave-wrapper-method
5862 "%s
59 if ischar(ans), fid = fopen('%s', 'w'); fprintf(fid, '%%s\\n', ans); fclose(fid);
63 if ischar(ans), fid = fopen('%s', 'w'); fdisp(fid, ans); fclose(fid);
6064 else, dlmwrite('%s', ans, '\\t')
6165 end")
6266
8690 (list
8791 "set (0, \"defaultfigurevisible\", \"off\");"
8892 full-body
89 (format "print -dpng %s" gfx-file))
93 (format "print -dpng %S\nans=%S" gfx-file gfx-file))
9094 "\n")
9195 full-body)
9296 result-type matlabp)))
238242 (`output
239243 (setq results
240244 (if matlabp
241 (cdr (reverse (delq "" (mapcar #'org-strip-quotes
242 (mapcar #'org-trim raw)))))
245 (cdr (reverse (delete "" (mapcar #'org-strip-quotes
246 (mapcar #'org-trim raw)))))
243247 (cdr (member org-babel-octave-eoe-output
244248 (reverse (mapcar #'org-strip-quotes
245249 (mapcar #'org-trim raw)))))))
254258 (insert-file-contents file-name)
255259 (re-search-forward "^[ \t]*[^# \t]" nil t)
256260 (when (< (setq beg (point-min))
257 (setq end (point-at-bol)))
261 (setq end (line-beginning-position)))
258262 (delete-region beg end)))
259263 (org-babel-import-elisp-from-file temp-file '(16))))
260264
00 ;;; ob-org.el --- Babel Functions for Org Code Blocks -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2626 ;; contents of the code block are returned in a raw result.
2727
2828 ;;; Code:
29
30 (require 'org-macs)
31 (org-assert-version)
32
2933 (require 'ob)
3034
3135 (declare-function org-export-string-as "ox"
00 ;;; ob-perl.el --- Babel Functions for Perl -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Dan Davison
55 ;; Eric Schulte
6 ;; Maintainer: Corwin Brust
6 ;; Maintainer: Corwin Brust <corwin@bru.st>
77 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: https://orgmode.org
8 ;; URL: https://orgmode.org
99
1010 ;; This file is part of GNU Emacs.
1111
2727 ;; Org-Babel support for evaluating perl source code.
2828
2929 ;;; Code:
30
31 (require 'org-macs)
32 (org-assert-version)
33
3034 (require 'ob)
3135
3236 (defvar org-babel-tangle-lang-exts)
00 ;;; ob-plantuml.el --- Babel Functions for Plantuml -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Zhang Weize
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2929
3030 ;;; Requirements:
3131
32 ;; plantuml | http://plantuml.sourceforge.net/
32 ;; plantuml | https://plantuml.com/
3333 ;; plantuml.jar | `org-plantuml-jar-path' should point to the jar file (when exec mode is `jar')
3434
3535 ;;; Code:
36
37 (require 'org-macs)
38 (org-assert-version)
39
3640 (require 'ob)
3741
3842 (defvar org-babel-default-header-args:plantuml
6468 :package-version '(Org . "9.4")
6569 :type 'string)
6670
67 (defcustom org-plantuml-executable-args (list "-headless")
68 "The arguments passed to plantuml executable when executing PlantUML."
71 (defcustom org-plantuml-args (list "-headless")
72 "The arguments passed to plantuml when executing PlantUML."
6973 :group 'org-babel
7074 :package-version '(Org . "9.4")
7175 :type '(repeat string))
108112 (defun org-babel-execute:plantuml (body params)
109113 "Execute a block of plantuml code with org-babel.
110114 This function is called by `org-babel-execute-src-block'."
111 (let* ((out-file (or (cdr (assq :file params))
112 (error "PlantUML requires a \":file\" header argument")))
115 (let* ((do-export (member "file" (cdr (assq :result-params params))))
116 (out-file (if do-export
117 (or (cdr (assq :file params))
118 (error "No :file provided but :results set to file. For plain text output, set :results to verbatim"))
119 (org-babel-temp-file "plantuml-" ".txt")))
113120 (cmdline (cdr (assq :cmdline params)))
114121 (in-file (org-babel-temp-file "plantuml-"))
115122 (java (or (cdr (assq :java params)) ""))
116123 (executable (cond ((eq org-plantuml-exec-mode 'plantuml) org-plantuml-executable-path)
117124 (t "java")))
118 (executable-args (cond ((eq org-plantuml-exec-mode 'plantuml) org-plantuml-executable-args)
125 (executable-args (cond ((eq org-plantuml-exec-mode 'plantuml) org-plantuml-args)
119126 ((string= "" org-plantuml-jar-path)
120127 (error "`org-plantuml-jar-path' is not set"))
121128 ((not (file-exists-p org-plantuml-jar-path))
122129 (error "Could not find plantuml.jar at %s" org-plantuml-jar-path))
123 (t (list java
124 "-jar"
125 (shell-quote-argument (expand-file-name org-plantuml-jar-path))))))
130 (t `(,java
131 "-jar"
132 ,(shell-quote-argument (expand-file-name org-plantuml-jar-path))
133 ,@org-plantuml-args))))
126134 (full-body (org-babel-plantuml-make-body body params))
127135 (cmd (mapconcat #'identity
128136 (append
153161 (if (and (string= (file-name-extension out-file) "svg")
154162 org-babel-plantuml-svg-text-to-path)
155163 (org-babel-eval (format "inkscape %s -T -l %s" out-file out-file) ""))
156 nil)) ;; signal that output has already been written to file
164 (unless do-export (with-temp-buffer
165 (insert-file-contents out-file)
166 (buffer-substring-no-properties
167 (point-min) (point-max))))))
157168
158169 (defun org-babel-prep-session:plantuml (_session _params)
159170 "Return an error because plantuml does not support sessions."
00 ;;; ob-processing.el --- Babel functions for processing -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2015-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2015-2023 Free Software Foundation, Inc.
33
44 ;; Author: Jarmo Hurri (adapted from ob-asymptote.el written by Eric Schulte)
5 ;; Maintainer: Jarmo Hurri <jarmo.hurri@iki.fi>
56 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
78
89 ;; This file is part of GNU Emacs.
910
4950 ;; - Processing.js module :: https://processingjs.org/
5051
5152 ;;; Code:
53
54 (require 'org-macs)
55 (org-assert-version)
56
5257 (require 'ob)
5358 (require 'sha1)
5459
8792 ;; make-temp-file is repeated until no hyphen is in the
8893 ;; name; also sketch dir name must be the same as the
8994 ;; basename of the sketch file.
90 (let* ((temporary-file-directory org-babel-temporary-directory)
95 (let* ((temporary-file-directory (org-babel-temp-directory))
9196 (sketch-dir
9297 (let (sketch-dir-candidate)
9398 (while
00 ;;; ob-python.el --- Babel Functions for Python -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Eric Schulte
55 ;; Dan Davison
66 ;; Maintainer: Jack Kamm <jackkamm@gmail.com>
77 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: https://orgmode.org
8 ;; URL: https://orgmode.org
99
1010 ;; This file is part of GNU Emacs.
1111
2727 ;; Org-Babel support for evaluating python source code.
2828
2929 ;;; Code:
30
31 (require 'org-macs)
32 (org-assert-version)
33
3034 (require 'ob)
3135 (require 'org-macs)
3236 (require 'python)
3337
3438 (declare-function py-shell "ext:python-mode" (&rest args))
35 (declare-function py-toggle-shells "ext:python-mode" (arg))
39 (declare-function py-choose-shell "ext:python-mode" (&optional shell))
3640 (declare-function py-shell-send-string "ext:python-mode" (strg &optional process))
3741
3842 (defvar org-babel-tangle-lang-exts)
177181 (substring name 1 (- (length name) 1))
178182 name)))
179183
180 (defvar py-default-interpreter)
181184 (defvar py-which-bufname)
182185 (defvar python-shell-buffer-name)
186 (defvar-local org-babel-python--initialized nil
187 "Flag used to mark that python session has been initialized.")
183188 (defun org-babel-python-initiate-session-by-key (&optional session)
184189 "Initiate a python session.
185190 If there is not a current inferior-process-buffer in SESSION
197202 (let ((python-shell-buffer-name
198203 (org-babel-python-without-earmuffs py-buffer)))
199204 (run-python cmd)
200 (sleep-for 0 10)))
205 (with-current-buffer py-buffer
206 (add-hook
207 'python-shell-first-prompt-hook
208 (lambda ()
209 (setq-local org-babel-python--initialized t)
210 (message "I am running!!!"))
211 nil 'local))))
201212 ((and (eq 'python-mode org-babel-python-mode)
202213 (fboundp 'py-shell)) ; python-mode.el
203214 (require 'python-mode)
204215 ;; Make sure that py-which-bufname is initialized, as otherwise
205216 ;; it will be overwritten the first time a Python buffer is
206217 ;; created.
207 (py-toggle-shells py-default-interpreter)
218 (py-choose-shell)
208219 ;; `py-shell' creates a buffer whose name is the value of
209220 ;; `py-which-bufname' with '*'s at the beginning and end
210221 (let* ((bufname (if (and py-buffer (buffer-live-p py-buffer))
216227 (py-shell nil nil t org-babel-python-command py-buffer nil nil t nil)))
217228 (t
218229 (error "No function available for running an inferior Python")))
230 ;; Wait until Python initializes.
231 (if (eq 'python org-babel-python-mode) ; python.el
232 ;; This is more reliable compared to
233 ;; `org-babel-comint-wait-for-output' as python may emit
234 ;; multiple prompts during initialization.
235 (with-current-buffer py-buffer
236 (while (not org-babel-python--initialized)
237 (org-babel-comint-wait-for-output py-buffer)))
238 (org-babel-comint-wait-for-output py-buffer))
219239 (setq org-babel-python-buffers
220240 (cons (cons session py-buffer)
221241 (assq-delete-all session org-babel-python-buffers)))
00 ;;; ob-ref.el --- Babel Functions for Referencing External Data -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Eric Schulte
55 ;; Dan Davison
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
4848 ;; #+end_src
4949
5050 ;;; Code:
51
52 (require 'org-macs)
53 (org-assert-version)
54
5155 (require 'ob-core)
5256 (require 'org-macs)
5357 (require 'cl-lib)
5458
55 (declare-function org-babel-lob-get-info "ob-lob" (&optional datum))
56 (declare-function org-element-at-point "org-element" ())
59 (declare-function org-babel-lob-get-info "ob-lob" (&optional datum no-eval))
60 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
5761 (declare-function org-element-property "org-element" (property element))
5862 (declare-function org-element-type "org-element" (element))
5963 (declare-function org-end-of-meta-data "org" (&optional full))
6165 (declare-function org-id-find-id-file "org-id" (id))
6266 (declare-function org-id-find-id-in-file "org-id" (id file &optional markerp))
6367 (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
64 (declare-function org-narrow-to-subtree "org" ())
65 (declare-function org-show-context "org" (&optional key))
68 (declare-function org-narrow-to-subtree "org" (&optional element))
69 (declare-function org-fold-show-context "org-fold" (&optional key))
6670
6771 (defvar org-babel-update-intermediate nil
6872 "Update the in-buffer results of code blocks executed to resolve references.")
103107 (pop-to-buffer-same-window (marker-buffer m))
104108 (goto-char m)
105109 (move-marker m nil)
106 (org-show-context)
110 (org-fold-show-context)
107111 t))))
108112
109113 (defun org-babel-ref-headline-body ()
123127 (save-excursion
124128 (let ((case-fold-search t)
125129 args new-refere new-header-args new-referent split-file split-ref
126 index)
130 index contents)
127131 ;; if ref is indexed grab the indices -- beware nested indices
128 (when (and (string-match "\\[\\([^\\[]+\\)\\]$" ref)
132 (when (and (string-match "\\[\\([^\\[]*\\)\\]$" ref)
129133 (let ((str (substring ref 0 (match-beginning 0))))
130134 (= (cl-count ?\( str) (cl-count ?\) str))))
131 (setq index (match-string 1 ref))
135 (if (> (length (match-string 1 ref)) 0)
136 (setq index (match-string 1 ref))
137 (setq contents t))
132138 (setq ref (substring ref 0 (match-beginning 0))))
133139 ;; assign any arguments to pass to source block
134140 (when (string-match
152158 (setq ref split-ref))
153159 (org-with-wide-buffer
154160 (goto-char (point-min))
155 (let* ((params (append args '((:results . "silent"))))
161 (let* ((params (append args '((:results . "none"))))
156162 (regexp (org-babel-named-data-regexp-for-name ref))
157163 (result
158164 (catch :found
170176 (throw :found
171177 (org-babel-execute-src-block
172178 nil (org-babel-lob-get-info e) params)))
173 (`src-block
179 ((and `src-block (guard (not contents)))
174180 (throw :found
175181 (org-babel-execute-src-block
176182 nil nil
192198 (org-babel-execute-src-block nil info params))))
193199 (error "Reference `%s' not found in this buffer" ref))))
194200 (cond
195 ((symbolp result) (format "%S" result))
201 ((and result (symbolp result)) (format "%S" result))
196202 ((and index (listp result))
197203 (org-babel-ref-index-list index result))
198204 (t result)))))))))
00 ;;; ob-ruby.el --- Babel Functions for Ruby -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2828
2929 ;; - ruby and irb executables :: https://www.ruby-lang.org/
3030 ;;
31 ;; - ruby-mode :: Can be installed through ELPA, or from
32 ;; https://github.com/eschulte/rinari/raw/master/util/ruby-mode.el
31 ;; - ruby-mode :: Comes with Emacs.
3332 ;;
3433 ;; - inf-ruby mode :: Can be installed through ELPA, or from
35 ;; https://github.com/eschulte/rinari/raw/master/util/inf-ruby.el
34 ;; https://raw.githubusercontent.com/nonsequitur/inf-ruby/master/inf-ruby.el
3635
3736 ;;; Code:
37
38 (require 'org-macs)
39 (org-assert-version)
40
3841 (require 'ob)
3942 (require 'org-macs)
4043
00 ;;; ob-sass.el --- Babel Functions for the Sass CSS generation language -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
3737 ;; - sass-mode :: https://github.com/nex3/haml/blob/master/extra/sass-mode.el
3838
3939 ;;; Code:
40
41 (require 'org-macs)
42 (org-assert-version)
43
4044 (require 'ob)
4145
4246 (defvar org-babel-default-header-args:sass '())
00 ;;; ob-scheme.el --- Babel Functions for Scheme -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Eric Schulte
55 ;; Michael Gauland
66 ;; Keywords: literate programming, reproducible research, scheme
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
3737 ;; ELPA.
3838
3939 ;;; Code:
40
41 (require 'org-macs)
42 (org-assert-version)
43
4044 (require 'ob)
4145 (require 'geiser nil t)
4246 (require 'geiser-impl nil t)
5155 (defvar geiser-repl-window-allow-split) ; Defined in geiser-repl.el
5256
5357 (declare-function run-geiser "ext:geiser-repl" (impl))
58 (declare-function geiser "ext:geiser-repl" (impl))
5459 (declare-function geiser-mode "ext:geiser-mode" ())
5560 (declare-function geiser-eval-region "ext:geiser-mode"
5661 (start end &optional and-go raw nomsg))
62 (declare-function geiser-eval-region/wait "ext:geiser-mode"
63 (start end &optional timeout))
5764 (declare-function geiser-repl-exit "ext:geiser-repl" (&optional arg))
5865 (declare-function geiser-eval--retort-output "ext:geiser-eval" (ret))
5966 (declare-function geiser-eval--retort-result-str "ext:geiser-eval" (ret prefix))
113120 (let ((buffer (org-babel-scheme-get-session-buffer name)))
114121 (or buffer
115122 (progn
116 (run-geiser impl)
123 (if (fboundp 'geiser)
124 (geiser impl)
125 ;; Obsolete since Geiser 0.26.
126 (run-geiser impl))
117127 (when name
118128 (rename-buffer name t)
119129 (org-babel-scheme-set-session-buffer name (current-buffer)))
175185 (setq geiser-impl--implementation nil)
176186 (let ((geiser-debug-jump-to-debug-p nil)
177187 (geiser-debug-show-debug-p nil))
178 (let ((ret (geiser-eval-region (point-min) (point-max))))
188 ;; `geiser-eval-region/wait' was introduced to await the
189 ;; result of async evaluation in geiser version 0.22.
190 (let ((ret (funcall (if (fboundp 'geiser-eval-region/wait)
191 #'geiser-eval-region/wait
192 #'geiser-eval-region)
193 (point-min)
194 (point-max))))
179195 (setq result (if output
180196 (or (geiser-eval--retort-output ret)
181197 "Geiser Interpreter produced no output")
00 ;;; ob-screen.el --- Babel Support for Interactive Terminal -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Benjamin Andresen
5 ;; Maintainer: Ken Mankoff
5 ;; Maintainer: Ken Mankoff <mankoff@gmail.com>
66 ;; Keywords: literate programming, interactive shell
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
3333 ;; M-x org-babel-screen-test RET
3434
3535 ;;; Code:
36
37 (require 'org-macs)
38 (org-assert-version)
39
3640 (require 'ob)
3741
3842 (defvar org-babel-screen-location "screen"
00 ;;; ob-sed.el --- Babel Functions for Sed Scripts -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2015-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2015-2023 Free Software Foundation, Inc.
33
44 ;; Author: Bjarte Johansen
55 ;; Keywords: literate programming, reproducible research
3434 ;; In addition to the normal header arguments, ob-sed also provides
3535 ;; :cmd-line and :in-file. :cmd-line allows one to pass other flags to
3636 ;; the sed command like the "--in-place" flag which makes sed edit the
37 ;; file pass to it instead of outputting to standard out or to a
37 ;; file passed to it instead of outputting to standard out or to a
3838 ;; different file. :in-file is a header arguments that allows one to
3939 ;; tell Org Babel which file the sed script to act on.
4040
4141 ;;; Code:
42
43 (require 'org-macs)
44 (org-assert-version)
45
4246 (require 'ob)
4347
4448 (defvar org-babel-sed-command "sed"
6064 BODY is the source inside a sed source block and PARAMS is an
6165 association list over the source block configurations. This
6266 function is called by `org-babel-execute-src-block'."
63 (message "executing sed source code block")
67 (message "Executing sed source code block")
6468 (let* ((result-params (cdr (assq :result-params params)))
6569 (cmd-line (cdr (assq :cmd-line params)))
6670 (in-file (cdr (assq :in-file params)))
00 ;;; ob-shell.el --- Babel Functions for Shell Evaluation -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2525 ;; Org-Babel support for evaluating shell source code.
2626
2727 ;;; Code:
28
29 (require 'org-macs)
30 (org-assert-version)
31
2832 (require 'ob)
2933 (require 'org-macs)
3034 (require 'shell)
4044
4145 (defvar org-babel-default-header-args:shell '())
4246 (defvar org-babel-shell-names)
47
48 (defconst org-babel-shell-set-prompt-commands
49 '(;; Fish has no PS2 equivalent.
50 ("fish" . "function fish_prompt\n\techo \"%s\"\nend")
51 ;; prompt2 is like PS2 in POSIX shells.
52 ("csh" . "set prompt=\"%s\"\nset prompt2=\"\"")
53 ;; PowerShell, similar to fish, does not have PS2 equivalent.
54 ("posh" . "function prompt { \"%s\" }")
55 ;; PROMPT_COMMAND can override PS1 settings. Disable it.
56 ;; Disable PS2 to avoid garbage in multi-line inputs.
57 (t . "PROMPT_COMMAND=;PS1=\"%s\";PS2="))
58 "Alist assigning shells with their prompt setting command.
59
60 Each element of the alist associates a shell type from
61 `org-babel-shell-names' with a template used to create a command to
62 change the default prompt. The template is an argument to `format'
63 that will be called with a single additional argument: prompt string.
64
65 The fallback association template is defined in (t . \"template\")
66 alist element.")
67
68 (defvar org-babel-prompt-command)
4369
4470 (defun org-babel-shell-initialize ()
4571 "Define execution functions associated to shell names.
5076 (eval `(defun ,(intern (concat "org-babel-execute:" name))
5177 (body params)
5278 ,(format "Execute a block of %s commands with Babel." name)
53 (let ((shell-file-name ,name))
79 (let ((shell-file-name ,name)
80 (org-babel-prompt-command
81 (or (cdr (assoc ,name org-babel-shell-set-prompt-commands))
82 (alist-get t org-babel-shell-set-prompt-commands))))
5483 (org-babel-execute:shell body params))))
5584 (eval `(defalias ',(intern (concat "org-babel-variable-assignments:" name))
5685 'org-babel-variable-assignments:shell
6796 :group 'org-babel
6897 :type '(repeat (string :tag "Shell name: "))
6998 :set (lambda (symbol value)
70 (set-default symbol value)
99 (set-default-toplevel-value symbol value)
71100 (org-babel-shell-initialize)))
72101
73102 (defcustom org-babel-shell-results-defaults-to-output t
205234 (mapconcat echo-var var "\n"))
206235 (t (funcall echo-var var)))))
207236
237 (defvar org-babel-sh-eoe-indicator "echo 'org_babel_sh_eoe'"
238 "String to indicate that evaluation has completed.")
239 (defvar org-babel-sh-eoe-output "org_babel_sh_eoe"
240 "String to indicate that evaluation has completed.")
241 (defvar org-babel-sh-prompt "org_babel_sh_prompt> "
242 "String to set prompt in session shell.")
243
208244 (defun org-babel-sh-initiate-session (&optional session _params)
209245 "Initiate a session named SESSION according to PARAMS."
210246 (when (and session (not (string= session "none")))
212248 (or (org-babel-comint-buffer-livep session)
213249 (progn
214250 (shell session)
251 ;; Set unique prompt for easier analysis of the output.
252 (org-babel-comint-wait-for-output (current-buffer))
253 (org-babel-comint-input-command
254 (current-buffer)
255 (format org-babel-prompt-command org-babel-sh-prompt))
256 (setq-local comint-prompt-regexp
257 (concat "^" (regexp-quote org-babel-sh-prompt)
258 " *"))
215259 ;; Needed for Emacs 23 since the marker is initially
216260 ;; undefined and the filter functions try to use it without
217261 ;; checking.
218262 (set-marker comint-last-output-start (point))
219263 (get-buffer (current-buffer)))))))
220
221 (defvar org-babel-sh-eoe-indicator "echo 'org_babel_sh_eoe'"
222 "String to indicate that evaluation has completed.")
223 (defvar org-babel-sh-eoe-output "org_babel_sh_eoe"
224 "String to indicate that evaluation has completed.")
225264
226265 (defun org-babel-sh-evaluate (session body &optional params stdin cmdline)
227266 "Pass BODY to the Shell process in BUFFER.
248287 (set-file-modes script-file #o755)
249288 (with-temp-file stdin-file (insert (or stdin "")))
250289 (with-temp-buffer
251 (call-process-shell-command
252 (concat (if shebang script-file
253 (format "%s %s" shell-file-name script-file))
254 (and cmdline (concat " " cmdline)))
255 stdin-file
256 (current-buffer))
290 (with-connection-local-variables
291 (apply #'process-file
292 (if shebang (file-local-name script-file)
293 shell-file-name)
294 stdin-file
295 (current-buffer)
296 nil
297 (if shebang (when cmdline (list cmdline))
298 (list shell-command-switch
299 (concat (file-local-name script-file) " " cmdline)))))
257300 (buffer-string))))
258301 (session ; session evaluation
259302 (mapconcat
260303 #'org-babel-sh-strip-weird-long-prompt
261304 (mapcar
262305 #'org-trim
263 (butlast
306 (butlast ; Remove eoe indicator
264307 (org-babel-comint-with-output
265308 (session org-babel-sh-eoe-output t body)
266 (dolist (line (append (split-string (org-trim body) "\n")
267 (list org-babel-sh-eoe-indicator)))
268 (insert line)
269 (comint-send-input nil t)
270 (while (save-excursion
271 (goto-char comint-last-input-end)
272 (not (re-search-forward
273 comint-prompt-regexp nil t)))
274 (accept-process-output
275 (get-buffer-process (current-buffer))))))
276 2))
309 (insert (org-trim body) "\n"
310 org-babel-sh-eoe-indicator)
311 (comint-send-input nil t))
312 ;; Remove `org-babel-sh-eoe-indicator' output line.
313 1))
277314 "\n"))
278315 ;; External shell script, with or without a predefined
279316 ;; shebang.
287324 (set-file-modes script-file #o755)
288325 (org-babel-eval script-file "")))
289326 (t (org-babel-eval shell-file-name (org-trim body))))))
290 (when value-is-exit-status
327 (when (and results value-is-exit-status)
291328 (setq results (car (reverse (split-string results "\n" t)))))
292329 (when results
293330 (let ((result-params (cdr (assq :result-params params))))
00 ;;; ob-sql.el --- Babel Functions for SQL -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
5 ;; Maintainer: Daniel Kraus <daniel@kraus.my>
56 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
78
89 ;; This file is part of GNU Emacs.
910
6869 ;;
6970
7071 ;;; Code:
72
73 (require 'org-macs)
74 (org-assert-version)
75
7176 (require 'ob)
7277
7378 (declare-function org-table-import "org-table" (file arg))
217222 defined in `sql-connection-alist', otherwise look into PARAMS.
218223 See `sql-connection-alist' (part of SQL mode) for how to define
219224 database connections."
220 (if (assq :dbconnection params)
221 (let* ((dbconnection (cdr (assq :dbconnection params)))
222 (name-mapping '((:dbhost . sql-server)
223 (:dbport . sql-port)
224 (:dbuser . sql-user)
225 (:dbpassword . sql-password)
226 (:dbinstance . sql-dbinstance)
227 (:database . sql-database)))
228 (mapped-name (cdr (assq name name-mapping))))
229 (cadr (assq mapped-name
230 (cdr (assoc dbconnection sql-connection-alist)))))
231 (cdr (assq name params))))
225 (or (cdr (assq name params))
226 (and (assq :dbconnection params)
227 (let* ((dbconnection (cdr (assq :dbconnection params)))
228 (name-mapping '((:dbhost . sql-server)
229 (:dbport . sql-port)
230 (:dbuser . sql-user)
231 (:dbpassword . sql-password)
232 (:dbinstance . sql-dbinstance)
233 (:database . sql-database)))
234 (mapped-name (cdr (assq name name-mapping))))
235 (cadr (assq mapped-name
236 (cdr (assoc-string dbconnection sql-connection-alist t))))))))
232237
233238 (defun org-babel-execute:sql (body params)
234239 "Execute a block of Sql code with Babel.
00 ;;; ob-sqlite.el --- Babel Functions for SQLite Databases -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
5 ;; Maintainer: Nick Savage
5 ;; Maintainer: Nick Savage <nick@nicksavage.ca>
66 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88
99 ;; This file is part of GNU Emacs.
1010
2626 ;; Org-Babel support for evaluating sqlite source code.
2727
2828 ;;; Code:
29
30 (require 'org-macs)
31 (org-assert-version)
32
2933 (require 'ob)
3034 (require 'ob-sql)
3135
00 ;;; ob-table.el --- Support for Calling Babel Functions from Tables -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
5252 ;; are optional.
5353
5454 ;;; Code:
55
56 (require 'org-macs)
57 (org-assert-version)
58
5559 (require 'ob-core)
5660 (require 'org-macs)
5761
8387 #+end_src
8488
8589 NOTE: The quotation marks around the function name,
86 'source-block', are optional.
90 `source-block', are optional.
8791
8892 NOTE: By default, string variable names are interpreted as
8993 references to source-code blocks, to force interpretation of a
107111 ;; ensure that all cells prefixed with $'s are strings
108112 (cons (car var)
109113 (delq nil (mapcar
110 (lambda (el)
111 (if (eq '$ el)
112 (prog1 nil (setq quote t))
113 (prog1
114 (cond
115 (quote (format "\"%s\"" el))
116 ((stringp el) (org-no-properties el))
117 (t el))
118 (setq quote nil))))
119 (cdr var)))))
114 (lambda (el)
115 (if (eq '$ el)
116 (prog1 nil (setq quote t))
117 (prog1
118 (cond
119 (quote (format "\"%s\"" el))
120 ((stringp el) (org-no-properties el))
121 (t el))
122 (setq quote nil))))
123 (cdr var)))))
120124 variables)))
121125 (unless (stringp source-block)
122126 (setq source-block (symbol-name source-block)))
123 (let ((result
124 (if (and source-block (> (length source-block) 0))
125 (let ((params
126 ;; FIXME: Why `eval'?!?!?
127 (eval `(org-babel-parse-header-arguments
128 (concat
129 ":var results="
130 ,source-block
131 "[" ,header-args "]"
132 "("
133 (mapconcat
134 (lambda (var-spec)
135 (if (> (length (cdr var-spec)) 1)
136 (format "%S='%S"
137 (car var-spec)
138 (mapcar #'read (cdr var-spec)))
139 (format "%S=%s"
140 (car var-spec) (cadr var-spec))))
141 ',variables ", ")
142 ")")))))
143 (org-babel-execute-src-block
144 nil (list "emacs-lisp" "results" params)
145 '((:results . "silent"))))
146 "")))
147 (org-trim (if (stringp result) result (format "%S" result)))))))
127 `(let ((result
128 (if ,(and source-block (> (length source-block) 0))
129 (let ((params
130 ',(org-babel-parse-header-arguments
131 (concat
132 ":var results="
133 source-block
134 "[" header-args "]"
135 "("
136 (mapconcat
137 (lambda (var-spec)
138 (if (> (length (cdr var-spec)) 1)
139 (format "%S='%S"
140 (car var-spec)
141 (mapcar #'read (cdr var-spec)))
142 (format "%S=%s"
143 (car var-spec) (cadr var-spec))))
144 variables ", ")
145 ")"))))
146 (org-babel-execute-src-block
147 nil (list "emacs-lisp" "results" params)
148 '((:results . "silent"))))
149 "")))
150 (org-trim (if (stringp result) result (format "%S" result)))))))
148151
149152 (provide 'ob-table)
150153
00 ;;; ob-tangle.el --- Extract Source Code From Org Files -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2525 ;; Extract the code from source blocks out into raw source-code files.
2626
2727 ;;; Code:
28
29 (require 'org-macs)
30 (org-assert-version)
2831
2932 (require 'cl-lib)
3033 (require 'org-src)
3639 (declare-function org-babel-update-block-body "ob-core" (new-body))
3740 (declare-function org-back-to-heading "org" (&optional invisible-ok))
3841 (declare-function org-before-first-heading-p "org" ())
39 (declare-function org-element-at-point "org-element" ())
42 (declare-function org-element--cache-active-p "org-element" ())
43 (declare-function org-element-lineage "org-element" (datum &optional types with-self))
44 (declare-function org-element-property "org-element" (property element))
45 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
4046 (declare-function org-element-type "org-element" (element))
4147 (declare-function org-heading-components "org" ())
4248 (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
4349 (declare-function org-in-archived-heading-p "org" (&optional no-inheritance))
4450 (declare-function outline-previous-heading "outline" ())
45 (defvar org-id-link-to-org-use-id nil) ; Dynamically scoped
51 (defvar org-id-link-to-org-use-id) ; Dynamically scoped
52
53 (defgroup org-babel-tangle nil
54 "Options for extracting source code from code blocks."
55 :tag "Org Babel Tangle"
56 :group 'org-babel)
4657
4758 (defcustom org-babel-tangle-lang-exts
4859 '(("emacs-lisp" . "el")
6677
6778 (defcustom org-babel-post-tangle-hook nil
6879 "Hook run in code files tangled by `org-babel-tangle'."
69 :group 'org-babel
80 :group 'org-babel-tangle
7081 :version "24.1"
7182 :type 'hook)
7283
7384 (defcustom org-babel-pre-tangle-hook '(save-buffer)
74 "Hook run at the beginning of `org-babel-tangle'."
75 :group 'org-babel
85 "Hook run at the beginning of `org-babel-tangle' in the original buffer."
86 :group 'org-babel-tangle
7687 :version "24.1"
7788 :type 'hook)
7889
7990 (defcustom org-babel-tangle-body-hook nil
8091 "Hook run over the contents of each code block body."
81 :group 'org-babel
92 :group 'org-babel-tangle
8293 :version "24.1"
94 :type 'hook)
95
96 (defcustom org-babel-tangle-finished-hook nil
97 "Hook run at the very end of `org-babel-tangle' in the original buffer.
98 In this way, it is the counterpart to `org-babel-pre-tangle-hook'."
99 :group 'org-babel-tangle
100 :package-version '(Org . "9.6")
83101 :type 'hook)
84102
85103 (defcustom org-babel-tangle-comment-format-beg "[[%link][%source-name]]"
98116
99117 Whether or not comments are inserted during tangling is
100118 controlled by the :comments header argument."
101 :group 'org-babel
119 :group 'org-babel-tangle
102120 :version "24.1"
103121 :type 'string)
104122
118136
119137 Whether or not comments are inserted during tangling is
120138 controlled by the :comments header argument."
121 :group 'org-babel
139 :group 'org-babel-tangle
122140 :version "24.1"
123141 :type 'string)
124142
127145 of tangle comments. Use `org-babel-tangle-comment-format-beg'
128146 and `org-babel-tangle-comment-format-end' to customize the format
129147 of tangled comments."
130 :group 'org-babel
148 :group 'org-babel-tangle
131149 :type 'boolean)
132150
133151 (defcustom org-babel-process-comment-text 'org-remove-indentation
135153 inserted as comments in tangled source-code files. The function
136154 should take a single string argument and return a string
137155 result. The default value is `org-remove-indentation'."
138 :group 'org-babel
156 :group 'org-babel-tangle
139157 :version "24.1"
140158 :type 'function)
159
160 (defcustom org-babel-tangle-default-file-mode #o644
161 "The default mode used for tangled files, as an integer.
162 The default value 420 correspands to the octal #o644, which is
163 read-write permissions for the user, read-only for everyone else."
164 :group 'org-babel-tangle
165 :package-version '(Org . "9.6")
166 :type 'integer)
141167
142168 (defun org-babel-find-file-noselect-refresh (file)
143169 "Find file ensuring that the latest changes on disk are
176202 Optional argument LANG-RE can be used to limit the exported
177203 source code blocks by languages matching a regular expression.
178204
179 Return a list whose CAR is the tangled file name."
205 Return list of the tangled file names."
180206 (interactive "fFile to tangle: \nP")
181207 (let* ((visited (find-buffer-visiting file))
182208 (buffer (or visited (find-file-noselect file))))
198224 (defun org-babel-tangle (&optional arg target-file lang-re)
199225 "Write code blocks to source-specific files.
200226 Extract the bodies of all source code blocks from the current
201 file into their own source-specific files.
227 file into their own source-specific files. Return the list of files.
202228 With one universal prefix argument, only tangle the block at point.
203229 When two universal prefix arguments, only tangle blocks for the
204230 tangle file of the block at point.
224250 org-babel-default-header-args))
225251 (tangle-file
226252 (when (equal arg '(16))
227 (or (cdr (assq :tangle (nth 2 (org-babel-get-src-block-info 'light))))
253 (or (cdr (assq :tangle (nth 2 (org-babel-get-src-block-info 'no-eval))))
228254 (user-error "Point is not in a source code block"))))
229255 path-collector)
230256 (mapc ;; map over file-names
253279 (when she-bang
254280 (unless tangle-mode (setq tangle-mode #o755)))
255281 (when tangle-mode
256 (add-to-list 'modes tangle-mode))
282 (add-to-list 'modes (org-babel-interpret-file-mode tangle-mode)))
257283 ;; Possibly create the parent directories for file.
258284 (let ((m (funcall get-spec :mkdirp)))
259285 (and m fnd (not (string= m "no"))
270296 lspecs)
271297 (when make-dir
272298 (make-directory fnd 'parents))
273 ;; erase previous file
274 (when (file-exists-p file-name)
275 (delete-file file-name))
276 (write-region nil nil file-name)
277 (mapc (lambda (mode) (set-file-modes file-name mode)) modes)
299 (unless
300 (and (file-exists-p file-name)
301 (let ((tangle-buf (current-buffer)))
302 (with-temp-buffer
303 (insert-file-contents file-name)
304 (and
305 (equal (buffer-size)
306 (buffer-size tangle-buf))
307 (= 0
308 (let (case-fold-search)
309 (compare-buffer-substrings
310 nil nil nil
311 tangle-buf nil nil)))))))
312 ;; erase previous file
313 (when (file-exists-p file-name)
314 (delete-file file-name))
315 (write-region nil nil file-name)
316 (mapc (lambda (mode) (set-file-modes file-name mode)) modes))
278317 (push file-name path-collector))))))
279318 (if (equal arg '(4))
280319 (org-babel-tangle-single-block 1 t)
294333 (org-babel-with-temp-filebuffer file
295334 (run-hooks 'org-babel-post-tangle-hook)))
296335 path-collector))
336 (run-hooks 'org-babel-tangle-finished-hook)
297337 path-collector))))
338
339 (defun org-babel-interpret-file-mode (mode)
340 "Determine the integer representation of a file MODE specification.
341 The following forms are currently recognized:
342 - an integer (returned without modification)
343 - \"o755\" (chmod style octal)
344 - \"rwxrw-r--\" (ls style specification)
345 - \"a=rw,u+x\" (chmod style) *
346
347 * The interpretation of these forms relies on `file-modes-symbolic-to-number',
348 and uses `org-babel-tangle-default-file-mode' as the base mode."
349 (cond
350 ((integerp mode)
351 (if (string-match-p "^[0-7][0-7][0-7]$" (format "%o" mode))
352 mode
353 (user-error "%1$o is not a valid file mode octal. \
354 Did you give the decimal value %1$d by mistake?" mode)))
355 ((not (stringp mode))
356 (error "File mode %S not recognized as a valid format." mode))
357 ((string-match-p "^o0?[0-7][0-7][0-7]$" mode)
358 (string-to-number (replace-regexp-in-string "^o" "" mode) 8))
359 ((string-match-p "^[ugoa]*\\(?:[+-=][rwxXstugo]*\\)+\\(,[ugoa]*\\(?:[+-=][rwxXstugo]*\\)+\\)*$" mode)
360 ;; Match regexp taken from `file-modes-symbolic-to-number'.
361 (file-modes-symbolic-to-number mode org-babel-tangle-default-file-mode))
362 ((string-match-p "^[r-][w-][xs-][r-][w-][xs-][r-][w-][x-]$" mode)
363 (file-modes-symbolic-to-number (concat "u=" (delete ?- (substring mode 0 3))
364 ",g=" (delete ?- (substring mode 3 6))
365 ",o=" (delete ?- (substring mode 6 9)))
366 0))
367 (t (error "File mode %S not recognized as a valid format. See `org-babel-interpret-file-mode'." mode))))
298368
299369 (defun org-babel-tangle-clean ()
300370 "Remove comments inserted by `org-babel-tangle'.
386456 (let ((counter 0) last-heading-pos blocks)
387457 (org-babel-map-src-blocks (buffer-file-name)
388458 (let ((current-heading-pos
389 (org-with-wide-buffer
390 (org-with-limited-levels (outline-previous-heading)))))
459 (if (org-element--cache-active-p)
460 (or (org-element-property :begin (org-element-lineage (org-element-at-point) '(headline) t)) 1)
461 (org-with-wide-buffer
462 (org-with-limited-levels (outline-previous-heading))))))
391463 (if (eq last-heading-pos current-heading-pos) (cl-incf counter)
392464 (setq counter 1)
393465 (setq last-heading-pos current-heading-pos)))
394466 (unless (or (org-in-commented-heading-p)
395467 (org-in-archived-heading-p))
396 (let* ((info (org-babel-get-src-block-info 'light))
468 (let* ((info (org-babel-get-src-block-info 'no-eval))
397469 (src-lang (nth 0 info))
398470 (src-tfile (cdr (assq :tangle (nth 2 info)))))
399471 (unless (or (string= src-tfile "no")
412484 (mapcar (lambda (b) (cons (car b) (nreverse (cdr b))))
413485 (nreverse blocks))))
414486
487 (defun org-babel-tangle--unbracketed-link (params)
488 "Get a raw link to the src block at point, without brackets.
489
490 The PARAMS are the 3rd element of the info for the same src block."
491 (unless (string= "no" (cdr (assq :comments params)))
492 (save-match-data
493 (let* (;; The created link is transient. Using ID is not necessary,
494 ;; but could have side-effects if used. An ID property may
495 ;; be added to existing entries thus creating unexpected file
496 ;; modifications.
497 (org-id-link-to-org-use-id nil)
498 (l (org-no-properties
499 (cl-letf (((symbol-function 'org-store-link-functions)
500 (lambda () nil)))
501 (org-store-link nil))))
502 (bare (and l
503 (string-match org-link-bracket-re l)
504 (match-string 1 l))))
505 (when bare
506 (if (and org-babel-tangle-use-relative-file-links
507 (string-match org-link-types-re bare)
508 (string= (match-string 1 bare) "file"))
509 (concat "file:"
510 (file-relative-name (substring bare (match-end 0))
511 (file-name-directory
512 (cdr (assq :tangle params)))))
513 bare))))))
514
515 (defvar org-outline-regexp) ; defined in lisp/org.el
415516 (defun org-babel-tangle-single-block (block-counter &optional only-this-block)
416517 "Collect the tangled source for current block.
417518 Return the list of block attributes needed by
428529 (extra (nth 3 info))
429530 (coderef (nth 6 info))
430531 (cref-regexp (org-src-coderef-regexp coderef))
431 (link (let* (
432 ;; The created link is transient. Using ID is
433 ;; not necessary, but could have side-effects if
434 ;; used. An ID property may be added to
435 ;; existing entries thus creatin unexpected file
436 ;; modifications.
437 (org-id-link-to-org-use-id nil)
438 (l (org-no-properties (org-store-link nil))))
439 (and (string-match org-link-bracket-re l)
440 (match-string 1 l))))
532 (link (org-babel-tangle--unbracketed-link params))
441533 (source-name
442534 (or (nth 4 info)
443535 (format "%s:%d"
450542 (body
451543 ;; Run the tangle-body-hook.
452544 (let ((body (if (org-babel-noweb-p params :tangle)
453 (org-babel-expand-noweb-references info)
545 (if (string= "strip-tangle" (cdr (assq :noweb (nth 2 info))))
546 (replace-regexp-in-string (org-babel-noweb-wrap) "" (nth 1 info))
547 (org-babel-expand-noweb-references info))
454548 (nth 1 info))))
455549 (with-temp-buffer
456550 (insert
476570 (buffer-substring
477571 (max (condition-case nil
478572 (save-excursion
479 (org-back-to-heading t) ; Sets match data
480 (match-end 0))
573 (org-back-to-heading t)
574 (re-search-forward org-outline-regexp))
481575 (error (point-min)))
482576 (save-excursion
483577 (if (re-search-backward
485579 (match-end 0)
486580 (point-min))))
487581 (point)))))
582 (src-tfile (cdr (assq :tangle params)))
488583 (result
489584 (list start-line
490585 (if org-babel-tangle-use-relative-file-links
491586 (file-relative-name file)
492587 file)
493 (if (and org-babel-tangle-use-relative-file-links
494 (string-match org-link-types-re link)
495 (string= (match-string 1 link) "file"))
496 (concat "file:"
497 (file-relative-name (substring link (match-end 0))
498 (file-name-directory
499 (cdr (assq :tangle params)))))
500 link)
588 link
501589 source-name
502590 params
503591 (if org-src-preserve-indentation
505593 (org-trim (org-remove-indentation body)))
506594 comment)))
507595 (if only-this-block
508 (let* ((src-tfile (cdr (assq :tangle (nth 4 result))))
509 (file-name (org-babel-effective-tangled-filename
596 (let* ((file-name (org-babel-effective-tangled-filename
510597 (nth 1 result) src-lang src-tfile)))
511598 (list (cons file-name (list (cons src-lang result)))))
512599 result)))
515602 "Return a list of begin and end link comments for the code block at point.
516603 INFO, when non nil, is the source block information, as returned
517604 by `org-babel-get-src-block-info'."
518 (let ((link-data (pcase (or info (org-babel-get-src-block-info 'light))
519 (`(,_ ,_ ,_ ,_ ,name ,start ,_)
605 (let ((link-data (pcase (or info (org-babel-get-src-block-info 'no-eval))
606 (`(,_ ,_ ,params ,_ ,name ,start ,_)
520607 `(("start-line" . ,(org-with-point-at start
521608 (number-to-string
522609 (line-number-at-pos))))
523610 ("file" . ,(buffer-file-name))
524 ("link" . ,(let (;; The created link is transient. Using ID is
525 ;; not necessary, but could have side-effects if
526 ;; used. An ID property may be added to
527 ;; existing entries thus creatin unexpected file
528 ;; modifications.
529 (org-id-link-to-org-use-id nil))
530 (org-no-properties (org-store-link nil))))
611 ("link" . ,(org-babel-tangle--unbracketed-link params))
531612 ("source-name" . ,name))))))
532613 (list (org-fill-template org-babel-tangle-comment-format-beg link-data)
533614 (org-fill-template org-babel-tangle-comment-format-end link-data))))
580661 (error "Not in tangled code"))
581662 (setq body (buffer-substring body-start end)))
582663 ;; Go to the beginning of the relative block in Org file.
583 (org-link-open-from-string link)
664 ;; Explicitly allow fuzzy search even if user customized
665 ;; otherwise.
666 (let (org-link-search-must-match-exact-headline)
667 (org-link-open-from-string link))
584668 (setq target-buffer (current-buffer))
585669 (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name)
586670 (let ((n (string-to-number (match-string 1 block-name))))
00 ;;; ob.el --- Working with Code Blocks in Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Eric Schulte
55 ;; Keywords: literate programming, reproducible research
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2121 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
2222
2323 ;;; Code:
24
25 (require 'org-macs)
26 (org-assert-version)
27
2428 (require 'org-macs)
2529 (require 'org-compat)
2630 (require 'org-keys)
00 ;;; oc-basic.el --- basic back-end for citations -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55
6565
6666 ;;; Code:
6767
68 (require 'org-macs)
69 (org-assert-version)
70
6871 (require 'bibtex)
6972 (require 'json)
7073 (require 'map)
7275 (require 'seq)
7376
7477 (declare-function org-open-at-point "org" (&optional arg))
78 (declare-function org-open-file "org" (path &optional in-emacs line search))
7579
7680 (declare-function org-element-interpret-data "org-element" (data))
7781 (declare-function org-element-property "org-element" (property element))
157161 (puthash (cdr (assq 'id item))
158162 (mapcar (pcase-lambda (`(,field . ,value))
159163 (pcase field
160 ('author
161 ;; Author is an array of objects, each
162 ;; of them designing a person. These
163 ;; objects may contain multiple
164 ;; properties, but for this basic
165 ;; processor, we'll focus on `given' and
166 ;; `family'.
164 ((or 'author 'editors)
165 ;; Author and editors are arrays of
166 ;; objects, each of them designing a
167 ;; person. These objects may contain
168 ;; multiple properties, but for this
169 ;; basic processor, we'll focus on
170 ;; `given' and `family'.
167171 ;;
168172 ;; For compatibility with BibTeX, add
169 ;; "and" between authors.
170 (cons 'author
173 ;; "and" between authors and editors.
174 (cons field
171175 (mapconcat
172176 (lambda (alist)
173177 (concat (alist-get 'family alist)
177181 " and ")))
178182 ('issued
179183 ;; Date are expressed as an array
180 ;; (`date-parts') or a "string (`raw').
181 ;; In both cases, extract the year and
182 ;; associate it to `year' field, for
183 ;; compatibility with BibTeX format.
184 ;; (`date-parts') or a "string (`raw'
185 ;; or `literal'). In both cases,
186 ;; extract the year and associate it
187 ;; to `year' field, for compatibility
188 ;; with BibTeX format.
184189 (let ((date (or (alist-get 'date-parts value)
190 (alist-get 'literal value)
185191 (alist-get 'raw value))))
186192 (cons 'year
187193 (cond
188194 ((consp date)
189 (caar date))
195 (let ((year (caar date)))
196 (cond
197 ((numberp year) (number-to-string year))
198 ((stringp year) year)
199 (t
200 (error
201 "First element of CSL-JSON date-parts should be a number or string, got %s: %S"
202 (type-of year) year)))))
190203 ((stringp date)
191 (car (split-string date "-")))
204 (replace-regexp-in-string
205 (rx
206 (minimal-match (zero-or-more anything))
207 (group-n 1 (repeat 4 digit))
208 (zero-or-more anything))
209 (rx (backref 1))
210 date))
192211 (t
193212 (error "Unknown CSL-JSON date format: %S"
194 date))))))
213 value))))))
195214 (_
196215 (cons field value))))
197216 item)
205224 (let ((entries (make-hash-table :test #'equal))
206225 (bibtex-sort-ignore-string-entries t))
207226 (bibtex-set-dialect dialect t)
227 ;; Throw an error if bibliography is malformed.
228 (unless (bibtex-validate)
229 (user-error "Malformed bibliography at %S"
230 (or (buffer-file-name) (current-buffer))))
208231 (bibtex-map-entries
209232 (lambda (key &rest _)
210233 ;; Normalize entries: field names are turned into symbols
220243 (cons
221244 (intern (downcase field))
222245 (replace-regexp-in-string "[ \t\n]+" " " value)))))
223 (bibtex-parse-entry t))
246 ;; Parse, substituting the @string replacements.
247 ;; See Emacs bug#56475 discussion.
248 (let ((bibtex-string-files `(,(buffer-file-name)))
249 (bibtex-expand-strings t))
250 (bibtex-parse-entry t)))
224251 entries)))
225252 entries))
226253
254 (defvar org-cite-basic--file-id-cache nil
255 "Hash table linking files to their hash.")
227256 (defun org-cite-basic--parse-bibliography (&optional info)
228257 "List all entries available in the buffer.
229258
236265 as symbols, and values as strings or nil.
237266
238267 Optional argument INFO is the export state, as a property list."
268 (unless (hash-table-p org-cite-basic--file-id-cache)
269 (setq org-cite-basic--file-id-cache (make-hash-table :test #'equal)))
239270 (if (plist-member info :cite-basic/bibliography)
240271 (plist-get info :cite-basic/bibliography)
241272 (let ((results nil))
242273 (dolist (file (org-cite-list-bibliography-files))
243274 (when (file-readable-p file)
244275 (with-temp-buffer
245 (insert-file-contents file)
246 (let* ((file-id (cons file (org-buffer-hash)))
247 (entries
248 (or (cdr (assoc file-id org-cite-basic--bibliography-cache))
249 (let ((table
250 (pcase (file-name-extension file)
251 ("json" (org-cite-basic--parse-json))
252 ("bib" (org-cite-basic--parse-bibtex 'biblatex))
253 ("bibtex" (org-cite-basic--parse-bibtex 'BibTeX))
254 (ext
255 (user-error "Unknown bibliography extension: %S"
256 ext)))))
257 (push (cons file-id table) org-cite-basic--bibliography-cache)
258 table))))
259 (push (cons file entries) results)))))
276 (when (or (org-file-has-changed-p file)
277 (not (gethash file org-cite-basic--file-id-cache)))
278 (insert-file-contents file)
279 (set-visited-file-name file t)
280 (puthash file (org-buffer-hash) org-cite-basic--file-id-cache))
281 (condition-case nil
282 (unwind-protect
283 (let* ((file-id (cons file (gethash file org-cite-basic--file-id-cache)))
284 (entries
285 (or (cdr (assoc file-id org-cite-basic--bibliography-cache))
286 (let ((table
287 (pcase (file-name-extension file)
288 ("json" (org-cite-basic--parse-json))
289 ("bib" (org-cite-basic--parse-bibtex 'biblatex))
290 ("bibtex" (org-cite-basic--parse-bibtex 'BibTeX))
291 (ext
292 (user-error "Unknown bibliography extension: %S"
293 ext)))))
294 (push (cons file-id table) org-cite-basic--bibliography-cache)
295 table))))
296 (push (cons file entries) results))
297 (set-visited-file-name nil t))
298 (error (setq org-cite-basic--file-id-cache nil))))))
260299 (when info (plist-put info :cite-basic/bibliography results))
261300 results)))
262301
309348 (org-export-raw-string value)
310349 value)))
311350
351 (defun org-cite-basic--shorten-names (names)
352 "Return a list of family names from a list of full NAMES.
353
354 To better accomomodate corporate names, this will only shorten
355 personal names of the form \"family, given\"."
356 (when (stringp names)
357 (mapconcat
358 (lambda (name)
359 (if (eq 1 (length name))
360 (cdr (split-string name))
361 (car (split-string name ", "))))
362 (split-string names " and ")
363 ", ")))
364
312365 (defun org-cite-basic--number-to-suffix (n)
313366 "Compute suffix associated to number N.
314367 This is used for disambiguation."
325378 ((= n 27) (throw :complete (cons 0 (cons 0 result))))
326379 (t nil))))))))
327380
381 (defun org-cite-basic--get-author (entry-or-key &optional info raw)
382 "Return author associated to ENTRY-OR-KEY.
383
384 ENTRY-OR-KEY, INFO and RAW arguments are the same arguments as
385 used in `org-cite-basic--get-field', which see.
386
387 Author is obtained from the \"author\" field, if available, or
388 from the \"editor\" field otherwise."
389 (or (org-cite-basic--get-field 'author entry-or-key info raw)
390 (org-cite-basic--get-field 'editor entry-or-key info raw)))
391
328392 (defun org-cite-basic--get-year (entry-or-key info &optional no-suffix)
329393 "Return year associated to ENTRY-OR-KEY.
330394
348412 ;; KEY-SUFFIX-ALIST is an association (KEY . SUFFIX), where KEY is
349413 ;; the cite key, as a string, and SUFFIX is the generated suffix
350414 ;; string, or the empty string.
351 (let* ((author (org-cite-basic--get-field 'author entry-or-key info 'raw))
415 (let* ((author (org-cite-basic--get-author entry-or-key info 'raw))
352416 (year
353417 (or (org-cite-basic--get-field 'year entry-or-key info 'raw)
354418 (let ((date
384448 "Format ENTRY according to STYLE string.
385449 ENTRY is an alist, as returned by `org-cite-basic--get-entry'.
386450 Optional argument INFO is the export state, as a property list."
387 (let ((author (org-cite-basic--get-field 'author entry info))
451 (let ((author (org-cite-basic--get-author entry info))
388452 (title (org-cite-basic--get-field 'title entry info))
389453 (from
390454 (or (org-cite-basic--get-field 'publisher entry info)
395459 ("plain"
396460 (let ((year (org-cite-basic--get-year entry info 'no-suffix)))
397461 (org-cite-concat
398 author ". " title (and from (list ", " from)) ", " year ".")))
462 (org-cite-basic--shorten-names author) ". "
463 title (and from (list ", " from)) ", " year ".")))
399464 ("numeric"
400465 (let ((n (org-cite-basic--key-number (cdr (assq 'id entry)) info))
401466 (year (org-cite-basic--get-year entry info 'no-suffix)))
436501 (_
437502 (lambda ()
438503 (interactive)
439 (setf (buffer-substring beg end)
440 (concat "@"
441 (if (= 1 (length suggestions))
442 (car suggestions)
443 (completing-read "Did you mean: "
444 suggestions nil t))))))))
504 (save-excursion
505 (goto-char beg)
506 (delete-region beg end)
507 (insert
508 "@"
509 (if (= 1 (length suggestions))
510 (car suggestions)
511 (completing-read "Did you mean: "
512 suggestions nil t))))))))
445513 (put-text-property beg end 'keymap km)))
446514
447515 (defun org-cite-basic-activate (citation)
511579 (suffix (org-element-property :suffix ref)))
512580 (funcall format-ref
513581 prefix
514 (org-cite-basic--get-field 'author k info)
582 (org-cite-basic--get-author k info)
515583 (org-cite-basic--get-year k info)
516584 suffix)))
517585 (org-cite-get-references citation)
550618 INFO is the export state, as a property list."
551619 (and field
552620 (lambda (a b)
553 (org-string-collate-lessp
621 (string-collate-lessp
554622 (org-cite-basic--get-field field a info 'raw)
555623 (org-cite-basic--get-field field b info 'raw)
556624 nil t))))
583651 (org-export-data
584652 (mapconcat
585653 (lambda (key)
586 (let ((author (org-cite-basic--get-field 'author key info)))
654 (let ((author (org-cite-basic--get-author key info)))
587655 (if caps (capitalize author) author)))
588656 (org-cite-get-references citation t)
589657 org-cite-basic-author-year-separator)
644712 style, as a string. BACKEND is the export back-end, as a symbol. INFO is the
645713 export state, as a property list."
646714 (mapconcat
647 (lambda (k)
648 (let ((entry (org-cite-basic--get-entry k info)))
649 (org-export-data
650 (org-cite-make-paragraph
651 (and (org-export-derived-backend-p backend 'latex)
652 (org-export-raw-string "\\noindent\n"))
653 (org-cite-basic--print-entry entry style info))
654 info)))
655 (org-cite-basic--sort-keys keys info)
715 (lambda (entry)
716 (org-export-data
717 (org-cite-make-paragraph
718 (and (org-export-derived-backend-p backend 'latex)
719 (org-export-raw-string "\\noindent\n"))
720 (org-cite-basic--print-entry entry style info))
721 info))
722 (delq nil
723 (mapcar
724 (lambda (k) (org-cite-basic--get-entry k info))
725 (org-cite-basic--sort-keys keys info)))
656726 "\n"))
657727
658728
718788 (t
719789 (clrhash org-cite-basic--completion-cache)
720790 (dolist (key (org-cite-basic--all-keys))
721 (let ((completion
722 (concat
723 (let ((author (org-cite-basic--get-field 'author key nil t)))
724 (if author
725 (truncate-string-to-width
726 (replace-regexp-in-string " and " "; " author)
727 org-cite-basic-author-column-end nil ?\s)
728 (make-string org-cite-basic-author-column-end ?\s)))
729 org-cite-basic-column-separator
730 (let ((date (org-cite-basic--get-year key nil 'no-suffix)))
731 (format "%4s" (or date "")))
732 org-cite-basic-column-separator
733 (org-cite-basic--get-field 'title key nil t))))
791 (let* ((entry (org-cite-basic--get-entry
792 key
793 ;; Supply pre-calculated bibliography to avoid
794 ;; performance degradation.
795 (list :cite-basic/bibliography entries)))
796 (completion
797 (concat
798 (let ((author (org-cite-basic--get-author entry nil 'raw)))
799 (if author
800 (truncate-string-to-width
801 (replace-regexp-in-string " and " "; " author)
802 org-cite-basic-author-column-end nil ?\s)
803 (make-string org-cite-basic-author-column-end ?\s)))
804 org-cite-basic-column-separator
805 (let ((date (org-cite-basic--get-year entry nil 'no-suffix)))
806 (format "%4s" (or date "")))
807 org-cite-basic-column-separator
808 (org-cite-basic--get-field 'title entry nil t))))
734809 (puthash completion key org-cite-basic--completion-cache)))
735810 (unless (map-empty-p org-cite-basic--completion-cache) ;no key
736811 (puthash entries t org-cite-basic--completion-cache)
00 ;;; oc-biblatex.el --- biblatex citation processor for Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55
4040 ;;
4141 ;; - author (a), including caps (c), full (f) and caps-full (cf) variants,
4242 ;; - locators (l), including bare (b), caps (c) and bare-caps (bc) variants,
43 ;; - noauthor (na),
43 ;; - noauthor (na), including bare (b) variant,
4444 ;; - nocite (n),
4545 ;; - text (t), including caps (c) variant,
4646 ;; - default style, including bare (b), caps (c) and bare-caps (bc) variants.
6161 ;; #+print_bibliography: :keyword abc,xyz :title "Primary Sources"
6262
6363 ;;; Code:
64
65 (require 'org-macs)
66 (org-assert-version)
67
68 (require 'map)
6469 (require 'org-macs)
6570 (require 'oc)
6671
6772 (declare-function org-element-property "org-element" (property element))
6873 (declare-function org-export-data "org-export" (data info))
69 (declare-function org-export-get-next-element "org-export" (blob info &optional n))
7074
7175
7276 ;;; Customization
8084 (string :tag "Options (key=value,key2=value2...)")
8185 (const :tag "No option" nil))
8286 :safe #'string-or-null-p)
87
88 (defcustom org-cite-biblatex-styles
89 '(("author" "caps" "Citeauthor*" nil nil)
90 ("author" "full" "citeauthor" nil nil)
91 ("author" "caps-full" "Citeauthor" nil nil)
92 ("author" nil "citeauthor*" nil nil)
93 ("locators" "bare" "notecite" nil nil)
94 ("locators" "caps" "Pnotecite" nil nil)
95 ("locators" "bare-caps" "Notecite" nil nil)
96 ("locators" nil "pnotecite" nil nil)
97 ("noauthor" "bare" "cite*" nil nil)
98 ("noauthor" nil "autocite*" nil nil)
99 ("nocite" nil "nocite" nil t)
100 ("text" "caps" "Textcite" "Textcites" nil)
101 ("text" nil "textcite" "textcites" nil)
102 (nil "bare" "cite" "cites" nil)
103 (nil "caps" "Autocite" "Autocites" nil)
104 (nil "bare-caps" "Cite" "Cites" nil)
105 (nil nil "autocite" "autocites" nil))
106 "List of styles and variants, with associated BibLaTeX commands.
107
108 Each style follows the pattern
109
110 (NAME VARIANT COMMAND MULTI-COMMAND NO-OPTION)
111
112 where:
113
114 NAME is the name of the style, as a string, or nil. The nil
115 style is the default style. As such, it must have an entry in
116 the list.
117
118 VARIANT is the name of the style variant, as a string or nil.
119 The nil variant is the default variant for the current style.
120 As such, each style name must be associated to a nil variant.
121
122 COMMAND is the LaTeX command to use, as a string. It should
123 not contain the leading backslash character.
124
125 MULTI-COMMAND is the LaTeX command to use when a multi-cite
126 command is appropriate. When nil, the style is deemed
127 inappropriate for multi-cites. The command should not contain
128 the leading backslash character.
129
130 NO-OPTION is a boolean. When non-nil, no optional argument
131 should be added to the LaTeX command.
132
133 Each NAME-VARIANT pair should be unique in the list.
134
135 It is also possible to provide shortcuts for style and variant
136 names. See `org-cite-biblatex-style-shortcuts'."
137 :group 'org-cite
138 :package-version '(Org . "9.6")
139 :type '(repeat
140 (list :tag "Style/variant combination"
141 ;; Name part.
142 (choice :tag "Style"
143 (string :tag "Name")
144 (const :tag "Default style" nil))
145 ;; Variant part.
146 (choice :tag "Variant"
147 (string :tag "Name")
148 (const :tag "Default variant" nil))
149 ;; Command part.
150 (string :tag "Command name")
151 (choice :tag "Multicite command"
152 (string :tag "Command name")
153 (const :tag "No multicite support" nil))
154 (choice :tag "Skip optional arguments"
155 (const :tag "Yes" t)
156 (const :tag "No" nil)))))
157
158 (defcustom org-cite-biblatex-style-shortcuts
159 '(("a" . "author")
160 ("b" . "bare")
161 ("bc" . "bare-caps")
162 ("c" . "caps")
163 ("cf" . "caps-full")
164 ("f" . "full")
165 ("l" . "locators")
166 ("n" . "nocite")
167 ("na" . "noauthor")
168 ("t" . "text"))
169 "List of shortcuts associated to style or variant names.
170
171 Each entry is a pair (NAME . STYLE-NAME) where NAME is the name
172 of the shortcut, as a string, and STYLE-NAME is the name of
173 a style in `org-cite-biblatex-styles'."
174 :group 'org-cite
175 :package-version '(Org . "9.6")
176 :type '(repeat
177 (cons :tag "Shortcut"
178 (string :tag "Name")
179 (string :tag "Full name")))
180 :safe t)
83181
84182
85183 ;;; Internal functions
163261 (mapconcat (lambda (r)
164262 (org-cite-biblatex--atomic-arguments (list r) info))
165263 (org-cite-get-references citation)
166 "")
167 ;; According to BibLaTeX manual, left braces or brackets
168 ;; following a multicite command could be parsed as other
169 ;; arguments. So we stop any further parsing by inserting
170 ;; a \relax unconditionally.
171 "\\relax")))
172
173 (defun org-cite-biblatex--command (citation info base &optional multi no-opt)
174 "Return biblatex command using BASE name for CITATION object.
264 ""))))
265
266 (defun org-cite-biblatex--command (citation info name &optional multi no-opt)
267 "Return BibLaTeX command NAME for CITATION object.
175268
176269 INFO is the export state, as a property list.
177270
178 When optional argument MULTI is non-nil, generate a \"multicite\" command when
179 appropriate. When optional argument NO-OPT is non-nil, do not add optional
180 arguments to the command."
181 (format "\\%s%s"
182 base
183 (if (and multi (org-cite-biblatex--multicite-p citation))
184 (concat "s" (org-cite-biblatex--multi-arguments citation info))
271 When optional argument MULTI is non-nil, use it as a multicite
272 command name when appropriate. When optional argument NO-OPT is
273 non-nil, do not add optional arguments to the command."
274 (if (and multi (org-cite-biblatex--multicite-p citation))
275 (format "\\%s%s" multi (org-cite-biblatex--multi-arguments citation info))
276 (format "\\%s%s"
277 name
185278 (org-cite-biblatex--atomic-arguments
186279 (org-cite-get-references citation) info no-opt))))
280
281 (defun org-cite-biblatex--expand-shortcuts (style)
282 "Return STYLE pair with shortcuts expanded."
283 (pcase style
284 (`(,style . ,variant)
285 (cons (or (alist-get style org-cite-biblatex-style-shortcuts
286 nil nil #'equal)
287 style)
288 (or (alist-get variant org-cite-biblatex-style-shortcuts
289 nil nil #'equal)
290 variant)))
291 (_ (error "This should not happen"))))
292
293 (defun org-cite-biblatex-list-styles ()
294 "List styles and variants supported in `biblatex' citation processor.
295 The output format is appropriate as a value for `:cite-styles' keyword
296 in `org-cite-register-processor', which see."
297 (let ((shortcuts (make-hash-table :test #'equal))
298 (variants (make-hash-table :test #'equal)))
299 (pcase-dolist (`(,name . ,full-name) org-cite-biblatex-style-shortcuts)
300 (push name (gethash full-name shortcuts)))
301 (pcase-dolist (`(,name ,variant . ,_) org-cite-biblatex-styles)
302 (unless (null variant) (push variant (gethash name variants))))
303 (map-apply (lambda (style-name variants)
304 (cons (cons (or style-name "nil")
305 (gethash style-name shortcuts))
306 (mapcar (lambda (v)
307 (cons v (gethash v shortcuts)))
308 variants)))
309 variants)))
187310
188311
189312 ;;; Export capability
214337 "Export CITATION object.
215338 STYLE is the citation style, as a pair of either strings or nil.
216339 INFO is the export state, as a property list."
217 (apply
218 #'org-cite-biblatex--command citation info
219 (pcase style
220 ;; "author" style.
221 (`(,(or "author" "a") . ,variant)
222 (pcase variant
223 ((or "caps" "c") '("Citeauthor*"))
224 ((or "full" "f") '("citeauthor"))
225 ((or "caps-full" "cf") '("Citeauthor"))
226 (_ '("citeauthor*"))))
227 ;; "locators" style.
228 (`(,(or "locators" "l") . ,variant)
229 (pcase variant
230 ((or "bare" "b") '("notecite"))
231 ((or "caps" "c") '("Pnotecite"))
232 ((or "bare-caps" "bc") '("Notecite"))
233 (_ '("pnotecite"))))
234 ;; "noauthor" style.
235 (`(,(or "noauthor" "na") . ,_) '("autocite*"))
236 ;; "nocite" style.
237 (`(,(or "nocite" "n") . ,_) '("nocite" nil t))
238 ;; "text" style.
239 (`(,(or "text" "t") . ,variant)
240 (pcase variant
241 ((or "caps" "c") '("Textcite" t))
242 (_ '("textcite" t))))
243 ;; Default "nil" style.
244 (`(,_ . ,variant)
245 (pcase variant
246 ((or "bare" "b") '("cite" t))
247 ((or "caps" "c") '("Autocite" t))
248 ((or "bare-caps" "bc") '("Cite" t))
249 (_ '("autocite" t))))
250 ;; This should not happen.
251 (_ (error "Invalid style: %S" style)))))
340 (pcase-let* ((`(,name . ,variant) (org-cite-biblatex--expand-shortcuts style))
341 (candidates nil)
342 (style-match-flag nil))
343 (catch :match
344 ;; Walk `org-cite-biblatex-styles' and prioritize matching
345 ;; candidates. At the end of the process, the optimal candidate
346 ;; should appear in front of CANDIDATES.
347 (dolist (style org-cite-biblatex-styles)
348 (pcase style
349 ;; A matching style-variant pair trumps anything else.
350 ;; Return it.
351 (`(,(pred (equal name)) ,(pred (equal variant)) . ,_)
352 (throw :match (setq candidates (list style))))
353 ;; nil-nil style-variant is the fallback value. Consider it
354 ;; only if nothing else matches.
355 (`(nil nil . ,_)
356 (unless candidates (push style candidates)))
357 ;; A matching style with default variant trumps a matching
358 ;; variant without the adequate style. Ensure the former
359 ;; appears first in the list.
360 (`(,(pred (equal name)) nil . ,_)
361 (push style candidates)
362 (setq style-match-flag t))
363 (`(nil ,(pred (equal variant)) . ,_)
364 (unless style-match-flag (push style candidates)))
365 ;; Discard anything else.
366 (_ nil))))
367 (apply
368 #'org-cite-biblatex--command citation info
369 (pcase (seq-elt candidates 0) ;; `seq-first' is not available in Emacs 26.
370 (`(,_ ,_ . ,command-parameters) command-parameters)
371 ('nil
372 (user-error
373 "Missing default style or variant in `org-cite-biblatex-styles'"))
374 (other
375 (user-error "Invalid entry %S in `org-cite-biblatex-styles'" other))))))
252376
253377 (defun org-cite-biblatex-prepare-preamble (output _keys files style &rest _)
254378 "Prepare document preamble for \"biblatex\" usage.
305429 :export-bibliography #'org-cite-biblatex-export-bibliography
306430 :export-citation #'org-cite-biblatex-export-citation
307431 :export-finalizer #'org-cite-biblatex-prepare-preamble
308 :cite-styles
309 '((("author" "a") ("caps" "c") ("full" "f") ("caps-full" "cf"))
310 (("locators" "l") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))
311 (("noauthor" "na"))
312 (("nocite" "n"))
313 (("text" "t") ("caps" "c"))
314 (("nil") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))))
432 :cite-styles #'org-cite-biblatex-list-styles)
315433
316434 (provide 'oc-biblatex)
317435 ;;; oc-biblatex.el ends here
0 ;;; oc-bibtex.el --- Vanilla citation processor for LaTeX -*- lexical-binding: t; -*-
1
2 ;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
3
4 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
5
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software: you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
20
21 ;;; Commentary:
22
23 ;; This library registers the `bibtex' citation processor, which
24 ;; provides the "export" capability for citations. It doesn't require
25 ;; any LaTeX package.
26 ;;
27 ;; It supports the following citation styles:
28 ;;
29 ;; - nocite (n),
30 ;; - default.
31 ;;
32 ;; Only suffixes are supported. Prefixes are ignored.
33 ;;
34 ;; Bibliography should consist of ".bib" files only.
35
36 ;;; Code:
37
38 (require 'org-macs)
39 (org-assert-version)
40
41 (require 'oc)
42
43 (declare-function org-element-property "org-element" (property element))
44
45 (declare-function org-export-data "org-export" (data info))
46
47
48 ;;; Export capability
49 (defun org-cite-bibtex-export-bibliography (_keys files style &rest _)
50 "Print references from bibliography FILES.
51 FILES is a list of absolute file names. STYLE is the bibliography style, as
52 a string or nil."
53 (concat (and style (format "\\bibliographystyle{%s}\n" style))
54 (format "\\bibliography{%s}"
55 (mapconcat #'file-name-sans-extension
56 files
57 ","))))
58
59 (defun org-cite-bibtex-export-citation (citation style _ info)
60 "Export CITATION object.
61 STYLE is the citation style, as a pair of strings or nil. INFO is the export
62 state, as a property list."
63 (let ((references (org-cite-get-references citation)))
64 (format "\\%s%s{%s}"
65 (pcase style
66 (`(,(or "nocite" "n") . ,_) "nocite")
67 (_ "cite"))
68 (let ((suffix (cdr (org-cite-main-affixes citation))))
69 (if suffix
70 (format "[%s]" (org-trim (org-export-data suffix info)))
71 ""))
72 (mapconcat (lambda (r) (org-element-property :key r))
73 references
74 ","))))
75
76
77 ;;; Register `bibtex' processor
78 (org-cite-register-processor 'bibtex
79 :export-bibliography #'org-cite-bibtex-export-bibliography
80 :export-citation #'org-cite-bibtex-export-citation
81 :cite-styles
82 '((("nocite" "n"))
83 (("nil"))))
84
85 (provide 'oc-bibtex)
86 ;;; oc-bibtex.el ends here
00 ;;; oc-csl.el --- csl citation processor for Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
5 ;; Maintainer: András Simonyi <andras.simonyi@gmail.com>
56
67 ;; This file is part of GNU Emacs.
78
5556
5657 ;; The library supports the following citation styles:
5758 ;;
58 ;; - author (a), including caps (c), full (f), and caps-full (cf) variants,
59 ;; - author (a), including bare (b), caps (c), bare-caps (bc), full (f),
60 ;; caps-full (cf), and bare-caps-full (bcf) variants,
5961 ;; - noauthor (na), including bare (b), caps (c) and bare-caps (bc) variants,
62 ;; - nocite (n),
6063 ;; - year (y), including a bare (b) variant,
61 ;; - text (t). including caps (c), full (f), and caps-full (cf) variants,
64 ;; - text (t), including caps (c), full (f), and caps-full (cf) variants,
65 ;; - title (ti), including a bare (b) variant,
66 ;; - locators (l), including a bare (b) variant,
67 ;; - bibentry (b), including a bare (b) variant,
6268 ;; - default style, including bare (b), caps (c) and bare-caps (bc) variants.
69 ;;
70 ;; Using "*" as a key in a nocite citation includes all available
71 ;; items in the printed bibliography. The "bibentry" citation style,
72 ;; similarly to biblatex's \fullcite, creates a citation which is
73 ;; similar to the bibliography entry.
6374
6475 ;; CSL styles recognize "locator" in citation references' suffix. For example,
6576 ;; in the citation
8495 ;; The part of the suffix before the locator is appended to reference's prefix.
8596 ;; If no locator term is used, but a number is present, then "page" is assumed.
8697
98 ;; Filtered sub-bibliographies can be printed by passing filtering
99 ;; options to the "print_bibliography" keywords. E.g.,
100 ;;
101 ;; #+print_bibliography: :type book keyword: emacs
102 ;;
103 ;; If you need to use a key multiple times, you can separate its
104 ;; values with commas, but without any space in-between:
105 ;;
106 ;; #+print_bibliography: :keyword abc,xyz :type article
107
87108 ;; This library was heavily inspired by and borrows from András Simonyi's
88109 ;; Citeproc Org (<https://github.com/andras-simonyi/citeproc-org>) library.
89110 ;; Many thanks to him!
90111
91112 ;;; Code:
113
114 (require 'org-macs)
115 (org-assert-version)
116
117 (require 'cl-lib)
118 (require 'map)
92119 (require 'bibtex)
93120 (require 'json)
94121 (require 'oc)
101128 (declare-function citeproc-create "ext:citeproc")
102129 (declare-function citeproc-citation-create "ext:citeproc")
103130 (declare-function citeproc-append-citations "ext:citeproc")
131 (declare-function citeproc-add-uncited "ext:citeproc")
104132 (declare-function citeproc-render-citations "ext:citeproc")
105133 (declare-function citeproc-render-bib "ext:citeproc")
106134 (declare-function citeproc-hash-itemgetter-from-any "ext:citeproc")
135 (declare-function citeproc-add-subbib-filters "ext:citeproc")
107136
108137 (declare-function org-element-interpret-data "org-element" (data))
109138 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
132161
133162 (defcustom org-cite-csl-styles-dir nil
134163 "Directory of CSL style files.
135 When non-nil, relative style file names are expanded relatively to this
136 directory. This variable is ignored when style file is absolute."
164
165 Relative style file names are expanded according to document's
166 default directory. If it fails and the variable is non-nil, Org
167 looks for style files in this directory, too."
137168 :group 'org-cite
138169 :package-version '(Org . "9.5")
139170 :type '(choice
140171 (directory :tag "Styles directory")
141 (const :tag "Use absolute file names" nil))
172 (const :tag "No central directory for style files" nil))
142173 ;; It's not obvious to me that arbitrary locations are safe.
143174 ;;; :safe #'string-or-null-p
144175 )
292323 (citeproc-proc-style
293324 (org-cite-csl--processor info))))
294325
326 (defun org-cite-csl--nocite-p (citation info)
327 "Non-nil when CITATION object's style is nocite.
328 INFO is the export state, as a property list."
329 (member (car (org-cite-citation-style citation info))
330 '("nocite" "n")))
331
295332 (defun org-cite-csl--create-structure-params (citation info)
296333 "Return citeproc structure creation params for CITATION object.
297334 STYLE is the citation style, as a string or nil. INFO is the export state, as
301338 ;; "author" style.
302339 (`(,(or "author" "a") . ,variant)
303340 (pcase variant
341 ((or "bare" "b") '(:mode author-only :suppress-affixes t))
304342 ((or "caps" "c") '(:mode author-only :capitalize-first t))
305343 ((or "full" "f") '(:mode author-only :ignore-et-al t))
344 ((or "bare-caps" "bc") '(:mode author-only :suppress-affixes t :capitalize-first t))
345 ((or "bare-full" "bf") '(:mode author-only :suppress-affixes t :ignore-et-al t))
306346 ((or "caps-full" "cf") '(:mode author-only :capitalize-first t :ignore-et-al t))
347 ((or "bare-caps-full" "bcf") '(:mode author-only :suppress-affixes t :capitalize-first t :ignore-et-al t))
307348 (_ '(:mode author-only))))
308349 ;; "noauthor" style.
309350 (`(,(or "noauthor" "na") . ,variant)
318359 (pcase variant
319360 ((or "bare" "b") '(:mode year-only :suppress-affixes t))
320361 (_ '(:mode year-only))))
362 ;; "bibentry" style.
363 (`(,(or "bibentry" "b") . ,variant)
364 (pcase variant
365 ((or "bare" "b") '(:mode bib-entry :suppress-affixes t))
366 (_ '(:mode bib-entry))))
367 ;; "locators" style.
368 (`(,(or "locators" "l") . ,variant)
369 (pcase variant
370 ((or "bare" "b") '(:mode locator-only :suppress-affixes t))
371 (_ '(:mode locator-only))))
372 ;; "title" style.
373 (`(,(or "title" "ti") . ,variant)
374 (pcase variant
375 ((or "bare" "b") '(:mode title-only :suppress-affixes t))
376 (_ '(:mode title-only))))
321377 ;; "text" style.
322378 (`(,(or "text" "t") . ,variant)
323379 (pcase variant
364420
365421 INFO is the export state, as a property list.
366422
367 When file name is relative, expand it according to `org-cite-csl-styles-dir',
368 or raise an error if the variable is unset."
423 When file name is relative, look for it in buffer's default
424 directory, failing that in `org-cite-csl-styles-dir' if non-nil.
425 Raise an error if no style file can be found."
369426 (pcase (org-cite-bibliography-style info)
370427 ('nil org-cite-csl--fallback-style-file)
371428 ((and (pred file-name-absolute-p) file) file)
372 ((and (guard org-cite-csl-styles-dir) file)
429 ((and (pred file-exists-p) file) (expand-file-name file))
430 ((and (guard org-cite-csl-styles-dir)
431 (pred (lambda (f)
432 (file-exists-p
433 (expand-file-name f org-cite-csl-styles-dir))))
434 file)
373435 (expand-file-name file org-cite-csl-styles-dir))
374436 (other
375 (user-error "Cannot handle relative style file name: %S" other))))
437 (user-error "CSL style file not found: %S" other))))
376438
377439 (defun org-cite-csl--locale-getter ()
378440 "Return a locale getter.
521583 Return an alist (CITATION . OUTPUT) where CITATION object has been rendered as
522584 OUTPUT using Citeproc."
523585 (or (plist-get info :cite-citeproc-rendered-citations)
524 (let* ((citations (org-cite-list-citations info))
525 (processor (org-cite-csl--processor info))
526 (structures
527 (mapcar (lambda (c) (org-cite-csl--create-structure c info))
528 citations)))
529 (citeproc-append-citations structures processor)
530 (let* ((rendered
531 (citeproc-render-citations
532 processor
533 (org-cite-csl--output-format info)
534 (org-cite-csl--no-citelinks-p info)))
535 (result (seq-mapn #'cons citations rendered)))
536 (plist-put info :cite-citeproc-rendered-citations result)
537 result))))
586 (let ((citations (org-cite-list-citations info))
587 (processor (org-cite-csl--processor info))
588 normal-citations nocite-ids)
589 (dolist (citation citations)
590 (if (org-cite-csl--nocite-p citation info)
591 (setq nocite-ids (append (org-cite-get-references citation t) nocite-ids))
592 (push citation normal-citations)))
593 (let ((structures
594 (mapcar (lambda (c) (org-cite-csl--create-structure c info))
595 (nreverse normal-citations))))
596 (citeproc-append-citations structures processor))
597 (when nocite-ids
598 (citeproc-add-uncited nocite-ids processor))
599 ;; All bibliographies have to be rendered in order to have
600 ;; correct citation numbers even if there are several
601 ;; sub-bibliograhies.
602 (org-cite-csl--rendered-bibliographies info)
603 (let (result
604 (rendered (citeproc-render-citations
605 processor
606 (org-cite-csl--output-format info)
607 (org-cite-csl--no-citelinks-p info))))
608 (dolist (citation citations)
609 (push (cons citation
610 (if (org-cite-csl--nocite-p citation info) "" (pop rendered)))
611 result))
612 (setq result (nreverse result))
613 (plist-put info :cite-citeproc-rendered-citations result)
614 result))))
615
616 (defun org-cite-csl--bibliography-filter (bib-props)
617 "Return the sub-bibliography filter corresponding to bibliography properties.
618
619 BIB-PROPS should be a plist representing the properties
620 associated with a \"print_bibliography\" keyword, as returned by
621 `org-cite-bibliography-properties'."
622 (let (result
623 (remove-keyword-colon (lambda (x) (intern (substring (symbol-name x) 1)))))
624 (map-do
625 (lambda (key value)
626 (pcase key
627 ((or :keyword :notkeyword :nottype :notcsltype :filter)
628 (dolist (v (split-string value ","))
629 (push (cons (funcall remove-keyword-colon key) v) result)))
630 ((or :type :csltype)
631 (if (string-match-p "," value)
632 (user-error "The \"%s\" print_bibliography option does not support comma-separated values" key)
633 (push (cons (funcall remove-keyword-colon key) value) result)))))
634 bib-props)
635 result))
636
637 (defun org-cite-csl--rendered-bibliographies (info)
638 "Return the rendered bibliographies.
639
640 INFO is the export state, as a property list.
641
642 Return an (OUTPUTS PARAMETERS) list where OUTPUTS is an alist
643 of (BIB-PROPS . OUTPUT) pairs where each key is a property list
644 of a \"print_bibliography\" keyword and the corresponding OUTPUT
645 value is the bibliography as rendered by Citeproc."
646 (or (plist-get info :cite-citeproc-rendered-bibliographies)
647 (let (bib-plists bib-filters)
648 ;; Collect bibliography property lists and the corresponding
649 ;; Citeproc sub-bib filters.
650 (org-element-map (plist-get info :parse-tree) 'keyword
651 (lambda (keyword)
652 (when (equal "PRINT_BIBLIOGRAPHY" (org-element-property :key keyword))
653 (let ((bib-plist (org-cite-bibliography-properties keyword)))
654 (push bib-plist bib-plists)
655 (push (org-cite-csl--bibliography-filter bib-plist) bib-filters)))))
656 (setq bib-filters (nreverse bib-filters)
657 bib-plists (nreverse bib-plists))
658 ;; Render and return all bibliographies.
659 (let ((processor (org-cite-csl--processor info)))
660 (citeproc-add-subbib-filters bib-filters processor)
661 (pcase-let* ((format (org-cite-csl--output-format info))
662 (`(,rendered-bibs . ,parameters)
663 (citeproc-render-bib
664 (org-cite-csl--processor info)
665 format
666 (org-cite-csl--no-citelinks-p info)))
667 (outputs (cl-mapcar #'cons bib-plists rendered-bibs))
668 (result (list outputs parameters)))
669 (plist-put info :cite-citeproc-rendered-bibliographies result)
670 result)))))
538671
539672
540673 ;;; Export capability
549682 ;; process.
550683 (org-cite-parse-objects output))))
551684
552 (defun org-cite-csl-render-bibliography (_keys _files _style _props _backend info)
685 (defun org-cite-csl-render-bibliography (_keys _files _style props _backend info)
553686 "Export bibliography.
554687 INFO is the export state, as a property list."
555688 (org-cite-csl--barf-without-citeproc)
556 (pcase-let* ((format (org-cite-csl--output-format info))
557 (`(,output . ,parameters)
558 (citeproc-render-bib
559 (org-cite-csl--processor info)
560 format
561 (org-cite-csl--no-citelinks-p info))))
689 (pcase-let* ((format (org-cite-csl--output-format info))
690 (`(,outputs ,parameters) (org-cite-csl--rendered-bibliographies info))
691 (output (cdr (assoc props outputs))))
562692 (pcase format
563693 ('html
564694 (concat
620750 :export-bibliography #'org-cite-csl-render-bibliography
621751 :export-finalizer #'org-cite-csl-finalizer
622752 :cite-styles
623 '((("author" "a") ("full" "f") ("caps" "c") ("caps-full" "cf"))
753 '((("author" "a") ("bare" "b") ("caps" "c") ("full" "f") ("bare-caps" "bc") ("caps-full" "cf") ("bare-caps-full" "bcf"))
624754 (("noauthor" "na") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))
625755 (("year" "y") ("bare" "b"))
626756 (("text" "t") ("caps" "c") ("full" "f") ("caps-full" "cf"))
627 (("nil") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))))
757 (("nil") ("bare" "b") ("caps" "c") ("bare-caps" "bc"))
758 (("nocite" "n"))
759 (("title" "ti") ("bare" "b"))
760 (("bibentry" "b") ("bare" "b"))
761 (("locators" "l") ("bare" "b"))))
628762
629763 (provide 'oc-csl)
630764 ;;; oc-csl.el ends here
00 ;;; oc-natbib.el --- Citation processor using natbib LaTeX package -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55
4141 ;; Bibliography accepts any style supported by "natbib" package.
4242
4343 ;;; Code:
44
45 (require 'org-macs)
46 (org-assert-version)
47
4448 (require 'oc)
4549
4650 (declare-function org-element-property "org-element" (property element))
00 ;;; oc.el --- Org Cite library -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55
5959 ;; on processors. See "Generic tools" section.
6060
6161 ;;; Code:
62
63 (require 'org-macs)
64 (org-assert-version)
6265
6366 (require 'org-compat)
6467 (require 'org-macs)
322325 See `org-cite-register-processor' for more information about
323326 processors.")
324327
325 (defun org-cite--get-processor (name)
326 "Return citation processor named after symbol NAME.
327 Return nil if no such processor is found."
328 (seq-find (lambda (p) (eq name (org-cite-processor-name p)))
329 org-cite--processors))
330
331328 (defun org-cite-register-processor (name &rest body)
332329 "Mark citation processor NAME as available.
333330
414411 The \"nil\" style denotes the processor fall-back style. It
415412 should have a corresponding entry in the value.
416413
414 The value can also be a function. It will be called without
415 any argument and should return a list structured as the above.
416
417417 Return a non-nil value on a successful operation."
418418 (declare (indent 1))
419419 (unless (and name (symbolp name))
420420 (error "Invalid processor name: %S" name))
421 (when (org-cite--get-processor name)
422 (org-cite-unregister-processor name))
423 (push (apply #'org-cite--make-processor :name name body)
424 org-cite--processors))
421 (setq org-cite--processors
422 (cons (apply #'org-cite--make-processor :name name body)
423 (seq-remove (lambda (p) (eq name (org-cite-processor-name p)))
424 org-cite--processors))))
425
426 (defun org-cite-try-load-processor (name)
427 "Try loading citation processor NAME if unavailable.
428 NAME is a symbol. When the NAME processor is unregistered, try
429 loading \"oc-NAME\" library beforehand, then cross fingers."
430 (unless (org-cite-get-processor name)
431 (require (intern (format "oc-%s" name)) nil t)))
432
433 (defun org-cite-get-processor (name)
434 "Return citation processor named after symbol NAME.
435 Return nil if no such processor is found."
436 (seq-find (lambda (p) (eq name (org-cite-processor-name p)))
437 org-cite--processors))
425438
426439 (defun org-cite-unregister-processor (name)
427440 "Unregister citation processor NAME.
429442 Return a non-nil value on a successful operation."
430443 (unless (and name (symbolp name))
431444 (error "Invalid processor name: %S" name))
432 (pcase (org-cite--get-processor name)
445 (pcase (org-cite-get-processor name)
433446 ('nil (error "Processor %S not registered" name))
434447 (processor
435448 (setq org-cite--processors (delete processor org-cite--processors))))
439452 "Return non-nil if PROCESSOR is able to handle CAPABILITY.
440453 PROCESSOR is the name of a cite processor, as a symbol. CAPABILITY is
441454 `activate', `export', `follow', or `insert'."
442 (let ((p (org-cite--get-processor processor)))
455 (let ((p (org-cite-get-processor processor)))
443456 (pcase capability
444457 ((guard (not p)) nil) ;undefined processor
445458 ('activate (functionp (org-cite-processor-activate p)))
672685 (let ((collection
673686 (seq-mapcat
674687 (lambda (name)
675 (org-cite-processor-cite-styles (org-cite--get-processor name)))
688 (pcase (org-cite-processor-cite-styles
689 (org-cite-get-processor name))
690 ((and (pred functionp) f) (funcall f))
691 (static-data static-data)))
676692 (or processors
677693 (mapcar (pcase-lambda (`(,_ . (,name . ,_))) name)
678694 org-cite-export-processors))))
788804 (cons (org-not-nil (car global))
789805 (or (cdr local) (cdr global)))))))
790806
807 (defun org-cite-read-processor-declaration (s)
808 "Read processor declaration from string S.
809
810 Return (NAME BIBLIOGRAPHY-STYLE CITATION-STYLE) triplet, when
811 NAME is the processor name, as a symbol, and both
812 BIBLIOGRAPHY-STYLE and CITATION-STYLE are strings or nil. Those
813 strings may contain spaces if they are enclosed within double
814 quotes.
815
816 String S is expected to contain between 1 and 3 tokens. The
817 function raises an error when it contains too few or too many
818 tokens. Spurious spaces are ignored."
819 (with-temp-buffer
820 (save-excursion (insert s))
821 (let ((result (list (read (current-buffer)))))
822 (dotimes (_ 2)
823 (skip-chars-forward " \t")
824 (cond
825 ((eobp) (push nil result))
826 ((char-equal ?\" (char-after))
827 (push (org-not-nil (read (current-buffer)))
828 result))
829 (t
830 (let ((origin (point)))
831 (skip-chars-forward "^ \t")
832 (push (org-not-nil (buffer-substring origin (point)))
833 result)))))
834 (skip-chars-forward " \t")
835 (unless (eobp)
836 (error "Trailing garbage following cite export processor declaration %S"
837 s))
838 (nreverse result))))
839
791840 (defun org-cite-bibliography-style (info)
792841 "Return expected bibliography style.
793842 INFO is a plist used as a communication channel."
807856 (or (plist-get info :citations)
808857 (letrec ((cites nil)
809858 (tree (plist-get info :parse-tree))
859 (definition-cache (make-hash-table :test #'equal))
860 (definition-list nil)
810861 (find-definition
811862 ;; Find definition for standard reference LABEL. At
812863 ;; this point, it is impossible to rely on
815866 ;; un-processed citation objects. So we use
816867 ;; a simplified version of the function above.
817868 (lambda (label)
818 (org-element-map tree 'footnote-definition
819 (lambda (d)
820 (and (equal label (org-element-property :label d))
821 (or (org-element-contents d) "")))
822 info t)))
869 (or (gethash label definition-cache)
870 (org-element-map
871 (or definition-list
872 (setq definition-list
873 (org-element-map
874 tree
875 'footnote-definition
876 #'identity info)))
877 'footnote-definition
878 (lambda (d)
879 (and (equal label (org-element-property :label d))
880 (puthash label
881 (or (org-element-contents d) "")
882 definition-cache)))
883 info t))))
823884 (search-cites
824885 (lambda (data)
825886 (org-element-map data '(citation footnote-reference)
833894 (_
834895 (let ((label (org-element-property :label datum)))
835896 (funcall search-cites
836 (funcall find-definition label))))))
897 (funcall find-definition label)))))
898 nil)
837899 info nil 'footnote-definition t))))
838900 (funcall search-cites tree)
839901 (let ((result (nreverse cites)))
11631225 (activate
11641226 (or (and name
11651227 (org-cite-processor-has-capability-p name 'activate)
1166 (org-cite-processor-activate (org-cite--get-processor name)))
1228 (org-cite-processor-activate (org-cite-get-processor name)))
11671229 #'org-cite-fontify-default)))
11681230 (when (re-search-forward org-element-citation-prefix-re limit t)
11691231 (let ((cite (org-with-point-at (match-beginning 0)
11701232 (org-element-citation-parser))))
11711233 (when cite
1172 (funcall activate cite)
1234 ;; Do not alter match data as font-lock expects us to set it
1235 ;; appropriately.
1236 (save-match-data (funcall activate cite))
11731237 ;; Move after cite object and make sure to return
11741238 ;; a non-nil value.
11751239 (goto-char (org-element-property :end cite)))))))
11901254
11911255 Export processor is stored as a triplet, or nil.
11921256
1193 When non-nil, it is defined as (NAME BIBLIOGRAPHY-STYLE CITATION-STYLE) where
1194 NAME is a symbol, whereas BIBLIOGRAPHY-STYLE and CITATION-STYLE are strings,
1195 or nil.
1196
1197 INFO is the communication channel, as a plist. It is modified by side-effect."
1257 When non-nil, it is defined as (NAME BIBLIOGRAPHY-STYLE
1258 CITATION-STYLE) where NAME is a symbol, whereas
1259 BIBLIOGRAPHY-STYLE and CITATION-STYLE are strings, or nil.
1260
1261 INFO is the communication channel, as a plist. It is modified by
1262 side-effect."
11981263 (let* ((err
11991264 (lambda (s)
1200 (user-error "Invalid cite export processor definition: %S" s)))
1265 (user-error "Invalid cite export processor declaration: %S" s)))
12011266 (processor
12021267 (pcase (plist-get info :cite-export)
12031268 ((or "" `nil) nil)
12041269 ;; Value is a string. It comes from a "cite_export"
1205 ;; keyword. It may contain between 1 and 3 tokens, the
1206 ;; first one being a symbol and the other (optional) two,
1207 ;; strings.
1270 ;; keyword.
12081271 ((and (pred stringp) s)
1209 (with-temp-buffer
1210 (save-excursion (insert s))
1211 (let ((result (list (read (current-buffer)))))
1212 (dotimes (_ 2)
1213 (skip-chars-forward " \t")
1214 (cond
1215 ((eobp) (push nil result))
1216 ((char-equal ?\" (char-after))
1217 (condition-case _
1218 (push (org-not-nil (read (current-buffer))) result)
1219 (error (funcall err s))))
1220 (t
1221 (let ((origin (point)))
1222 (skip-chars-forward "^ \t")
1223 (push (org-not-nil (buffer-substring origin (point)))
1224 result)))))
1225 (unless (eobp) (funcall err s))
1226 (nreverse result))))
1272 (org-cite-read-processor-declaration s))
12271273 ;; Value is an alist. It must come from
12281274 ;; `org-cite-export-processors' variable. Find the most
12291275 ;; appropriate processor according to current export
12601306 (pcase processor
12611307 ('nil nil)
12621308 (`(,name . ,_)
1309 (org-cite-try-load-processor name)
12631310 (cond
1264 ((not (org-cite--get-processor name))
1311 ((not (org-cite-get-processor name))
12651312 (user-error "Unknown processor %S" name))
12661313 ((not (org-cite-processor-has-capability-p name 'export))
12671314 (user-error "Processor %S is unable to handle citation export" name)))))
12741321 (pcase (plist-get info :cite-export)
12751322 ('nil nil)
12761323 (`(,p ,_ ,_)
1277 (funcall (org-cite-processor-export-citation (org-cite--get-processor p))
1324 (funcall (org-cite-processor-export-citation (org-cite-get-processor p))
12781325 citation
12791326 (org-cite-citation-style citation info)
12801327 (plist-get info :back-end)
12901337 (`(,p ,_ ,_)
12911338 (let ((export-bibilography
12921339 (org-cite-processor-export-bibliography
1293 (org-cite--get-processor p))))
1340 (org-cite-get-processor p))))
12941341 (when export-bibilography
12951342 (funcall export-bibilography
12961343 (org-cite-list-keys info)
13911438 ('nil output)
13921439 (`(,p ,_ ,_)
13931440 (let ((finalizer
1394 (org-cite-processor-export-finalizer (org-cite--get-processor p))))
1441 (org-cite-processor-export-finalizer (org-cite-get-processor p))))
13951442 (if (not finalizer)
13961443 output
13971444 (funcall finalizer
14091456 "Follow citation or citation-reference DATUM.
14101457 Following is done according to the processor set in `org-cite-follow-processor'.
14111458 ARG is the prefix argument received when calling `org-open-at-point', or nil."
1459 (unless org-cite-follow-processor
1460 (user-error "No processor set to follow citations"))
1461 (org-cite-try-load-processor org-cite-follow-processor)
14121462 (let ((name org-cite-follow-processor))
14131463 (cond
1414 ((null name)
1415 (user-error "No processor set to follow citations"))
1416 ((not (org-cite--get-processor name))
1464 ((not (org-cite-get-processor name))
14171465 (user-error "Unknown processor %S" name))
14181466 ((not (org-cite-processor-has-capability-p name 'follow))
14191467 (user-error "Processor %S cannot follow citations" name))
14201468 (t
1421 (let ((follow (org-cite-processor-follow (org-cite--get-processor name))))
1469 (let ((follow (org-cite-processor-follow (org-cite-get-processor name))))
14221470 (funcall follow datum arg))))))
14231471
14241472
14601508 (not (looking-at-p "\\*+ END[ \t]*$")))
14611509 (let ((case-fold-search nil))
14621510 (looking-at org-complex-heading-regexp))))
1463 (match-beginning 4)
1464 (>= (point) (match-beginning 4))
1511 (>= (point) (or
1512 ;; Real heading.
1513 (match-beginning 4)
1514 ;; If no heading, end of priority.
1515 (match-end 3)
1516 ;; ... end of todo keyword.
1517 (match-end 2)
1518 ;; ... after stars.
1519 (1+ (match-end 1))))
14651520 (or (not (match-beginning 5))
14661521 (< (point) (match-beginning 5))))))
14671522 ;; White spaces after an object or blank lines after an element
14781533 ;; unaffected.
14791534 ((eq type 'item)
14801535 (> (point) (+ (org-element-property :begin context)
1481 (current-indentation)
1536 (org-current-text-indentation)
14821537 (if (org-element-property :checkbox context)
14831538 5 1))))
14841539 ;; Other elements are invalid.
15231578 (defun org-cite-make-insert-processor (select-key select-style)
15241579 "Build a function appropriate as an insert processor.
15251580
1526 SELECT-KEY is a function called with one argument. When it is nil, the function
1527 should return a citation key as a string, or nil. Otherwise, the function
1528 should return a list of such keys, or nil. The keys should not have any leading
1529 \"@\" character.
1530
1531 SELECT-STYLE is a function called with one argument, the citation object being
1532 edited or constructed so far. It should return a style string, or nil.
1533
1534 The return value is a function of two arguments: CONTEXT and ARG. CONTEXT is
1535 either a citation reference, a citation object, or nil. ARG is a prefix
1536 argument.
1537
1538 The generated function inserts or edit a citation at point. More specifically,
1581 SELECT-KEY is a function called with one argument. When it is
1582 nil, the function should return a citation key as a string, or
1583 nil. Otherwise, the function should return a list of such keys,
1584 or nil. The keys should not have any leading \"@\" character.
1585
1586 SELECT-STYLE is a function called with one argument, the citation
1587 object being edited or constructed so far. It should return
1588 a style string, or nil.
1589
1590 The return value is a function of two arguments: CONTEXT and ARG.
1591 CONTEXT is either a citation reference, a citation object, or
1592 nil. ARG is a prefix argument.
1593
1594 The generated function inserts or edits a citation at point.
1595 More specifically,
15391596
15401597 On a citation reference:
15411598
1542 - on the prefix or right before the \"@\" character, insert a new reference
1543 before the current one,
1599 - on the prefix or right before the \"@\" character, insert
1600 a new reference before the current one,
15441601 - on the suffix, insert it after the reference,
15451602 - otherwise, update the cite key, preserving both affixes.
15461603
1547 When ARG is non-nil, remove the reference, possibly removing the whole
1548 citation if it contains a single reference.
1604 When ARG is non-nil, remove the reference, possibly removing
1605 the whole citation if it contains a single reference.
15491606
15501607 On a citation object:
15511608
15521609 - on the style part, offer to update it,
1553 - on the global prefix, add a new reference before the first one,
1554 - on the global suffix, add a new reference after the last one,
1555
1556 Elsewhere, insert a citation at point. When ARG is non-nil, offer to complete
1557 style in addition to references."
1610 - on the global prefix, add a new reference before the first
1611 one,
1612 - on the global suffix, add a new reference after the last
1613 one.
1614
1615 Elsewhere, insert a citation at point. When ARG is non-nil,
1616 offer to complete style in addition to references."
15581617 (unless (and (functionp select-key) (functionp select-style))
15591618 (error "Wrong argument type(s)"))
15601619 (lambda (context arg)
15751634 (if (>= style-end (point))
15761635 ;; On style part, edit the style.
15771636 (let ((style-start (+ 5 begin))
1578 (style (funcall select-style)))
1637 (style (funcall select-style context)))
15791638 (unless style (user-error "Aborted"))
15801639 (org-with-point-at style-start
15811640 (delete-region style-start style-end)
16261685 Insertion is done according to the processor set in `org-cite-insert-processor'.
16271686 ARG is the prefix argument received when calling interactively the function."
16281687 (interactive "P")
1688 (unless org-cite-insert-processor
1689 (user-error "No processor set to insert citations"))
1690 (org-cite-try-load-processor org-cite-insert-processor)
16291691 (let ((name org-cite-insert-processor))
16301692 (cond
1631 ((null name)
1632 (user-error "No processor set to insert citations"))
1633 ((not (org-cite--get-processor name))
1693 ((not (org-cite-get-processor name))
16341694 (user-error "Unknown processor %S" name))
16351695 ((not (org-cite-processor-has-capability-p name 'insert))
16361696 (user-error "Processor %S cannot insert citations" name))
16371697 (t
16381698 (let ((context (org-element-context))
1639 (insert (org-cite-processor-insert (org-cite--get-processor name))))
1699 (insert (org-cite-processor-insert (org-cite-get-processor name))))
16401700 (cond
16411701 ((memq (org-element-type context) '(citation citation-reference))
16421702 (funcall insert context arg))
00 ;;; ol-bbdb.el --- Links to BBDB entries -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Authors: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Thomas Baumann <thomas dot baumann at ch dot tum dot de>
66 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88 ;;
99 ;; This file is part of GNU Emacs.
1010 ;;
9191 ;; link from which the entry at point originates.
9292 ;;
9393 ;;; Code:
94
95 (require 'org-macs)
96 (org-assert-version)
9497
9598 (require 'cl-lib)
9699 (require 'org-compat)
131134
132135 (defgroup org-bbdb-anniversaries nil
133136 "Customizations for including anniversaries from BBDB into Agenda."
134 :group 'org-bbdb)
137 :group 'org-agenda)
135138
136139 (defcustom org-bbdb-default-anniversary-format "birthday"
137140 "Default anniversary class."
00 ;;; ol-bibtex.el --- Links to BibTeX entries -*- lexical-binding: t; -*-
11 ;;
2 ;; Copyright (C) 2007-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2007-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Authors: Bastien Guerry <bzg@gnu.org>
55 ;; Carsten Dominik <carsten dot dominik at gmail dot com>
8585 ;; the active region, then call `org-bibtex-write' in a .org file to
8686 ;; insert a heading for the read bibtex entry
8787 ;;
88 ;; - All Bibtex information is taken from the document compiled by
89 ;; Andrew Roberts from the Bibtex manual, available at
88 ;; - All BibTeX information is taken from the document compiled by
89 ;; Andrew Roberts from the BibTeX manual, available at
9090 ;; https://www.andy-roberts.net/res/writing/latex/bibentries.pdf
9191 ;;
9292 ;;; History:
9898 ;; and then implemented by Bastien Guerry.
9999 ;;
100100 ;; Eric Schulte eventually added the functions for translating between
101 ;; Org headlines and Bibtex entries, and for fleshing out the Bibtex
101 ;; Org headlines and BibTeX entries, and for fleshing out the BibTeX
102102 ;; fields of existing Org headlines.
103103 ;;
104104 ;; Org mode loads this module by default - if this is not what you want,
105105 ;; configure the variable `org-modules'.
106106
107107 ;;; Code:
108
109 (require 'org-macs)
110 (org-assert-version)
108111
109112 (require 'bibtex)
110113 (require 'cl-lib)
114117
115118 (defvar org-agenda-overriding-header)
116119 (defvar org-agenda-search-view-always-boolean)
117 (defvar org-bibtex-description nil) ; dynamically scoped from org.el
120 (defvar org-bibtex-description nil)
118121 (defvar org-id-locations)
119122 (defvar org-property-end-re)
120123 (defvar org-special-properties)
132135 (declare-function org-heading-components "org" ())
133136 (declare-function org-insert-heading "org" (&optional arg invisible-ok top))
134137 (declare-function org-map-entries "org" (func &optional match scope &rest skip))
135 (declare-function org-narrow-to-subtree "org" ())
138 (declare-function org-narrow-to-subtree "org" (&optional element))
136139 (declare-function org-set-property "org" (property value))
137140 (declare-function org-toggle-tag "org" (tag &optional onoff))
141 (declare-function org-indent-region "org" (start end))
138142
139143 (declare-function org-search-view "org-agenda" (&optional todo-only string edit-at))
140144
141145
142 ;;; Bibtex data
146 ;;; BibTeX data
143147 (defvar org-bibtex-types
144148 '((:article
145149 (:description . "An article from a journal or magazine")
197201 (:description . "A document having an author and title, but not formally published.")
198202 (:required :author :title :note)
199203 (:optional :month :year :doi :url)))
200 "Bibtex entry types with required and optional parameters.")
204 "BibTeX entry types with required and optional parameters.")
201205
202206 (defvar org-bibtex-fields
203207 '((:address . "Usually the address of the publisher or other type of institution. For major publishing houses, van Leunen recommends omitting the information entirely. For small publishers, on the other hand, you can help the reader by giving the complete address.")
226230 (:url . "Uniform resource locator.")
227231 (:volume . "The volume of a journal or multi-volume book.")
228232 (:year . "The year of publication or, for an unpublished work, the year it was written. Generally it should consist of four numerals, such as 1984, although the standard styles can handle any year whose last four nonpunctuation characters are numerals, such as '(about 1984)'"))
229 "Bibtex fields with descriptions.")
233 "BibTeX fields with descriptions.")
230234
231235 (defvar org-bibtex-entries nil
232236 "List to hold parsed bibtex entries.")
237
238 (defgroup org-bibtex nil
239 "Options for translating between Org headlines and BibTeX entries."
240 :tag "Org BibTeX"
241 :group 'org)
233242
234243 (defcustom org-bibtex-autogen-keys nil
235244 "Set to a truth value to use `bibtex-generate-autokey' to generate keys."
343352 (upcase property)))))))
344353 (when it (org-trim it))))
345354
346 (defun org-bibtex-put (property value)
347 (let ((prop (upcase (if (keywordp property)
348 (substring (symbol-name property) 1)
349 property))))
350 (org-set-property
351 (concat (unless (string= org-bibtex-key-property prop) org-bibtex-prefix)
352 prop)
353 value)))
355 (defun org-bibtex-put (property value &optional insert-raw)
356 "Set PROPERTY of headline at point to VALUE.
357 The PROPERTY will be prefixed with `org-bibtex-prefix' when necessary.
358 With non-nil optional argument INSERT-RAW, insert node property string
359 at point."
360 (let* ((prop (upcase (if (keywordp property)
361 (substring (symbol-name property) 1)
362 property)))
363 (prop (concat (unless (string= org-bibtex-key-property prop)
364 org-bibtex-prefix)
365 prop)))
366 (if insert-raw
367 (insert (format ":%s: %s\n" prop value))
368 (org-set-property prop value))))
354369
355370 (defun org-bibtex-headline ()
356371 "Return a bibtex entry of the given headline as a string."
423438 (error "Field:%s is not known" field))
424439 (save-window-excursion
425440 (let* ((name (substring (symbol-name field) 1))
426 (buf-name (format "*Bibtex Help %s*" name)))
441 (buf-name (format "*BibTeX Help %s*" name)))
427442 (with-output-to-temp-buffer buf-name
428443 (princ (cdr (assoc field org-bibtex-fields))))
429444 (with-current-buffer buf-name (visual-line-mode 1))
480495 (org-bibtex-autokey)))
481496
482497
483 ;;; Bibtex link functions
498 ;;; BibTeX link functions
484499 (org-link-set-parameters "bibtex"
485500 :follow #'org-bibtex-open
486501 :store #'org-bibtex-store-link)
577592 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
578593
579594
580 ;;; Bibtex <-> Org headline translation functions
595 ;;; BibTeX <-> Org headline translation functions
581596 (defun org-bibtex (filename)
582597 "Export each headline in the current file to a bibtex entry.
583598 Headlines are exported using `org-bibtex-headline'."
584599 (interactive
585600 (list (read-file-name
586 "Bibtex file: " nil nil nil
601 "BibTeX file: " nil nil nil
587602 (let ((file (buffer-file-name (buffer-base-buffer))))
588603 (and file
589604 (file-name-nondirectory
603618 nil))))
604619 (when error-point
605620 (goto-char error-point)
606 (message "Bibtex error at %S" (nth 4 (org-heading-components))))))
621 (message "BibTeX error at %S" (nth 4 (org-heading-components))))))
607622
608623 (defun org-bibtex-check (&optional optional)
609624 "Check the current headline for required fields.
654669
655670 (defun org-bibtex-read ()
656671 "Read a bibtex entry and save to `org-bibtex-entries'.
657 This uses `bibtex-parse-entry'."
672 This uses `bibtex-parse-entry'.
673 Return the new value of `org-bibtex-entries'."
658674 (interactive)
659675 (let ((keyword (lambda (str) (intern (concat ":" (downcase str)))))
660676 (clean-space (lambda (str) (replace-regexp-in-string
677693 (funcall clean-space (funcall strip-delim (cdr pair)))))
678694 (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
679695 org-bibtex-entries)
680 (unless (car org-bibtex-entries) (pop org-bibtex-entries))))
696 (unless (car org-bibtex-entries) (pop org-bibtex-entries))
697 org-bibtex-entries))
681698
682699 (defun org-bibtex-read-buffer (buffer)
683700 "Read all bibtex entries in BUFFER and save to `org-bibtex-entries'.
700717 (interactive "fFile: ")
701718 (org-bibtex-read-buffer (find-file-noselect file 'nowarn 'rawfile)))
702719
703 (defun org-bibtex-write ()
704 "Insert a heading built from the first element of `org-bibtex-entries'."
720 (defun org-bibtex-write (&optional noindent)
721 "Insert a heading built from the first element of `org-bibtex-entries'.
722 When optional argument NOINDENT is non-nil, do not indent the properties
723 drawer."
705724 (interactive)
706 (when (= (length org-bibtex-entries) 0)
725 (unless org-bibtex-entries
707726 (error "No entries in `org-bibtex-entries'"))
708727 (let* ((entry (pop org-bibtex-entries))
709728 (org-special-properties nil) ; avoids errors with `org-entry-put'
711730 (togtag (lambda (tag) (org-toggle-tag tag 'on))))
712731 (org-insert-heading)
713732 (insert (funcall org-bibtex-headline-format-function entry))
714 (org-bibtex-put "TITLE" (funcall val :title))
733 (insert "\n:PROPERTIES:\n")
734 (org-bibtex-put "TITLE" (funcall val :title) 'insert)
715735 (org-bibtex-put org-bibtex-type-property-name
716 (downcase (funcall val :type)))
736 (downcase (funcall val :type))
737 'insert)
717738 (dolist (pair entry)
718739 (pcase (car pair)
719740 (:title nil)
720741 (:type nil)
721 (:key (org-bibtex-put org-bibtex-key-property (cdr pair)))
742 (:key (org-bibtex-put org-bibtex-key-property (cdr pair) 'insert))
722743 (:keywords (if org-bibtex-tags-are-keywords
723744 (dolist (kw (split-string (cdr pair) ", *"))
724745 (funcall
726747 (replace-regexp-in-string
727748 "[^[:alnum:]_@#%]" ""
728749 (replace-regexp-in-string "[ \t]+" "_" kw))))
729 (org-bibtex-put (car pair) (cdr pair))))
730 (_ (org-bibtex-put (car pair) (cdr pair)))))
731 (mapc togtag org-bibtex-tags)))
750 (org-bibtex-put (car pair) (cdr pair) 'insert)))
751 (_ (org-bibtex-put (car pair) (cdr pair) 'insert))))
752 (insert ":END:\n")
753 (mapc togtag org-bibtex-tags)
754 (unless noindent
755 (org-indent-region
756 (save-excursion (org-back-to-heading t) (point))
757 (point)))))
732758
733759 (defun org-bibtex-yank ()
734760 "If kill ring holds a bibtex entry yank it as an Org headline."
735761 (interactive)
736762 (let (entry)
737 (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
763 (with-temp-buffer
764 (yank 1)
765 (bibtex-mode)
766 (setf entry (org-bibtex-read)))
738767 (if entry
739768 (org-bibtex-write)
740769 (error "Yanked text does not appear to contain a BibTeX entry"))))
742771 (defun org-bibtex-import-from-file (file)
743772 "Read bibtex entries from FILE and insert as Org headlines after point."
744773 (interactive "fFile: ")
745 (dotimes (_ (org-bibtex-read-file file))
746 (save-excursion (org-bibtex-write))
747 (re-search-forward org-property-end-re)
748 (open-line 1) (forward-char 1)))
774 (let ((pos (point)))
775 (dotimes (_ (org-bibtex-read-file file))
776 (save-excursion (org-bibtex-write 'noindent))
777 (re-search-forward org-property-end-re)
778 (insert "\n"))
779 (org-indent-region pos (point))))
749780
750781 (defun org-bibtex-export-to-kill-ring ()
751782 "Export current headline to kill ring as bibtex entry."
00 ;;; ol-docview.el --- Links to Docview mode buffers -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Jan Böcker <jan.boecker at jboecker dot de>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
4141
4242 ;;; Code:
4343
44 (require 'org-macs)
45 (org-assert-version)
4446
4547 (require 'doc-view)
4648 (require 'ol)
7476 (string-to-number (match-string 2 link)))))
7577 ;; Let Org mode open the file (in-emacs = 1) to ensure
7678 ;; org-link-frame-setup is respected.
77 (org-open-file path 1)
79 (if (file-exists-p path)
80 (org-open-file path 1)
81 (error "No such file: %s" path))
7882 (when page (doc-view-goto-page page))))
7983
8084 (defun org-docview-store-link ()
00 ;;; ol-doi.el --- DOI links support in Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55
2525
2626 ;;; Code:
2727
28 (require 'org-macs)
29 (org-assert-version)
30
2831 (require 'ol)
2932
3033 (defcustom org-link-doi-server-url "https://doi.org/"
4346 "Export a \"doi\" type link.
4447 PATH is the DOI name. DESC is the description of the link, or
4548 nil. BACKEND is a symbol representing the backend used for
46 export. INFO is a a plist containing the export parameters."
49 export. INFO is a plist containing the export parameters."
4750 (let ((uri (concat org-link-doi-server-url path)))
4851 (pcase backend
4952 (`html
00 ;;; ol-eshell.el --- Links to Working Directories in Eshell -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2011-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2011-2023 Free Software Foundation, Inc.
33
44 ;; Author: Konrad Hinsen <konrad.hinsen AT fastmail.net>
55
2121 ;;; Commentary:
2222
2323 ;;; Code:
24
25 (require 'org-macs)
26 (org-assert-version)
2427
2528 (require 'eshell)
2629 (require 'esh-mode)
4548 (eshell-buffer-name (car buffer-and-command))
4649 (command (cadr buffer-and-command)))
4750 (if (get-buffer eshell-buffer-name)
48 (pop-to-buffer-same-window eshell-buffer-name)
51 (pop-to-buffer
52 eshell-buffer-name
53 (if (boundp 'display-comint-buffer-action) ; Emacs >= 29
54 display-comint-buffer-action
55 '(display-buffer-same-window (inhibit-same-window))))
4956 (eshell))
5057 (goto-char (point-max))
5158 (eshell-kill-input)
00 ;;; ol-eww.el --- Store URL and kill from Eww mode -*- lexical-binding: t -*-
11
2 ;; Copyright (C) 2014-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2014-2023 Free Software Foundation, Inc.
33
44 ;; Author: Marco Wahl <marcowahlsoft>a<gmailcom>
55 ;; Keywords: link, eww
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
4343
4444
4545 ;;; Code:
46
47 (require 'org-macs)
48 (org-assert-version)
49
4650 (require 'ol)
4751 (require 'cl-lib)
4852 (require 'eww)
49
50 ;; For Emacsen < 25.
51 (defvar eww-current-title)
52 (defvar eww-current-url)
5353
5454
5555 ;; Store Org link in Eww mode buffer
6666 (when (eq major-mode 'eww-mode)
6767 (org-link-store-props
6868 :type "eww"
69 :link (if (< emacs-major-version 25)
70 eww-current-url
71 (eww-current-url))
69 :link (eww-current-url)
7270 :url (url-view-url t)
73 :description (if (< emacs-major-version 25)
74 (or eww-current-title eww-current-url)
75 (or (plist-get eww-data :title)
76 (eww-current-url))))))
71 :description (or (plist-get eww-data :title)
72 (eww-current-url)))))
7773
7874
7975 ;; Some auxiliary functions concerning links in Eww buffers
114110 (setq transform-start (region-beginning))
115111 (setq transform-end (region-end))
116112 ;; Deactivate mark if current mark is activate.
117 (when (fboundp 'deactivate-mark) (deactivate-mark)))
113 (deactivate-mark))
118114 (message "Transforming links...")
119115 (save-excursion
120116 (goto-char transform-start)
00 ;;; ol-gnus.el --- Links to Gnus Groups and Messages -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Tassilo Horn <tassilo at member dot fsf dot org>
66 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88 ;;
99 ;; This file is part of GNU Emacs.
1010 ;;
2929 ;; configure the variable `org-modules'.
3030
3131 ;;; Code:
32
33 (require 'org-macs)
34 (org-assert-version)
3235
3336 (require 'gnus-sum)
3437 (require 'gnus-util)
7073
7174 (defcustom org-gnus-no-server nil
7275 "Should Gnus be started using `gnus-no-server'?"
73 :group 'org-gnus
76 :group 'org-link-follow
7477 :version "24.4"
7578 :package-version '(Org . "8.0")
7679 :type 'boolean)
00 ;;; ol-info.el --- Links to Info Nodes -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2929
3030 ;;; Code:
3131
32 (require 'org-macs)
33 (org-assert-version)
34
3235 (require 'ol)
3336
3437 ;; Declare external functions and variables
4245 (org-link-set-parameters "info"
4346 :follow #'org-info-open
4447 :export #'org-info-export
45 :store #'org-info-store-link)
48 :store #'org-info-store-link
49 :insert-description #'org-info-description-as-command)
4650
4751 ;; Implementation
4852 (defun org-info-store-link ()
6266 "Follow an Info file and node link specified by PATH."
6367 (org-info-follow-link path))
6468
69 (defun org-info--link-file-node (path)
70 "Extract file name and node from info link PATH.
71
72 Return cons consisting of file name and node name or \"Top\" if node
73 part is not specified. Components may be separated by \":\" or by \"#\".
74 File may be a virtual one, see `Info-virtual-files'."
75 (if (not path)
76 '("dir" . "Top")
77 (string-match "\\`\\([^#:]*\\)\\(?:[#:]:?\\(.*\\)\\)?\\'" path)
78 (let* ((node (match-string 2 path))
79 ;; Do not reorder, `org-trim' modifies match.
80 (file (org-trim (match-string 1 path))))
81 (cons
82 (if (org-string-nw-p file) file "dir")
83 (if (org-string-nw-p node) (org-trim node) "Top")))))
84
85 (defun org-info-description-as-command (link desc)
86 "Info link description that can be pasted as command.
87
88 For the following LINK
89
90 \"info:elisp#Non-ASCII in Strings\"
91
92 the result is
93
94 info \"(elisp) Non-ASCII in Strings\"
95
96 that may be executed as shell command or evaluated by
97 \\[eval-expression] (wrapped with parenthesis) to read the manual
98 in Emacs.
99
100 Calling convention is similar to `org-link-make-description-function'.
101 DESC has higher priority and returned when it is not nil or empty string.
102 If LINK is not an info link then DESC is returned."
103 (let* ((prefix "info:")
104 (need-file-node (and (not (org-string-nw-p desc))
105 (string-prefix-p prefix link))))
106 (pcase (and need-file-node
107 (org-info--link-file-node (org-unbracket-string prefix "" link)))
108 ;; Unlike (info "dir"), "info dir" shell command opens "(coreutils)dir invocation".
109 (`("dir" . "Top") "info \"(dir)\"")
110 (`(,file . "Top") (format "info %s" file))
111 (`(,file . ,node) (format "info \"(%s) %s\"" file node))
112 (_ desc))))
65113
66114 (defun org-info-follow-link (name)
67115 "Follow an Info file and node link specified by NAME."
68 (if (or (string-match "\\(.*\\)\\(?:#\\|::\\)\\(.*\\)" name)
69 (string-match "\\(.*\\)" name))
70 (let ((filename (match-string 1 name))
71 (nodename-or-index (or (match-string 2 name) "Top")))
72 (require 'info)
73 ;; If nodename-or-index is invalid node name, then look it up
74 ;; in the index.
75 (condition-case nil
76 (Info-find-node filename nodename-or-index)
77 (user-error (Info-find-node filename "Top")
78 (condition-case nil
79 (Info-index nodename-or-index)
80 (user-error "Could not find '%s' node or index entry"
81 nodename-or-index)))))
82 (user-error "Could not open: %s" name)))
116 (pcase-let ((`(,filename . ,nodename-or-index)
117 (org-info--link-file-node name)))
118 (require 'info)
119 ;; If nodename-or-index is invalid node name, then look it up
120 ;; in the index.
121 (condition-case nil
122 (Info-find-node filename nodename-or-index)
123 (user-error (Info-find-node filename "Top")
124 (condition-case nil
125 (Info-index nodename-or-index)
126 (user-error "Could not find '%s' node or index entry"
127 nodename-or-index))))))
83128
84129 (defconst org-info-emacs-documents
85130 '("ada-mode" "auth" "autotype" "bovine" "calc" "ccmode" "cl" "dbus" "dired-x"
94139 Taken from <https://www.gnu.org/software/emacs/manual/html_mono/.>")
95140
96141 (defconst org-info-other-documents
97 '(("libc" . "https://www.gnu.org/software/libc/manual/html_mono/libc.html")
142 '(("dir" . "https://www.gnu.org/manual/manual.html") ; index
143 ("libc" . "https://www.gnu.org/software/libc/manual/html_mono/libc.html")
98144 ("make" . "https://www.gnu.org/software/make/manual/make.html"))
99145 "Alist of documents generated from Texinfo source.
100146 When converting info links to HTML, links to any one of these manuals are
128174 (defun org-info-export (path desc format)
129175 "Export an info link.
130176 See `org-link-parameters' for details about PATH, DESC and FORMAT."
131 (let* ((parts (split-string path "#\\|::"))
132 (manual (car parts))
133 (node (or (nth 1 parts) "Top")))
177 (pcase-let ((`(,manual . ,node) (org-info--link-file-node path)))
134178 (pcase format
135179 (`html
136180 (format "<a href=\"%s#%s\">%s</a>"
00 ;;; ol-irc.el --- Links to IRC Sessions -*- lexical-binding: t; -*-
11 ;;
2 ;; Copyright (C) 2008-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2008-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Philip Jackson <emacs@shellarchive.co.uk>
55 ;; Keywords: erc, irc, link, org
4646 ;; requested server then one will be created.
4747
4848 ;;; Code:
49
50 (require 'org-macs)
51 (org-assert-version)
4952
5053 (require 'ol)
5154
134137 ;; can we get a '::' part?
135138 (if (string= erc-line (erc-prompt))
136139 (progn
137 (goto-char (point-at-bol))
140 (goto-char (line-beginning-position))
138141 (when (search-backward-regexp "^[^ ]" nil t)
139 (buffer-substring-no-properties (point-at-bol)
140 (point-at-eol))))
142 (buffer-substring-no-properties (line-beginning-position)
143 (line-end-position))))
141144 (when (search-backward erc-line nil t)
142 (buffer-substring-no-properties (point-at-bol)
143 (point-at-eol)))))))
145 (buffer-substring-no-properties (line-beginning-position)
146 (line-end-position)))))))
144147
145148 (defun org-irc-erc-store-link ()
146149 "Store a link to the IRC log file or the session itself.
150153 (require 'erc-log)
151154 (if org-irc-link-to-logs
152155 (let* ((erc-line (buffer-substring-no-properties
153 (point-at-bol) (point-at-eol)))
156 (line-beginning-position) (line-end-position)))
154157 (parsed-line (org-irc-erc-get-line-from-log erc-line)))
155158 (if (erc-logging-enabled nil)
156159 (progn
00 ;;; ol-man.el --- Links to man pages -*- lexical-binding: t; -*-
11 ;;
2 ;; Copyright (C) 2020-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2020-2023 Free Software Foundation, Inc.
33 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
44 ;; Maintainer: Bastien Guerry <bzg@gnu.org>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
10 ;; This program is free software; you can redistribute it and/or modify
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
1111 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 3, or (at your option)
13 ;; any later version.
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
1414
15 ;; This program is distributed in the hope that it will be useful,
15 ;; GNU Emacs is distributed in the hope that it will be useful,
1616 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
1717 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1818 ;; GNU General Public License for more details.
2222 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2323 ;;
2424 ;;; Commentary:
25
26 (require 'org-macs)
27 (org-assert-version)
2528
2629 (require 'ol)
2730
4245 matched strings in man buffer."
4346 (string-match "\\(.*?\\)\\(?:::\\(.*\\)\\)?$" path)
4447 (let* ((command (match-string 1 path))
45 (search (match-string 2 path)))
46 (funcall org-man-command command)
48 (search (match-string 2 path))
49 (buffer (funcall org-man-command command)))
4750 (when search
48 (with-current-buffer (concat "*Man " command "*")
49 (goto-char (point-min))
50 (search-forward search)))))
51 (with-current-buffer buffer
52 (goto-char (point-min))
53 (unless (search-forward search nil t)
54 (let ((process (get-buffer-process buffer)))
55 (while (process-live-p process)
56 (accept-process-output process)))
57 (goto-char (point-min))
58 (search-forward search))
59 (forward-line -1)
60 (let ((point (point)))
61 (let ((window (get-buffer-window buffer)))
62 (set-window-point window point)
63 (set-window-start window point)))))))
5164
5265 (defun org-man-store-link ()
5366 "Store a link to a README file."
00 ;;; ol-mhe.el --- Links to MH-E Messages -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Thomas Baumann <thomas dot baumann at ch dot tum dot de>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2828 ;; configure the variable `org-modules'.
2929
3030 ;;; Code:
31
32 (require 'org-macs)
33 (org-assert-version)
3134
3235 (require 'org-macs)
3336 (require 'ol)
00 ;;; ol-rmail.el --- Links to Rmail Messages -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2828 ;; want, configure the variable `org-modules'.
2929
3030 ;;; Code:
31
32 (require 'org-macs)
33 (org-assert-version)
3134
3235 (require 'ol)
3336
00 ;;; ol-w3m.el --- Copy and Paste From W3M -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2008-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2008-2023 Free Software Foundation, Inc.
33
44 ;; Author: Andy Stewart <lazycat dot manatee at gmail dot com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99
3939 ;;
4040
4141 ;;; Code:
42
43 (require 'org-macs)
44 (org-assert-version)
4245
4346 (require 'ol)
4447
7174 (setq transform-start (region-beginning))
7275 (setq transform-end (region-end))
7376 ;; Deactivate mark if current mark is activate.
74 (when (fboundp 'deactivate-mark) (deactivate-mark)))
77 (deactivate-mark))
7578 (message "Transforming links...")
7679 (save-excursion
7780 (goto-char transform-start)
00 ;;; ol.el --- Org links library -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2018-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2018-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
2626
2727 ;;; Code:
2828
29 (require 'org-macs)
30 (org-assert-version)
31
2932 (require 'org-compat)
3033 (require 'org-macs)
34 (require 'org-fold)
3135
3236 (defvar clean-buffer-list-kill-buffer-names)
3337 (defvar org-agenda-buffer-name)
3741 (defvar org-inhibit-startup)
3842 (defvar org-outline-regexp-bol)
3943 (defvar org-src-source-file-name)
40 (defvar org-time-stamp-formats)
4144 (defvar org-ts-regexp)
4245
4346 (declare-function calendar-cursor-to-date "calendar" (&optional error event))
4649 (declare-function org-back-to-heading "org" (&optional invisible-ok))
4750 (declare-function org-before-first-heading-p "org" ())
4851 (declare-function org-do-occur "org" (regexp &optional cleanup))
49 (declare-function org-element-at-point "org-element" ())
52 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
5053 (declare-function org-element-cache-refresh "org-element" (pos))
5154 (declare-function org-element-context "org-element" (&optional element))
5255 (declare-function org-element-lineage "org-element" (datum &optional types with-self))
6568 (declare-function org-mode "org" ())
6669 (declare-function org-occur "org" (regexp &optional keep-previous callback))
6770 (declare-function org-open-file "org" (path &optional in-emacs line search))
68 (declare-function org-overview "org" ())
71 (declare-function org-cycle-overview "org-cycle" ())
6972 (declare-function org-restart-font-lock "org" ())
7073 (declare-function org-run-like-in-org-mode "org" (cmd))
71 (declare-function org-show-context "org" (&optional key))
74 (declare-function org-fold-show-context "org-fold" (&optional key))
7275 (declare-function org-src-coderef-format "org-src" (&optional element))
7376 (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
7477 (declare-function org-src-edit-buffer-p "org-src" (&optional buffer))
139142 Function that inserts a link with completion. The function
140143 takes one optional prefix argument.
141144
145 `:insert-description'
146
147 String or function used as a default when prompting users for a
148 link's description. A string is used as-is, a function is
149 called with two arguments: the link location (a string such as
150 \"~/foobar\", \"id:some-org-id\" or \"https://www.foo.com\")
151 and the description generated by `org-insert-link'. It should
152 return the description to use (this reflects the behavior of
153 `org-link-make-description-function'). If it returns nil, no
154 default description is used, but no error is thrown (from the
155 user's perspective, this is equivalent to a default description
156 of \"\").
157
142158 `:display'
143159
144160 Value for `invisible' text property on the hidden parts of the
182198 (defcustom org-link-descriptive t
183199 "Non-nil means Org displays descriptive links.
184200
185 E.g. [[https://orgmode.org][Org website]] is be displayed as
201 E.g. [[https://orgmode.org][Org website]] is displayed as
186202 \"Org Website\", hiding the link itself and just displaying its
187203 description. When set to nil, Org displays the full links
188204 literally.
198214 This function must take two parameters: the first one is the
199215 link, the second one is the description generated by
200216 `org-insert-link'. The function should return the description to
201 use."
217 use. If it returns nil, no default description is used, but no
218 error is thrown (from the user’s perspective, this is equivalent
219 to a default description of \"\")."
202220 :group 'org-link
203221 :type '(choice (const nil) (function))
204222 :safe #'null)
338356 (defcustom org-link-search-must-match-exact-headline 'query-to-create
339357 "Non-nil means internal fuzzy links can only match headlines.
340358
341 When nil, the a fuzzy link may point to a target or a named
359 When nil, the fuzzy link may point to a target or a named
342360 construct in the document. When set to the special value
343361 `query-to-create', offer to create a new headline when none
344362 matched.
602620
603621 (defvar org-link--search-failed nil
604622 "Non-nil when last link search failed.")
623
624
625 (defvar-local org-link--link-folding-spec '(org-link
626 (:global t)
627 (:ellipsis . nil)
628 (:isearch-open . t)
629 (:fragile . org-link--reveal-maybe))
630 "Folding spec used to hide invisible parts of links.")
631
632 (defvar-local org-link--description-folding-spec '(org-link-description
633 (:global t)
634 (:ellipsis . nil)
635 (:visible . t)
636 (:isearch-open . nil)
637 (:fragile . org-link--reveal-maybe))
638 "Folding spec used to reveal link description.")
605639
606640
607641 ;;; Internal Functions
645679 (cons 6 128))))
646680 (when (>= val 192) (setq eat (car shift-xor)))
647681 (setq val (logxor val (cdr shift-xor)))
648 (setq sum (+ (lsh sum (car shift-xor)) val))
682 (setq sum (+ (ash sum (car shift-xor)) val))
649683 (when (> eat 0) (setq eat (- eat 1)))
650684 (cond
651685 ((= 0 eat) ;multi byte
699733 (make-indirect-buffer (current-buffer)
700734 indirect-buffer-name
701735 'clone))))
702 (with-current-buffer indirect-buffer (org-overview))
736 (with-current-buffer indirect-buffer (org-cycle-overview))
703737 indirect-buffer))))
704738
705739 (defun org-link--search-radio-target (target)
717751 (let ((object (org-element-context)))
718752 (when (eq (org-element-type object) 'radio-target)
719753 (goto-char (org-element-property :begin object))
720 (org-show-context 'link-search)
754 (org-fold-show-context 'link-search)
721755 (throw :radio-match nil))))
722756 (goto-char origin)
723757 (user-error "No match for radio target: %s" target))))
759793 (setq string (substring string (match-end 0))))
760794 (t nil))))
761795 string))
796
797 (defun org-link--reveal-maybe (region _)
798 "Reveal folded link in REGION when needed.
799 This function is intended to be used as :fragile property of a folding
800 spec."
801 (org-with-point-at (car region)
802 (not (org-in-regexp org-link-any-re))))
762803
763804
764805 ;;; Public API
936977
937978 (defun org-link-decode (s)
938979 "Decode percent-encoded parts in string S.
939 E.g. \"%C3%B6\" becomes the german o-Umlaut."
980 E.g. \"%C3%B6\" becomes the German o-Umlaut."
940981 (replace-regexp-in-string "\\(%[0-9A-Za-z]\\{2\\}\\)+"
941982 #'org-link--decode-compound s t t))
942983
9741015 (replace-regexp-in-string "]\\'"
9751016 (concat "\\&" zero-width-space)
9761017 (org-trim description))))))
977 (if (not (org-string-nw-p link)) description
1018 (if (not (org-string-nw-p link))
1019 (or description
1020 (error "Empty link"))
9781021 (format "[[%s]%s]"
9791022 (org-link-escape link)
9801023 (if description (format "[%s]" description) "")))))
12561299 (error "No match for fuzzy expression: %s" normalized)))
12571300 ;; Disclose surroundings of match, if appropriate.
12581301 (when (and (derived-mode-p 'org-mode) (not stealth))
1259 (org-show-context 'link-search))
1302 (org-fold-show-context 'link-search))
12601303 type))
12611304
12621305 (defun org-link-heading-search-string (&optional string)
13211364 (string-match-p org-link-elisp-skip-confirm-regexp path))
13221365 (not org-link-elisp-confirm-function)
13231366 (funcall org-link-elisp-confirm-function
1324 (format "Execute %S as Elisp? "
1367 (format "Execute %s as Elisp? "
13251368 (org-add-props path nil 'face 'org-warning))))
13261369 (message "%s => %s" path
13271370 (if (eq ?\( (string-to-char path))
13761419 (string-match-p org-link-shell-skip-confirm-regexp path))
13771420 (not org-link-shell-confirm-function)
13781421 (funcall org-link-shell-confirm-function
1379 (format "Execute %S in shell? "
1422 (format "Execute %s in shell? "
13801423 (org-add-props path nil 'face 'org-warning))))
13811424 (let ((buf (generate-new-buffer "*Org Shell Output*")))
13821425 (message "Executing %s" path)
14291472 (`nil nil)
14301473 (link
14311474 (goto-char (org-element-property :begin link))
1432 (when (org-invisible-p) (org-show-context))
1475 (when (org-invisible-p) (org-fold-show-context 'link-search))
14331476 (throw :found t)))))
14341477 (goto-char pos)
14351478 (setq org-link--search-failed t)
14421485 (interactive)
14431486 (org-next-link t))
14441487
1488 (defun org-link-descriptive-ensure ()
1489 "Toggle the literal or descriptive display of links in current buffer if needed."
1490 (org-fold-core-set-folding-spec-property
1491 (car org-link--link-folding-spec)
1492 :visible (not org-link-descriptive)))
1493
14451494 ;;;###autoload
14461495 (defun org-toggle-link-display ()
1447 "Toggle the literal or descriptive display of links."
1496 "Toggle the literal or descriptive display of links in current buffer."
14481497 (interactive)
1449 (if org-link-descriptive (remove-from-invisibility-spec '(org-link))
1450 (add-to-invisibility-spec '(org-link)))
1451 (org-restart-font-lock)
1452 (setq org-link-descriptive (not org-link-descriptive)))
1498 (setq org-link-descriptive (not org-link-descriptive))
1499 (org-link-descriptive-ensure))
14531500
14541501 ;;;###autoload
14551502 (defun org-store-link (arg &optional interactive?)
14801527 (let ((end (region-end)))
14811528 (goto-char (region-beginning))
14821529 (set-mark (point))
1483 (while (< (point-at-eol) end)
1530 (while (< (line-end-position) end)
14841531 (move-end-of-line 1) (activate-mark)
14851532 (let (current-prefix-arg)
14861533 (call-interactively 'org-store-link))
15181565 t))))
15191566 (setq link (plist-get org-store-link-plist :link))
15201567 ;; If store function actually set `:description' property, use
1521 ;; it, even if it is nil. Otherwise, fallback to link value.
1522 (setq desc (if (plist-member org-store-link-plist :description)
1523 (plist-get org-store-link-plist :description)
1524 link)))
1568 ;; it, even if it is nil. Otherwise, fallback to nil (ask user).
1569 (setq desc (plist-get org-store-link-plist :description)))
15251570
15261571 ;; Store a link from a remote editing buffer.
15271572 ((org-src-edit-buffer-p)
15621607 (t (setq link nil)))))
15631608
15641609 ;; We are in the agenda, link to referenced location
1565 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
1610 ((eq major-mode 'org-agenda-mode)
15661611 (let ((m (or (get-text-property (point) 'org-hd-marker)
15671612 (get-text-property (point) 'org-marker))))
15681613 (when m
15731618 (let ((cd (calendar-cursor-to-date)))
15741619 (setq link
15751620 (format-time-string
1576 (car org-time-stamp-formats)
1577 (apply 'encode-time
1578 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
1579 nil nil nil))))
1621 (org-time-stamp-format)
1622 (org-encode-time 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd))))
15801623 (org-link-store-props :type "calendar" :date cd)))
1581
1582 ((eq major-mode 'w3-mode)
1583 (setq cpltxt (if (and (buffer-name)
1584 (not (string-match "Untitled" (buffer-name))))
1585 (buffer-name)
1586 (url-view-url t))
1587 link (url-view-url t))
1588 (org-link-store-props :type "w3" :url (url-view-url t)))
15891624
15901625 ((eq major-mode 'image-mode)
15911626 (setq cpltxt (concat "file:"
15991634 (setq file (if file
16001635 (abbreviate-file-name
16011636 (expand-file-name (dired-get-filename nil t)))
1602 ;; otherwise, no file so use current directory.
1637 ;; Otherwise, no file so use current directory.
16031638 default-directory))
16041639 (setq cpltxt (concat "file:" file)
16051640 link cpltxt)))
16121647
16131648 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
16141649 (org-with-limited-levels
1615 (cond
1616 ;; Store a link using the target at point.
1650 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
1651 (cond
1652 ;; Store a link using the target at point
16171653 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
1618 (setq cpltxt
1654 (setq link
16191655 (concat "file:"
16201656 (abbreviate-file-name
16211657 (buffer-file-name (buffer-base-buffer)))
16221658 "::" (match-string 1))
1623 link cpltxt))
1624 ;; Store a link using the CUSTOM_ID property.
1625 ((setq custom-id (org-entry-get nil "CUSTOM_ID"))
1626 (setq cpltxt
1627 (concat "file:"
1628 (abbreviate-file-name
1629 (buffer-file-name (buffer-base-buffer)))
1630 "::#" custom-id)
1631 link cpltxt))
1632 ;; Store a link using (and perhaps creating) the ID property.
1659 ;; Target may be shortened when link is inserted.
1660 ;; Avoid [[target][file:~/org/test.org::target]]
1661 ;; links. Maybe the case of identical target and
1662 ;; description should be handled by `org-insert-link'.
1663 cpltxt nil
1664 desc nil
1665 ;; Do not append #CUSTOM_ID link below.
1666 custom-id nil))
16331667 ((and (featurep 'org-id)
16341668 (or (eq org-id-link-to-org-use-id t)
16351669 (and interactive?
16381672 'create-if-interactive-and-no-custom-id)
16391673 (not custom-id))))
16401674 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
1675 ;; Store a link using the ID at point
16411676 (setq link (condition-case nil
16421677 (prog1 (org-id-store-link)
1643 (setq desc (or (plist-get org-store-link-plist
1644 :description)
1645 "")))
1678 (setq desc (plist-get org-store-link-plist :description)))
16461679 (error
1647 ;; Probably before first headline, link only to file.
1680 ;; Probably before first headline, link only to file
16481681 (concat "file:"
16491682 (abbreviate-file-name
16501683 (buffer-file-name (buffer-base-buffer))))))))
17041737
17051738 ;; We're done setting link and desc, clean up
17061739 (when (consp link) (setq cpltxt (car link) link (cdr link)))
1707 (setq link (or link cpltxt)
1708 desc (or desc cpltxt))
1740 (setq link (or link cpltxt))
17091741 (cond ((not desc))
17101742 ((equal desc "NONE") (setq desc nil))
17111743 (t (setq desc (org-link-display-format desc))))
17351767 press `RET' at the prompt), the link defaults to the most recently
17361768 stored link. As `SPC' triggers completion in the minibuffer, you need to
17371769 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
1770 Completion candidates include link descriptions.
1771
1772 If there is a link under cursor then edit it.
17381773
17391774 You will also be prompted for a description, and if one is given, it will
17401775 be displayed in the buffer instead of the link.
17601795 If the LINK-LOCATION parameter is non-nil, this value will be used as
17611796 the link location instead of reading one interactively.
17621797
1763 If the DESCRIPTION parameter is non-nil, this value will be used as the
1764 default description. Otherwise, if `org-link-make-description-function'
1765 is non-nil, this function will be called with the link target, and the
1766 result will be the default link description. When called non-interactively,
1767 don't allow to edit the default description."
1798 If the DESCRIPTION parameter is non-nil, this value will be used
1799 as the default description. If not, and the chosen link type has
1800 a non-nil `:insert-description' parameter, that is used to
1801 generate a description as described in `org-link-parameters'
1802 docstring. Otherwise, if `org-link-make-description-function' is
1803 non-nil, this function will be called with the link target, and
1804 the result will be the default link description. When called
1805 non-interactively, don't allow to edit the default description."
17681806 (interactive "P")
17691807 (let* ((wcf (current-window-configuration))
17701808 (origbuf (current-buffer))
17741812 (desc region)
17751813 (link link-location)
17761814 (abbrevs org-link-abbrev-alist-local)
1777 entry all-prefixes auto-desc)
1815 (all-prefixes (append (mapcar #'car abbrevs)
1816 (mapcar #'car org-link-abbrev-alist)
1817 (org-link-types)))
1818 entry)
17781819 (cond
17791820 (link-location) ; specified by arg, just use it.
17801821 ((org-in-regexp org-link-bracket-re 1)
18151856 (unless (pos-visible-in-window-p (point-max))
18161857 (org-fit-window-to-buffer))
18171858 (and (window-live-p cw) (select-window cw))))
1818 (setq all-prefixes (append (mapcar #'car abbrevs)
1819 (mapcar #'car org-link-abbrev-alist)
1820 (org-link-types)))
18211859 (unwind-protect
18221860 ;; Fake a link history, containing the stored links.
18231861 (let ((org-link--history
18281866 "Link: "
18291867 (append
18301868 (mapcar (lambda (x) (concat x ":")) all-prefixes)
1831 (mapcar #'car org-stored-links))
1869 (mapcar #'car org-stored-links)
1870 ;; Allow description completion. Avoid "nil" option
1871 ;; in the case of `completing-read-default' and
1872 ;; an error in `ido-completing-read' when some links
1873 ;; have no description.
1874 (delq nil (mapcar 'cadr org-stored-links)))
18321875 nil nil nil
18331876 'org-link--history
18341877 (caar org-stored-links)))
18351878 (unless (org-string-nw-p link) (user-error "No link selected"))
18361879 (dolist (l org-stored-links)
18371880 (when (equal link (cadr l))
1838 (setq link (car l))
1839 (setq auto-desc t)))
1881 (setq link (car l))))
18401882 (when (or (member link all-prefixes)
18411883 (and (equal ":" (substring link -1))
18421884 (member (substring link 0 -1) all-prefixes)
19131955 (when (equal desc origpath)
19141956 (setq desc path)))))
19151957
1916 (unless auto-desc
1917 (let ((initial-input
1918 (cond
1919 (description)
1920 ((not org-link-make-description-function) desc)
1921 (t (condition-case nil
1922 (funcall org-link-make-description-function link desc)
1923 (error
1924 (message "Can't get link description from %S"
1925 (symbol-name org-link-make-description-function))
1926 (sit-for 2)
1927 nil))))))
1928 (setq desc (if (called-interactively-p 'any)
1929 (read-string "Description: " initial-input)
1930 initial-input))))
1958 (let* ((type
1959 (cond
1960 ((and all-prefixes
1961 (string-match (rx-to-string `(: string-start (submatch (or ,@all-prefixes)) ":")) link))
1962 (match-string 1 link))
1963 ((file-name-absolute-p link) "file")
1964 ((string-match "\\`\\.\\.?/" link) "file")))
1965 (initial-input
1966 (cond
1967 (description)
1968 (desc)
1969 ((org-link-get-parameter type :insert-description)
1970 (let ((def (org-link-get-parameter type :insert-description)))
1971 (condition-case nil
1972 (cond
1973 ((stringp def) def)
1974 ((functionp def)
1975 (funcall def link desc)))
1976 (error
1977 (message "Can't get link description from org link parameter `:insert-description': %S"
1978 def)
1979 (sit-for 2)
1980 nil))))
1981 (org-link-make-description-function
1982 (condition-case nil
1983 (funcall org-link-make-description-function link desc)
1984 (error
1985 (message "Can't get link description from %S"
1986 org-link-make-description-function)
1987 (sit-for 2)
1988 nil))))))
1989 (setq desc (if (called-interactively-p 'any)
1990 (read-string "Description: " initial-input)
1991 initial-input)))
19311992
19321993 (unless (org-string-nw-p desc) (setq desc nil))
19331994 (when remove (apply #'delete-region remove))
19962057 (cl-pushnew (org-element-property :value obj) rtn
19972058 :test #'equal))))
19982059 rtn))))
2060 (setq targets
2061 (sort targets
2062 (lambda (a b)
2063 (> (length a) (length b)))))
19992064 (setq org-target-link-regexp
20002065 (and targets
20012066 (concat before-re
20192084 (list old-regexp org-target-link-regexp)
20202085 "\\|")
20212086 after-re)))))
2022 (when (featurep 'org-element)
2087 (when (and (featurep 'org-element)
2088 (not (bound-and-true-p org-mode-loading)))
20232089 (org-with-point-at 1
20242090 (while (re-search-forward regexp nil t)
20252091 (org-element-cache-refresh (match-beginning 1))))))
00 ;;; org-agenda.el --- Dynamic task and appointment lists for Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
4444
4545 ;;; Code:
4646
47 (require 'org-macs)
48 (org-assert-version)
49
4750 (require 'cl-lib)
4851 (require 'ol)
52 (require 'org-fold-core)
4953 (require 'org)
5054 (require 'org-macs)
5155 (require 'org-refile)
56 (require 'org-element)
5257
5358 (declare-function diary-add-to-list "diary-lib"
5459 (date string specifier &optional marker globcolor literal))
96101
97102 ;; Defined somewhere in this file, but used before definition.
98103 (defvar org-agenda-buffer-name "*Org Agenda*")
99 (defvar org-agenda-overriding-header nil)
100104 (defvar org-agenda-title-append nil)
105 (defvar org-agenda-overriding-header)
101106 ;; (with-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
102107 ;; (with-no-warnings (defvar date)) ;; unprefixed, from calendar.el
103108 (defvar original-date) ; dynamically scoped, calendar.el does scope this
124129 :group 'org-agenda
125130 :type 'boolean)
126131
127 (defcustom org-agenda-block-separator ?=
132 (defcustom org-agenda-block-separator
133 (if (and (display-graphic-p)
134 (char-displayable-p ?─))
135 ?─
136 ?=)
128137 "The separator between blocks in the agenda.
129138 If this is a string, it will be used as the separator, with a newline added.
130139 If it is a character, it will be repeated to fill the window width.
131140 If nil the separator is disabled. In `org-agenda-custom-commands' this
132141 addresses the separator between the current and the previous block."
133142 :group 'org-agenda
143 :package-version '(Org . "9.6")
134144 :type '(choice
135145 (const :tag "Disabled" nil)
136146 (character)
455465
456466 key The key (one or more characters as a string) to be associated
457467 with the command.
458 desc A description of the command, when omitted or nil, a default
468 desc A description of the command. When omitted or nil, a default
459469 description is built using MATCH.
460470 type The command type, any of the following symbols:
461471 agenda The daily/weekly agenda.
472 agenda* Appointments for current week/day.
462473 todo Entries with a specific TODO keyword, in all agenda files.
463474 search Entries containing search words entry or headline.
464475 tags Tags/Property/TODO match in all agenda files.
466477 todo-tree Sparse tree of specific TODO keyword in *current* file.
467478 tags-tree Sparse tree with all tags matches in *current* file.
468479 occur-tree Occur sparse tree for *current* file.
480 alltodo The global TODO list.
481 stuck Stuck projects.
469482 ... A user-defined function.
470483 match What to search for:
471484 - a single keyword for TODO keyword searches
479492 files A list of files to write the produced agenda buffer to with
480493 the command `org-store-agenda-views'.
481494 If a file name ends in \".html\", an HTML version of the buffer
482 is written out. If it ends in \".ps\", a postscript version is
495 is written out. If it ends in \".ps\", a PostScript version is
483496 produced. Otherwise, only the plain text is written to the file.
484497
485498 You can also define a set of commands, to create a composite agenda buffer.
491504
492505 desc A description string to be displayed in the dispatcher menu.
493506 cmd An agenda command, similar to the above. However, tree commands
494 are not allowed, but instead you can get agenda and global todo list.
495 So valid commands for a set are:
507 are not allowed. Valid commands for a set are:
496508 (agenda \"\" settings)
509 (agenda* \"\" settings)
497510 (alltodo \"\" settings)
498511 (stuck \"\" settings)
499512 (todo \"match\" settings files)
513526 \\='((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
514527 (\"hl\" tags \"+HOME+Lisa\")
515528 (\"hp\" tags \"+HOME+Peter\")
516 (\"hk\" tags \"+HOME+Kim\")))"
529 (\"hk\" tags \"+HOME+Kim\")))
530
531 See also Info node `(org) Custom Agenda Views'."
517532 :group 'org-agenda-custom-commands
518533 :type `(repeat
519534 (choice :value ("x" "Describe command here" tags "" nil)
592607 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
593608 "How to identify stuck projects.
594609 This is a list of four items:
610
595611 1. A tags/todo/property matcher string that is used to identify a project.
596 See the manual for a description of tag and property searches.
597 The entire tree below a headline matched by this is considered one project.
612 See Info node `(org) Matching tags and properties' for a
613 description of tag and property searches. The entire tree
614 below a headline matched by this is considered one project.
615
598616 2. A list of TODO keywords identifying non-stuck projects.
599617 If the project subtree contains any headline with one of these todo
600618 keywords, the project is considered to be not stuck. If you specify
601619 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
620
602621 3. A list of tags identifying non-stuck projects.
603622 If the project subtree contains any headline with one of these tags,
604623 the project is considered to be not stuck. If you specify \"*\" as
606625 the explicit presence of a tag somewhere in the subtree, inherited
607626 tags do not count here. If inherited tags make a project not stuck,
608627 use \"-TAG\" in the tags part of the matcher under (1.) above.
628
609629 4. An arbitrary regular expression matching non-stuck projects.
610630
611631 If the project turns out to be not stuck, search continues also in the
10411061 :type 'boolean)
10421062
10431063 (defcustom org-agenda-show-outline-path t
1044 "Non-nil means show outline path in echo area after line motion."
1064 "Non-nil means show outline path in echo area after line motion.
1065
1066 If set to `title', show outline path with prepended document
1067 title. Fallback to file name is no title is present."
10451068 :group 'org-agenda-startup
1046 :type 'boolean)
1069 :type '(choice
1070 (const :tag "Don't show outline path in agenda view." nil)
1071 (const :tag "Show outline path with prepended file name." t)
1072 (const :tag "Show outline path with prepended document title." title))
1073 :package-version '(Org . "9.6"))
10471074
10481075 (defcustom org-agenda-start-with-entry-text-mode nil
10491076 "The initial value of entry-text-mode in a newly created agenda window."
11501177 "Non-nil means start the overview always on the specified weekday.
11511178 0 denotes Sunday, 1 denotes Monday, etc.
11521179 When nil, always start on the current day.
1153 Custom commands can set this variable in the options section."
1180 Custom commands can set this variable in the options section.
1181
1182 This variable only applies when agenda spans either 7 or 14 days."
11541183 :group 'org-agenda-daily/weekly
11551184 :type '(choice (const :tag "Today" nil)
11561185 (integer :tag "Weekday No.")))
12131242 :version "24.1"
12141243 :type 'boolean)
12151244
1245 (defcustom org-agenda-clock-report-header nil
1246 "Header inserted before the table in Org agenda clock report mode.
1247
1248 See Info node `(org) Agenda Commands' for more details."
1249 :group 'org-agenda
1250 :type '(choice
1251 (string :tag "Header")
1252 (const :tag "No header" nil))
1253 :safe #'stringp
1254 :package-version '(Org . "9.6"))
1255
12161256 (defun org-agenda-time-of-day-to-ampm (time)
12171257 "Convert TIME of a string like \"13:45\" to an AM/PM style time string."
12181258 (let* ((hour-number (string-to-number (substring time 0 -3)))
15131553 :type 'boolean)
15141554
15151555 (defcustom org-agenda-time-grid
1516 '((daily today require-timed)
1517 (800 1000 1200 1400 1600 1800 2000)
1518 "......"
1519 "----------------")
1520
1556 (let ((graphical (and (display-graphic-p)
1557 (char-displayable-p ?┄))))
1558 `((daily today require-timed)
1559 (800 1000 1200 1400 1600 1800 2000)
1560 ,(if graphical " ┄┄┄┄┄ " "......")
1561 ,(if graphical "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄" "----------------")))
15211562 "The settings for time grid for agenda display.
15221563 This is a list of four items. The first item is again a list. It contains
15231564 symbols specifying conditions when the grid should be displayed:
15371578 The fourth item is a string placed after the grid times. This
15381579 will align with agenda items."
15391580 :group 'org-agenda-time-grid
1581 :package-version '(Org . "9.6")
15401582 :type
15411583 '(list
15421584 (set :greedy t :tag "Grid Display Options"
15581600 :type 'boolean)
15591601
15601602 (defcustom org-agenda-current-time-string
1561 "now - - - - - - - - - - - - - - - - - - - - - - - - -"
1603 (if (and (display-graphic-p)
1604 (char-displayable-p ?←)
1605 (char-displayable-p ?─))
1606 "← now ───────────────────────────────────────────────"
1607 "now - - - - - - - - - - - - - - - - - - - - - - - - -")
15621608 "The string for the current time marker in the agenda."
15631609 :group 'org-agenda-time-grid
1564 :version "24.1"
1610 :package-version '(Org . "9.6")
15651611 :type 'string)
15661612
15671613 (defgroup org-agenda-sorting nil
16111657 alpha-down Sort headlines alphabetically, reversed.
16121658
16131659 The different possibilities will be tried in sequence, and testing stops
1614 if one comparison returns a \"not-equal\". For example, the default
1615 '(time-up category-keep priority-down)
1660 if one comparison returns a \"not-equal\". For example,
1661 (setq org-agenda-sorting-strategy
1662 \\='(time-up category-keep priority-down))
16161663 means: Pull out all entries having a specified time of day and sort them,
16171664 in order to make a time schedule for the current day the first thing in the
16181665 agenda listing for the day. Of the entries without a time indication, keep
20752122
20762123 (defcustom org-agenda-bulk-custom-functions nil
20772124 "Alist of characters and custom functions for bulk actions.
2078 For example, this value makes those two functions available:
2079
2080 \\='((?R set-category)
2081 (?C bulk-cut))
2125 For example, this makes those two functions available:
2126
2127 (setq org-agenda-bulk-custom-functions
2128 \\='((?R set-category)
2129 (?C bulk-cut)))
20822130
20832131 With selected entries in an agenda buffer, `B R' will call
20842132 the custom function `set-category' on the selected entries.
20892137 collecting function will be run once and should return a list of
20902138 arguments to pass to the bulk function. For example:
20912139
2092 \\='((?R set-category get-category))
2140 (setq org-agenda-bulk-custom-functions
2141 \\='((?R set-category get-category)))
20932142
20942143 Now, `B R' will call the custom `get-category' which would prompt
20952144 the user once for a category. That category is then passed as an
21082157 If STRING is non-nil, the text property will be fetched from position 0
21092158 in that string. If STRING is nil, it will be fetched from the beginning
21102159 of the current line."
2111 (declare (debug t))
2160 (declare (debug t) (indent 1))
21122161 (org-with-gensyms (marker)
2113 `(let ((,marker (get-text-property (if ,string 0 (point-at-bol))
2162 `(let ((,marker (get-text-property (if ,string 0 (line-beginning-position))
21142163 'org-hd-marker ,string)))
21152164 (with-current-buffer (marker-buffer ,marker)
21162165 (save-excursion
21552204 (org-remap org-agenda-mode-map 'move-end-of-line 'org-agenda-end-of-line)
21562205
21572206 (defvar org-agenda-menu) ; defined later in this file.
2158 (defvar org-agenda-restrict nil) ; defined later in this file.
2207 (defvar org-agenda-restrict nil
2208 "Non-nil means agenda restriction is active.
2209 This is an internal flag indicating either temporary or extended
2210 agenda restriction. Specifically, it is set to t if the agenda
2211 is restricted to an entire file, and is set to the corresponding
2212 buffer if the agenda is restricted to a part of a file, e.g. a
2213 region or a substree. In the latter case,
2214 `org-agenda-restrict-begin' and `org-agenda-restrict-end' are set
2215 to the beginning and the end of the part.
2216
2217 See also `org-agenda-set-restriction-lock'.")
21592218 (defvar org-agenda-follow-mode nil)
21602219 (defvar org-agenda-entry-text-mode nil)
21612220 (defvar org-agenda-clockreport-mode nil)
22342293 org-agenda-top-headline-filter
22352294 org-agenda-regexp-filter
22362295 org-agenda-effort-filter
2296 org-agenda-filters-preset
22372297 org-agenda-markers
22382298 org-agenda-last-search-view-search-was-boolean
22392299 org-agenda-last-indirect-buffer
23092369 org-agenda-show-log org-agenda-start-with-log-mode
23102370 org-agenda-clockreport-mode org-agenda-start-with-clockreport-mode))
23112371 (add-to-invisibility-spec '(org-filtered))
2312 (add-to-invisibility-spec '(org-link))
2372 (org-fold-core-initialize `(,org-link--description-folding-spec
2373 ,org-link--link-folding-spec))
23132374 (easy-menu-change
23142375 '("Agenda") "Agenda Files"
23152376 (append
26852746
26862747 ;;; Agenda dispatch
26872748
2688 (defvar org-agenda-restrict-begin (make-marker))
2689 (defvar org-agenda-restrict-end (make-marker))
2690 (defvar org-agenda-last-dispatch-buffer nil)
2691 (defvar org-agenda-overriding-restriction nil)
2749 (defvar org-agenda-restrict-begin (make-marker)
2750 "Internal variable used to mark the restriction beginning.
2751 It is only relevant when `org-agenda-restrict' is a buffer.")
2752 (defvar org-agenda-restrict-end (make-marker)
2753 "Internal variable used to mark the restriction end.
2754 It is only relevant when `org-agenda-restrict' is a buffer.")
2755 (defvar org-agenda-overriding-restriction nil
2756 "Non-nil means extended agenda restriction is active.
2757 This is an internal flag set by `org-agenda-set-restriction-lock'.")
26922758
26932759 (defcustom org-agenda-custom-commands-contexts nil
26942760 "Alist of custom agenda keys and contextual rules.
26972763 want this command to be accessible only from plain text files,
26982764 use this:
26992765
2700 \\='((\"p\" ((in-file . \"\\\\.txt\\\\'\"))))
2766 (setq org-agenda-custom-commands-contexts
2767 \\='((\"p\" ((in-file . \"\\\\.txt\\\\'\")))))
27012768
27022769 Here are the available contexts definitions:
27032770
27152782 You can also bind a key to another agenda custom command
27162783 depending on contextual rules.
27172784
2718 \\='((\"p\" \"q\" ((in-file . \"\\\\.txt\\\\'\"))))
2785 (setq org-agenda-custom-commands-contexts
2786 \\='((\"p\" \"q\" ((in-file . \"\\\\.txt\\\\'\")))))
27192787
27202788 Here it means: in .txt files, use \"p\" as the key for the
27212789 agenda command otherwise associated with \"q\". (The command
28842952 (setq org-agenda-restrict nil)
28852953 (move-marker org-agenda-restrict-begin nil)
28862954 (move-marker org-agenda-restrict-end nil))
2887 ;; Delete old local properties
2888 (put 'org-agenda-redo-command 'org-lprops nil)
2889 ;; Delete previously set last-arguments
2890 (put 'org-agenda-redo-command 'last-args nil)
2891 ;; Remember where this call originated
2892 (setq org-agenda-last-dispatch-buffer (current-buffer))
28932955 (unless org-keys
28942956 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
28952957 org-keys (car ans)
29152977 (move-marker org-agenda-restrict-begin (point))
29162978 (move-marker org-agenda-restrict-end
29172979 (progn (org-end-of-subtree t)))))
2918 ((and (eq restriction 'buffer)
2919 (or (< 1 (point-min))
2920 (< (point-max) (1+ (buffer-size)))))
2921 (setq org-agenda-restrict (current-buffer))
2922 (move-marker org-agenda-restrict-begin (point-min))
2923 (move-marker org-agenda-restrict-end (point-max)))))
2980 ((eq restriction 'buffer)
2981 (if (not (buffer-narrowed-p))
2982 (setq org-agenda-restrict t)
2983 (setq org-agenda-restrict (current-buffer))
2984 (move-marker org-agenda-restrict-begin (point-min))
2985 (move-marker org-agenda-restrict-end (point-max))))))
29242986
29252987 ;; For example the todo list should not need it (but does...)
29262988 (cond
29362998 (setq org-agenda-buffer-name
29372999 (or (and (stringp org-match) (format "*Org Agenda(%s:%s)*" org-keys org-match))
29383000 (format "*Org Agenda(%s)*" org-keys))))
2939 (put 'org-agenda-redo-command 'org-lprops lprops)
29403001 (cl-progv
29413002 (mapcar #'car lprops)
29423003 (mapcar (lambda (binding) (eval (cadr binding) t)) lprops)
29433004 (pcase type
29443005 (`agenda
2945 (org-agenda-list current-prefix-arg))
3006 (org-agenda-list arg))
29463007 (`agenda*
2947 (org-agenda-list current-prefix-arg nil nil t))
3008 (org-agenda-list arg nil nil t))
29483009 (`alltodo
2949 (org-todo-list current-prefix-arg))
3010 (org-todo-list arg))
29503011 (`search
2951 (org-search-view current-prefix-arg org-match nil))
3012 (org-search-view arg org-match nil))
29523013 (`stuck
2953 (org-agenda-list-stuck-projects current-prefix-arg))
3014 (org-agenda-list-stuck-projects arg))
29543015 (`tags
2955 (org-tags-view current-prefix-arg org-match))
3016 (org-tags-view arg org-match))
29563017 (`tags-todo
29573018 (org-tags-view '(4) org-match))
29583019 (`todo
29593020 (org-todo-list org-match))
29603021 (`tags-tree
29613022 (org-check-for-org-mode)
2962 (org-match-sparse-tree current-prefix-arg org-match))
3023 (org-match-sparse-tree arg org-match))
29633024 (`todo-tree
29643025 (org-check-for-org-mode)
29653026 (org-occur (concat "^" org-outline-regexp "[ \t]*"
29713032 (funcall type org-match))
29723033 ;; FIXME: Will signal an error since it's not `functionp'!
29733034 ((pred fboundp) (funcall type org-match))
2974 (_ (user-error "Invalid custom agenda command type %s" type)))))
3035 (_ (user-error "Invalid custom agenda command type %s" type))))
3036 (let ((inhibit-read-only t))
3037 (add-text-properties (point-min) (point-max)
3038 `(org-lprops ,lprops))))
29753039 (org-agenda-run-series (nth 1 entry) (cddr entry))))
29763040 ((equal org-keys "C")
29773041 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
30733137 (when (eq rmheader t)
30743138 (org-goto-line 1)
30753139 (re-search-forward ":" nil t)
3076 (delete-region (match-end 0) (point-at-eol))
3140 (delete-region (match-end 0) (line-end-position))
30773141 (forward-char 1)
30783142 (looking-at "-+")
3079 (delete-region (match-end 0) (point-at-eol))
3143 (delete-region (match-end 0) (line-end-position))
30803144 (move-marker header-end (match-end 0)))
30813145 (goto-char header-end)
30823146 (delete-region (point) (point-max))
32493313 (defvar org-agenda-overriding-arguments nil)
32503314 (defvar org-agenda-overriding-cmd-arguments nil)
32513315
3252 (defun org-let (list &rest body) ;FIXME: So many kittens are suffering here.
3253 (declare (indent 1) (obsolete cl-progv "2021"))
3254 (eval (cons 'let (cons list body))))
3255
3256 (defun org-let2 (list1 list2 &rest body) ;FIXME: Where did our karma go?
3257 (declare (indent 2) (obsolete cl-progv "2021"))
3258 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3259
32603316 (defun org-agenda-run-series (name series)
32613317 "Run agenda NAME as a SERIES of agenda commands."
32623318 (let* ((gprops (nth 1 series))
32913347 (`agenda
32923348 (call-interactively 'org-agenda-list))
32933349 (`agenda*
3294 (funcall 'org-agenda-list nil nil t))
3350 (funcall 'org-agenda-list nil nil nil t))
32953351 (`alltodo
32963352 (call-interactively 'org-todo-list))
32973353 (`search
34163472 (setq props (plist-put props 'tags (mapconcat #'identity tmp ":"))))
34173473 (when (setq tmp (plist-get props 'date))
34183474 (when (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
3419 (let ((calendar-date-display-form '(year "-" month "-" day)))
3420 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
3421
3475 (let ((calendar-date-display-form
3476 '((format "%s-%.2d-%.2d" year
3477 (string-to-number month)
3478 (string-to-number day)))))
34223479 (setq tmp (calendar-date-string tmp)))
34233480 (setq props (plist-put props 'date tmp)))
34243481 (when (setq tmp (plist-get props 'day))
34253482 (when (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
3426 (let ((calendar-date-display-form '(year "-" month "-" day)))
3483 (let ((calendar-date-display-form
3484 '((format "%s-%.2d-%.2d" year
3485 (string-to-number month)
3486 (string-to-number day)))))
34273487 (setq tmp (calendar-date-string tmp)))
34283488 (setq props (plist-put props 'day tmp))
34293489 (setq props (plist-put props 'agenda-day tmp)))
35023562 "Mark the line at POS as an agenda structure header."
35033563 (save-excursion
35043564 (goto-char pos)
3505 (put-text-property (point-at-bol) (point-at-eol)
3565 (put-text-property (line-beginning-position) (line-end-position)
35063566 'org-agenda-structural-header t)
35073567 (when org-agenda-title-append
3508 (put-text-property (point-at-bol) (point-at-eol)
3568 (put-text-property (line-beginning-position) (line-end-position)
35093569 'org-agenda-title-append org-agenda-title-append))))
35103570
35113571 (defvar org-mobile-creating-agendas) ; defined in org-mobile.el
37033763 ;; find and remove min common indentation
37043764 (goto-char (point-min))
37053765 (untabify (point-min) (point-max))
3706 (setq ind (current-indentation))
3766 (setq ind (org-current-text-indentation))
37073767 (while (not (eobp))
37083768 (unless (looking-at "[ \t]*$")
3709 (setq ind (min ind (current-indentation))))
3769 (setq ind (min ind (org-current-text-indentation))))
37103770 (beginning-of-line 2))
37113771 (goto-char (point-min))
37123772 (while (not (eobp))
37133773 (unless (looking-at "[ \t]*$")
37143774 (move-to-column ind)
3715 (delete-region (point-at-bol) (point)))
3775 (delete-region (line-beginning-position) (point)))
37163776 (beginning-of-line 2))
37173777
37183778 (run-hooks 'org-agenda-entry-text-cleanup-hook)
37633823 define a filter for one of the individual blocks. You need to set it in
37643824 the global options and expect it to be applied to the entire view.")
37653825
3826 (defvar org-agenda-filters-preset nil
3827 "Alist of filter types and associated preset of filters.
3828 This variable is local in `org-agenda' buffers. See `org-agenda-local-vars'.")
3829
37663830 (defconst org-agenda-filter-variables
37673831 '((category . org-agenda-category-filter)
37683832 (tag . org-agenda-tag-filter)
37733837 "Is any filter active?"
37743838 (cl-some (lambda (x)
37753839 (or (symbol-value (cdr x))
3776 (get :preset-filter x)))
3840 (assoc-default (car x) org-agenda-filters-preset)))
37773841 org-agenda-filter-variables))
37783842
37793843 (defvar org-agenda-category-filter-preset nil
38823946 (cat . ,org-agenda-category-filter))))))
38833947 (if (org-agenda-use-sticky-p)
38843948 (progn
3885 (put 'org-agenda-tag-filter :preset-filter nil)
3886 (put 'org-agenda-category-filter :preset-filter nil)
3887 (put 'org-agenda-regexp-filter :preset-filter nil)
3888 (put 'org-agenda-effort-filter :preset-filter nil)
38893949 ;; Popup existing buffer
38903950 (org-agenda-prepare-window (get-buffer org-agenda-buffer-name)
38913951 filter-alist)
38933953 (or org-agenda-multi (org-agenda-fit-window-to-buffer))
38943954 (throw 'exit "Sticky Agenda buffer, use `r' to refresh"))
38953955 (setq org-todo-keywords-for-agenda nil)
3896 (put 'org-agenda-tag-filter :preset-filter
3897 org-agenda-tag-filter-preset)
3898 (put 'org-agenda-category-filter :preset-filter
3899 org-agenda-category-filter-preset)
3900 (put 'org-agenda-regexp-filter :preset-filter
3901 org-agenda-regexp-filter-preset)
3902 (put 'org-agenda-effort-filter :preset-filter
3903 org-agenda-effort-filter-preset)
39043956 (if org-agenda-multi
39053957 (progn
39063958 (setq buffer-read-only nil)
39103962 (insert "\n"
39113963 (if (stringp org-agenda-block-separator)
39123964 org-agenda-block-separator
3913 (make-string (window-width) org-agenda-block-separator))
3965 (make-string (window-max-chars-per-line) org-agenda-block-separator))
39143966 "\n"))
39153967 (narrow-to-region (point) (point-max)))
39163968 (setq org-done-keywords-for-agenda nil)
39253977 (setq org-agenda-buffer (current-buffer))
39263978 (setq org-agenda-contributing-files nil)
39273979 (setq org-agenda-columns-active nil)
3928 (org-agenda-prepare-buffers (org-agenda-files nil 'ifmode))
3980 (setq org-agenda-filters-preset
3981 `((tag . ,org-agenda-tag-filter-preset)
3982 (category . ,org-agenda-category-filter-preset)
3983 (regexp . ,org-agenda-regexp-filter-preset)
3984 (effort . ,org-agenda-effort-filter-preset)))
3985 (org-agenda-prepare-buffers (org-agenda-files nil 'ifmode))
39293986 (setq org-todo-keywords-for-agenda
39303987 (org-uniquify org-todo-keywords-for-agenda))
39313988 (setq org-done-keywords-for-agenda
39844041 (goto-char (point-min))
39854042 (while (equal (forward-line) 0)
39864043 (when (setq mrk (get-text-property (point) 'org-hd-marker))
3987 (put-text-property (point-at-bol) (point-at-eol)
4044 (put-text-property (line-beginning-position) (line-end-position)
39884045 'tags
39894046 (org-with-point-at mrk
39904047 (org-get-tags))))))))
39954052 org-agenda-top-headline-filter))
39964053 (when org-agenda-tag-filter
39974054 (org-agenda-filter-apply org-agenda-tag-filter 'tag t))
3998 (when (get 'org-agenda-tag-filter :preset-filter)
4055 (when (assoc-default 'tag org-agenda-filters-preset)
39994056 (org-agenda-filter-apply
4000 (get 'org-agenda-tag-filter :preset-filter) 'tag t))
4057 (assoc-default 'tag org-agenda-filters-preset) 'tag t))
40014058 (when org-agenda-category-filter
40024059 (org-agenda-filter-apply org-agenda-category-filter 'category))
4003 (when (get 'org-agenda-category-filter :preset-filter)
4060 (when (assoc-default 'category org-agenda-filters-preset)
40044061 (org-agenda-filter-apply
4005 (get 'org-agenda-category-filter :preset-filter) 'category))
4062 (assoc-default 'category org-agenda-filters-preset) 'category))
40064063 (when org-agenda-regexp-filter
40074064 (org-agenda-filter-apply org-agenda-regexp-filter 'regexp))
4008 (when (get 'org-agenda-regexp-filter :preset-filter)
4065 (when (assoc-default 'regexp org-agenda-filters-preset)
40094066 (org-agenda-filter-apply
4010 (get 'org-agenda-regexp-filter :preset-filter) 'regexp))
4067 (assoc-default 'regexp org-agenda-filters-preset) 'regexp))
40114068 (when org-agenda-effort-filter
40124069 (org-agenda-filter-apply org-agenda-effort-filter 'effort))
4013 (when (get 'org-agenda-effort-filter :preset-filter)
4070 (when (assoc-default 'effort org-agenda-filters-preset)
40144071 (org-agenda-filter-apply
4015 (get 'org-agenda-effort-filter :preset-filter) 'effort))
4072 (assoc-default 'effort org-agenda-filters-preset) 'effort))
40164073 (add-hook 'kill-buffer-hook #'org-agenda-reset-markers 'append 'local))
40174074 (run-hooks 'org-agenda-finalize-hook))))
40184075
40324089 (goto-char s)
40334090 (when (equal (org-get-at-bol 'org-hd-marker)
40344091 org-clock-hd-marker)
4035 (setq ov (make-overlay (point-at-bol) (1+ (point-at-eol))))
4092 (setq ov (make-overlay (line-beginning-position)
4093 (1+ (line-end-position))))
40364094 (overlay-put ov 'type 'org-agenda-clocking)
40374095 (overlay-put ov 'face 'org-agenda-clocking)
40384096 (overlay-put ov 'help-echo
40634121 b (match-beginning 1)
40644122 e (if (eq org-agenda-fontify-priorities 'cookies)
40654123 (1+ (match-end 2))
4066 (point-at-eol))
4124 (line-end-position))
40674125 ov (make-overlay b e))
40684126 (overlay-put
40694127 ov 'face
41214179
41224180 If the header at `org-hd-marker' is blocked according to
41234181 `org-entry-blocked-p', then if `org-agenda-dim-blocked-tasks' is
4124 'invisible and the header is not blocked by checkboxes, set the
4182 `invisible' and the header is not blocked by checkboxes, set the
41254183 text property `org-todo-blocked' to `invisible', otherwise set it
41264184 to t."
41274185 (when (get-text-property 0 'todo-state entry)
41534211 If this function returns nil, the current match should not be skipped.
41544212 Otherwise, the function must return a position from where the search
41554213 should be continued.
4156 This may also be a Lisp form, it will be evaluated.
4157 Never set this variable using `setq' or so, because then it will apply
4158 to all future agenda commands. If you do want a global skipping condition,
4159 use the option `org-agenda-skip-function-global' instead.
4160 The correct usage for `org-agenda-skip-function' is to bind it with
4161 `let' to scope it dynamically into the agenda-constructing command.
4214
4215 This may also be a Lisp form that will be evaluated. Useful
4216 forms include `org-agenda-skip-entry-if' and
4217 `org-agenda-skip-subtree-if'. See the Info node `(org) Special
4218 Agenda Views' for more details and examples.
4219
4220 Never set this variable using `setq' or similar, because then it
4221 will apply to all future agenda commands. If you want a global
4222 skipping condition, use the option `org-agenda-skip-function-global'
4223 instead.
4224
4225 The correct way to use `org-agenda-skip-function' is to bind it with `let'
4226 to scope it dynamically into the agenda-constructing command.
41624227 A good way to set it is through options in `org-agenda-custom-commands'.")
41634228
4164 (defun org-agenda-skip ()
4229 (defun org-agenda-skip (&optional element)
41654230 "Throw to `:skip' in places that should be skipped.
41664231 Also moves point to the end of the skipped region, so that search can
4167 continue from there."
4168 (let ((p (point-at-bol)) to)
4169 (when (or
4170 (save-excursion (goto-char p) (looking-at comment-start-skip))
4171 (and org-agenda-skip-archived-trees (not org-agenda-archives-mode)
4172 (or (and (get-text-property p :org-archived)
4173 (org-end-of-subtree t))
4174 (and (member org-archive-tag org-file-tags)
4175 (goto-char (point-max)))))
4176 (and org-agenda-skip-comment-trees
4177 (get-text-property p :org-comment)
4178 (org-end-of-subtree t))
4179 (and (setq to (or (org-agenda-skip-eval org-agenda-skip-function-global)
4180 (org-agenda-skip-eval org-agenda-skip-function)))
4181 (goto-char to))
4182 (org-in-src-block-p t))
4183 (throw :skip t))))
4232 continue from there.
4233
4234 Optional argument ELEMENT contains element at point."
4235 (when (or
4236 (if element
4237 (eq (org-element-type element) 'comment)
4238 (save-excursion
4239 (goto-char (line-beginning-position))
4240 (looking-at comment-start-skip)))
4241 (and org-agenda-skip-archived-trees (not org-agenda-archives-mode)
4242 (or (and (save-match-data (org-in-archived-heading-p nil element))
4243 (org-end-of-subtree t element))
4244 (and (member org-archive-tag org-file-tags)
4245 (goto-char (point-max)))))
4246 (and org-agenda-skip-comment-trees
4247 (org-in-commented-heading-p nil element)
4248 (org-end-of-subtree t element))
4249 (let ((to (or (org-agenda-skip-eval org-agenda-skip-function-global)
4250 (org-agenda-skip-eval org-agenda-skip-function))))
4251 (and to (goto-char to)))
4252 (org-in-src-block-p t element))
4253 (throw :skip t)))
41844254
41854255 (defun org-agenda-skip-eval (form)
41864256 "If FORM is a function or a list, call (or eval) it and return the result.
42084278 of these markers and resets them when they are no longer in use."
42094279 (let ((m (copy-marker (or pos (point)) t)))
42104280 (setq org-agenda-last-marker-time (float-time))
4211 (if org-agenda-buffer
4212 (with-current-buffer org-agenda-buffer
4281 (if (and org-agenda-buffer (buffer-live-p org-agenda-buffer))
4282 (with-current-buffer org-agenda-buffer
42134283 (push m org-agenda-markers))
42144284 (push m org-agenda-markers))
42154285 m))
42414311 m org-agenda-entry-text-maxlines
42424312 org-agenda-entry-text-leaders))))
42434313 (when (string-match "\\S-" txt)
4244 (setq o (make-overlay (point-at-bol) (point-at-eol)))
4314 (setq o (make-overlay (line-beginning-position) (line-end-position)))
42454315 (overlay-put o 'evaporate t)
42464316 (overlay-put o 'org-overlay-type 'agenda-entry-content)
42474317 (overlay-put o 'after-string txt))))
42864356 Custom commands can set this variable in the options section.
42874357 This is usually a string like \"2007-11-01\", \"+2d\" or any other
42884358 input allowed when reading a date through the Org calendar.
4289 See the docstring of `org-read-date' for details.")
4359 See the docstring of `org-read-date' for details.
4360
4361 This variable has no effect when `org-agenda-start-on-weekday' is set
4362 and agenda spans 7 or 14 days.")
42904363 (defvar org-starting-day nil) ; local variable in the agenda buffer
42914364 (defvar org-arg-loc nil) ; local variable
42924365
43504423 (- sd (+ (if (< d 0) 7 0) d)))))
43514424 (day-numbers (list start))
43524425 (day-cnt 0)
4426 ;; FIXME: This may cause confusion when users are trying to
4427 ;; debug agenda. The debugger will not trigger without
4428 ;; redisplay.
43534429 (inhibit-redisplay (not debug-on-error))
43544430 (org-agenda-show-log-scoped org-agenda-show-log)
43554431 s rtn rtnall file date d start-pos end-pos todayp ;; e
44674543 (setq p (plist-put p :tend clocktable-end))
44684544 (setq p (plist-put p :scope 'agenda))
44694545 (setq tbl (apply #'org-clock-get-clocktable p))
4546 (when org-agenda-clock-report-header
4547 (insert (propertize org-agenda-clock-report-header 'face 'org-agenda-structure))
4548 (unless (string-suffix-p "\n" org-agenda-clock-report-header)
4549 (insert "\n")))
44704550 (insert tbl)))
44714551 (goto-char (point-min))
44724552 (or org-agenda-multi (org-agenda-fit-window-to-buffer))
46004680 (org-agenda-text-search-extra-files org-agenda-text-search-extra-files)
46014681 regexp rtn rtnall files file pos inherited-tags
46024682 marker category level tags c neg re boolean
4603 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
4683 ee txt beg end last-search-end words regexps+ regexps- hdl-only buffer beg1 str)
46044684 (unless (and (not edit-at)
46054685 (stringp string)
46064686 (string-match "\\S-" string))
47394819 (throw 'nextfile t))
47404820 (goto-char (max (point-min) (1- (point))))
47414821 (while (re-search-forward regexp nil t)
4822 (setq last-search-end (point))
47424823 (org-back-to-heading t)
47434824 (while (and (not (zerop org-agenda-search-view-max-outline-level))
47444825 (> (org-reduced-level (org-outline-level))
47464827 (forward-line -1)
47474828 (org-back-to-heading t)))
47484829 (skip-chars-forward "* ")
4749 (setq beg (point-at-bol)
4830 (setq beg (line-beginning-position)
47504831 beg1 (point)
47514832 end (progn
47524833 (outline-next-heading)
47614842 (goto-char beg)
47624843 (org-agenda-skip)
47634844 (setq str (buffer-substring-no-properties
4764 (point-at-bol)
4765 (if hdl-only (point-at-eol) end)))
4845 (line-beginning-position)
4846 (if hdl-only (line-end-position) end)))
47664847 (mapc (lambda (wr) (when (string-match wr str)
47674848 (goto-char (1- end))
47684849 (throw :skip t)))
47904871 txt (org-agenda-format-item
47914872 ""
47924873 (buffer-substring-no-properties
4793 beg1 (point-at-eol))
4874 beg1 (line-end-position))
47944875 level category tags t))
47954876 (org-add-props txt props
47964877 'org-marker marker 'org-hd-marker marker
48004881 'priority 1000
48014882 'type "search")
48024883 (push txt ee)
4803 (goto-char (1- end))))))))))
4884 (goto-char (max (1- end) last-search-end))))))))))
48044885 (setq rtn (nreverse ee))
48054886 (setq rtnall (append rtnall rtn)))
48064887 (org-agenda--insert-overriding-header
48564937
48574938 ;;;###autoload
48584939 (defun org-todo-list (&optional arg)
4859 "Show all (not done) TODO entries from all agenda file in a single list.
4940 "Show all (not done) TODO entries from all agenda files in a single list.
48604941 The prefix arg can be used to select a specific TODO keyword and limit
48614942 the list to these. When using `\\[universal-argument]', you will be prompted
48624943 for a keyword. A numeric prefix directly selects the Nth keyword in
49255006 (let ((n 0))
49265007 (dolist (k kwds)
49275008 (let ((s (format "(%d)%s" (cl-incf n) k)))
4928 (when (> (+ (current-column) (string-width s) 1) (window-width))
5009 (when (> (+ (current-column) (string-width s) 1) (window-max-chars-per-line))
49295010 (insert "\n "))
49305011 (insert " " s))))
49315012 (insert "\n"))
50625143
50635144 (defun org-agenda-skip-entry-if (&rest conditions)
50645145 "Skip entry if any of CONDITIONS is true.
5065 See `org-agenda-skip-if' for details."
5146 See `org-agenda-skip-if' for details about CONDITIONS.
5147
5148 This function can be put into `org-agenda-skip-function' for the
5149 duration of a command."
50665150 (org-agenda-skip-if nil conditions))
50675151
50685152 (defun org-agenda-skip-subtree-if (&rest conditions)
50695153 "Skip subtree if any of CONDITIONS is true.
5070 See `org-agenda-skip-if' for details."
5154 See `org-agenda-skip-if' for details about CONDITIONS.
5155
5156 This function can be put into `org-agenda-skip-function' for the
5157 duration of a command."
50715158 (org-agenda-skip-if t conditions))
50725159
50735160 (defun org-agenda-skip-if (subtree conditions)
50895176 todo Check if TODO keyword matches
50905177 nottodo Check if TODO keyword does not match
50915178
5092 The regexp is taken from the conditions list, it must come right after
5093 the `regexp' or `notregexp' element.
5179 The regexp is taken from the conditions list, and must come right
5180 after the `regexp' or `notregexp' element.
50945181
50955182 `todo' and `nottodo' accept as an argument a list of todo
50965183 keywords, which may include \"*\" to match any todo keyword.
53025389 "Hook run when the fancy diary buffer is cleaned up.")
53035390
53045391 (defun org-agenda-cleanup-fancy-diary ()
5305 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5392 "Remove unwanted stuff in buffer created by `diary-fancy-display'.
53065393 This gets rid of the date, the underline under the date, and the
53075394 dummy entry installed by Org mode to ensure non-empty diary for
53085395 each date. It also removes lines that contain only whitespace."
53325419 (abbreviate-file-name buffer-file-name))
53335420 "")
53345421 'org-agenda-diary-link t
5335 'org-marker (org-agenda-new-marker (point-at-bol))))
5422 'org-marker (org-agenda-new-marker (line-beginning-position))))
53365423
53375424 (defun org-diary-default-entry ()
53385425 "Add a dummy entry to the diary.
55495636 (t org-not-done-regexp))))
55505637 marker priority category level tags todo-state
55515638 ts-date ts-date-type ts-date-pair
5552 ee txt beg end inherited-tags todo-state-end-pos)
5639 ee txt beg end inherited-tags todo-state-end-pos
5640 effort effort-minutes)
55535641 (goto-char (point-min))
55545642 (while (re-search-forward regexp nil t)
55555643 (catch :skip
55685656 (goto-char (match-beginning 2))
55695657 (setq marker (org-agenda-new-marker (match-beginning 0))
55705658 category (org-get-category)
5659 effort (save-match-data (or (get-text-property (point) 'effort)
5660 (org-entry-get (point) org-effort-property)))
5661 effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))
55715662 ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
55725663 ts-date (car ts-date-pair)
55735664 ts-date-type (cdr ts-date-pair)
55815672 (memq 'todo org-agenda-use-tag-inheritance))))
55825673 tags (org-get-tags nil (not inherited-tags))
55835674 level (make-string (org-reduced-level (org-outline-level)) ? )
5584 txt (org-agenda-format-item "" txt level category tags t)
5675 txt (org-agenda-format-item ""
5676 (org-add-props txt nil
5677 'effort effort
5678 'effort-minutes effort-minutes)
5679 level category tags t)
55855680 priority (1+ (org-get-priority txt)))
55865681 (org-add-props txt props
55875682 'org-marker marker 'org-hd-marker marker
55885683 'priority priority
5684 'effort effort 'effort-minutes effort-minutes
55895685 'level level
55905686 'ts-date ts-date
55915687 'type (concat "todo" ts-date-type) 'todo-state todo-state)
57095805 (regexp-quote
57105806 (substring
57115807 (format-time-string
5712 (car org-time-stamp-formats)
5713 (encode-time ; DATE bound by calendar
5808 (org-time-stamp-format)
5809 (org-encode-time ; DATE bound by calendar
57145810 0 0 0 (nth 1 date) (car date) (nth 2 date)))
57155811 1 11))
57165812 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[hdwmy]>\\)"
57285824 (org-at-planning-p)
57295825 (org-before-first-heading-p)
57305826 (and org-agenda-include-inactive-timestamps
5731 (org-at-clock-log-p)))
5827 (org-at-clock-log-p))
5828 (not (org-at-timestamp-p 'agenda)))
57325829 (throw :skip nil))
5733 (org-agenda-skip))
5830 (org-agenda-skip (org-element-at-point)))
57345831 (let* ((pos (match-beginning 0))
57355832 (repeat (match-string 1))
57365833 (sexp-entry (match-string 3))
57885885 (assq (point) deadline-position-alist))
57895886 (throw :skip nil))
57905887 (let* ((category (org-get-category pos))
5888 (effort (org-entry-get pos org-effort-property))
5889 (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort))))
57915890 (inherited-tags
57925891 (or (eq org-agenda-show-inherited-tags 'always)
57935892 (and (consp org-agenda-show-inherited-tags)
58065905 (item
58075906 (org-agenda-format-item
58085907 (and inactive? org-agenda-inactive-leader)
5809 head level category tags time-stamp org-ts-regexp habit?)))
5908 (org-add-props head nil
5909 'effort effort
5910 'effort-minutes effort-minutes)
5911 level category tags time-stamp org-ts-regexp habit?)))
58105912 (org-add-props item props
58115913 'priority (if habit?
58125914 (org-habit-get-priority (org-habit-parse-todo))
58155917 'org-hd-marker (org-agenda-new-marker)
58165918 'date date
58175919 'level level
5920 'effort effort 'effort-minutes effort-minutes
58185921 'ts-date (if repeat (org-agenda--timestamp-to-absolute repeat)
58195922 current)
58205923 'todo-state todo-state
58385941 ;; FIXME: Is this `entry' binding intended to be dynamic,
58395942 ;; so as to "hide" any current binding for it?
58405943 marker category extra level ee txt tags entry
5841 result beg b sexp sexp-entry todo-state warntime inherited-tags)
5944 result beg b sexp sexp-entry todo-state warntime inherited-tags
5945 effort effort-minutes)
58425946 (goto-char (point-min))
58435947 (while (re-search-forward regexp nil t)
58445948 (catch :skip
5845 (org-agenda-skip)
5949 ;; We do not run `org-agenda-skip' right away because every single sexp
5950 ;; in the buffer is matched here, unlike day-specific search
5951 ;; in ordinary timestamps. Most of the sexps will not match
5952 ;; the agenda day and it is quicker to run `org-agenda-skip' only for
5953 ;; matching sexps later on.
58465954 (setq beg (match-beginning 0))
58475955 (goto-char (1- (match-end 0)))
58485956 (setq b (point))
58495957 (forward-sexp 1)
58505958 (setq sexp (buffer-substring b (point)))
58515959 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
5852 (org-trim (match-string 1))
5960 (buffer-substring
5961 (match-beginning 1)
5962 (save-excursion
5963 (goto-char (match-end 1))
5964 (skip-chars-backward "[:blank:]")
5965 (point)))
58535966 ""))
58545967 (setq result (org-diary-sexp-entry sexp sexp-entry date))
58555968 (when result
5969 ;; Only check if entry should be skipped on matching sexps.
5970 (org-agenda-skip (org-element-at-point))
58565971 (setq marker (org-agenda-new-marker beg)
58575972 level (make-string (org-reduced-level (org-outline-level)) ? )
58585973 category (org-get-category beg)
5974 effort (save-match-data (or (get-text-property (point) 'effort)
5975 (org-entry-get (point) org-effort-property)))
58595976 inherited-tags
58605977 (or (eq org-agenda-show-inherited-tags 'always)
58615978 (and (listp org-agenda-show-inherited-tags)
58675984 todo-state (org-get-todo-state)
58685985 warntime (get-text-property (point) 'org-appt-warntime)
58695986 extra nil)
5987 (setq effort-minutes (when effort (save-match-data (org-duration-to-minutes effort))))
58705988
58715989 (dolist (r (if (stringp result)
58725990 (list result)
58785996 (if (string-match "\\S-" r)
58795997 (setq txt r)
58805998 (setq txt "SEXP entry returned empty string"))
5881 (setq txt (org-agenda-format-item extra txt level category tags 'time))
5999 (setq txt (org-agenda-format-item extra
6000 (org-add-props txt nil
6001 'effort effort
6002 'effort-minutes effort-minutes)
6003 level category tags 'time))
58826004 (org-add-props txt props 'org-marker marker
58836005 'date date 'todo-state todo-state
6006 'effort effort 'effort-minutes effort-minutes
58846007 'level level 'type "sexp" 'warntime warntime)
58856008 (push txt ee)))))
58866009 (nreverse ee)))
59656088 (regexp-quote
59666089 (substring
59676090 (format-time-string
5968 (car org-time-stamp-formats)
5969 (encode-time ; DATE bound by calendar
6091 (org-time-stamp-format)
6092 (org-encode-time ; DATE bound by calendar
59706093 0 0 0 (nth 1 date) (car date) (nth 2 date)))
59716094 1 11))))
59726095 (org-agenda-search-headline-for-time nil)
59736096 marker hdmarker priority category level tags closedp type
5974 statep clockp state ee txt extra timestr rest clocked inherited-tags)
6097 statep clockp state ee txt extra timestr rest clocked inherited-tags
6098 effort effort-minutes)
59756099 (goto-char (point-min))
59766100 (while (re-search-forward regexp nil t)
59776101 (catch :skip
59826106 clockp (not (or closedp statep))
59836107 state (and statep (match-string 2))
59846108 category (org-get-category (match-beginning 0))
5985 timestr (buffer-substring (match-beginning 0) (point-at-eol)))
6109 timestr (buffer-substring (match-beginning 0) (line-end-position))
6110 effort (save-match-data (or (get-text-property (point) 'effort)
6111 (org-entry-get (point) org-effort-property))))
6112 (setq effort-minutes (when effort (save-match-data (org-duration-to-minutes effort))))
59866113 (when (string-match "\\]" timestr)
59876114 ;; substring should only run to end of time stamp
59886115 (setq rest (substring timestr (match-end 0))
60296156 (closedp "Closed: ")
60306157 (statep (concat "State: (" state ")"))
60316158 (t (concat "Clocked: (" clocked ")")))
6032 txt level category tags timestr)))
6159 (org-add-props txt nil
6160 'effort effort
6161 'effort-minutes effort-minutes)
6162 level category tags timestr)))
60336163 (setq type (cond (closedp "closed")
60346164 (statep "state")
60356165 (t "clock")))
60376167 (org-add-props txt props
60386168 'org-marker marker 'org-hd-marker hdmarker 'face 'org-agenda-done
60396169 'priority priority 'level level
6170 'effort effort 'effort-minutes effort-minutes
60406171 'type type 'date date
60416172 'undone-face 'org-warning 'done-face 'org-agenda-done)
60426173 (push txt ee))
6043 (goto-char (point-at-eol))))
6174 (goto-char (line-end-position))))
60446175 (nreverse ee)))
60456176
60466177 (defun org-agenda-show-clocking-issues ()
60776208 (setq issue "No valid clock line") (throw 'next t))
60786209 (org-with-point-at m
60796210 (save-excursion
6080 (goto-char (point-at-bol))
6211 (goto-char (line-beginning-position))
60816212 (unless (looking-at re)
60826213 (error "No valid Clock line")
60836214 (throw 'next t))
61236254 (setq tlend (or te tlend) tlstart (or ts tlstart))
61246255 (when issue
61256256 ;; OK, there was some issue, add an overlay to show the issue
6126 (setq ov (make-overlay (point-at-bol) (point-at-eol)))
6257 (setq ov (make-overlay (line-beginning-position) (line-end-position)))
61276258 (overlay-put ov 'before-string
61286259 (concat
61296260 (org-add-props
61466277 (throw 'exit t))
61476278 ;; We have a shorter gap.
61486279 ;; Now we have to get the minute of the day when these times are
6149 (let* ((t1dec (org-decode-time t1))
6150 (t2dec (org-decode-time t2))
6280 (let* ((t1dec (decode-time t1))
6281 (t2dec (decode-time t2))
61516282 ;; compute the minute on the day
61526283 (min1 (+ (nth 1 t1dec) (* 60 (nth 2 t1dec))))
61536284 (min2 (+ (nth 1 t2dec) (* 60 (nth 2 t2dec)))))
61856316 (current (calendar-absolute-from-gregorian date))
61866317 deadline-items)
61876318 (goto-char (point-min))
6188 (while (re-search-forward regexp nil t)
6189 (catch :skip
6190 (unless (save-match-data (org-at-planning-p)) (throw :skip nil))
6191 (org-agenda-skip)
6192 (let* ((s (match-string 1))
6193 (pos (1- (match-beginning 1)))
6194 (todo-state (save-match-data (org-get-todo-state)))
6195 (done? (member todo-state org-done-keywords))
6196 (sexp? (string-prefix-p "%%" s))
6197 ;; DEADLINE is the deadline date for the entry. It is
6198 ;; either the base date or the last repeat, according
6199 ;; to `org-agenda-prefer-last-repeat'.
6200 (deadline
6201 (cond
6202 (sexp? (org-agenda--timestamp-to-absolute s current))
6203 ((or (eq org-agenda-prefer-last-repeat t)
6204 (member todo-state org-agenda-prefer-last-repeat))
6205 (org-agenda--timestamp-to-absolute
6206 s today 'past (current-buffer) pos))
6207 (t (org-agenda--timestamp-to-absolute s))))
6208 ;; REPEAT is the future repeat closest from CURRENT,
6209 ;; according to `org-agenda-show-future-repeats'. If
6210 ;; the latter is nil, or if the time stamp has no
6211 ;; repeat part, default to DEADLINE.
6212 (repeat
6213 (cond
6214 (sexp? deadline)
6215 ((<= current today) deadline)
6216 ((not org-agenda-show-future-repeats) deadline)
6217 (t
6218 (let ((base (if (eq org-agenda-show-future-repeats 'next)
6219 (1+ today)
6220 current)))
6319 (if (org-element--cache-active-p)
6320 (org-element-cache-map
6321 (lambda (el)
6322 (when (and (org-element-property :deadline el)
6323 (or (not with-hour)
6324 (org-element-property
6325 :hour-start
6326 (org-element-property :deadline el))
6327 (org-element-property
6328 :hour-end
6329 (org-element-property :deadline el))))
6330 (goto-char (org-element-property :contents-begin el))
6331 (catch :skip
6332 (org-agenda-skip el)
6333 (let* ((s (substring (org-element-property
6334 :raw-value
6335 (org-element-property :deadline el))
6336 1 -1))
6337 (pos (save-excursion
6338 (goto-char (org-element-property :contents-begin el))
6339 ;; We intentionally leave NOERROR
6340 ;; argument in `re-search-forward' nil. If
6341 ;; the search fails here, something went
6342 ;; wrong and we are looking at
6343 ;; non-matching headline.
6344 (re-search-forward regexp (line-end-position))
6345 (1- (match-beginning 1))))
6346 (todo-state (org-element-property :todo-keyword el))
6347 (done? (eq 'done (org-element-property :todo-type el)))
6348 (sexp? (eq 'diary
6349 (org-element-property
6350 :type (org-element-property :deadline el))))
6351 ;; DEADLINE is the deadline date for the entry. It is
6352 ;; either the base date or the last repeat, according
6353 ;; to `org-agenda-prefer-last-repeat'.
6354 (deadline
6355 (cond
6356 (sexp? (org-agenda--timestamp-to-absolute s current))
6357 ((or (eq org-agenda-prefer-last-repeat t)
6358 (member todo-state org-agenda-prefer-last-repeat))
6359 (org-agenda--timestamp-to-absolute
6360 s today 'past (current-buffer) pos))
6361 (t (org-agenda--timestamp-to-absolute s))))
6362 ;; REPEAT is the future repeat closest from CURRENT,
6363 ;; according to `org-agenda-show-future-repeats'. If
6364 ;; the latter is nil, or if the time stamp has no
6365 ;; repeat part, default to DEADLINE.
6366 (repeat
6367 (cond
6368 (sexp? deadline)
6369 ((<= current today) deadline)
6370 ((not org-agenda-show-future-repeats) deadline)
6371 (t
6372 (let ((base (if (eq org-agenda-show-future-repeats 'next)
6373 (1+ today)
6374 current)))
6375 (org-agenda--timestamp-to-absolute
6376 s base 'future (current-buffer) pos)))))
6377 (diff (- deadline current))
6378 (suppress-prewarning
6379 (let ((scheduled
6380 (and org-agenda-skip-deadline-prewarning-if-scheduled
6381 (org-element-property
6382 :raw-value
6383 (org-element-property :scheduled el)))))
6384 (cond
6385 ((not scheduled) nil)
6386 ;; The current item has a scheduled date, so
6387 ;; evaluate its prewarning lead time.
6388 ((integerp org-agenda-skip-deadline-prewarning-if-scheduled)
6389 ;; Use global prewarning-restart lead time.
6390 org-agenda-skip-deadline-prewarning-if-scheduled)
6391 ((eq org-agenda-skip-deadline-prewarning-if-scheduled
6392 'pre-scheduled)
6393 ;; Set pre-warning to no earlier than SCHEDULED.
6394 (min (- deadline
6395 (org-agenda--timestamp-to-absolute scheduled))
6396 org-deadline-warning-days))
6397 ;; Set pre-warning to deadline.
6398 (t 0))))
6399 (wdays (or suppress-prewarning (org-get-wdays s))))
6400 (cond
6401 ;; Only display deadlines at their base date, at future
6402 ;; repeat occurrences or in today agenda.
6403 ((= current deadline) nil)
6404 ((= current repeat) nil)
6405 ((not today?) (throw :skip nil))
6406 ;; Upcoming deadline: display within warning period WDAYS.
6407 ((> deadline current) (when (> diff wdays) (throw :skip nil)))
6408 ;; Overdue deadline: warn about it for
6409 ;; `org-deadline-past-days' duration.
6410 (t (when (< org-deadline-past-days (- diff)) (throw :skip nil))))
6411 ;; Possibly skip done tasks.
6412 (when (and done?
6413 (or org-agenda-skip-deadline-if-done
6414 (/= deadline current)))
6415 (throw :skip nil))
6416 (save-excursion
6417 (goto-char (org-element-property :begin el))
6418 (let* ((category (org-get-category))
6419 (effort (save-match-data (or (get-text-property (point) 'effort)
6420 (org-element-property (intern (concat ":" (upcase org-effort-property))) el))))
6421 (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort))))
6422 (level (make-string (org-element-property :level el)
6423 ?\s))
6424 (head (save-excursion
6425 (goto-char (org-element-property :begin el))
6426 (re-search-forward org-outline-regexp-bol)
6427 (buffer-substring-no-properties (point) (line-end-position))))
6428 (inherited-tags
6429 (or (eq org-agenda-show-inherited-tags 'always)
6430 (and (listp org-agenda-show-inherited-tags)
6431 (memq 'agenda org-agenda-show-inherited-tags))
6432 (and (eq org-agenda-show-inherited-tags t)
6433 (or (eq org-agenda-use-tag-inheritance t)
6434 (memq 'agenda
6435 org-agenda-use-tag-inheritance)))))
6436 (tags (org-get-tags el (not inherited-tags)))
6437 (time
6438 (cond
6439 ;; No time of day designation if it is only
6440 ;; a reminder.
6441 ((and (/= current deadline) (/= current repeat)) nil)
6442 ((string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
6443 (concat (substring s (match-beginning 1)) " "))
6444 (t 'time)))
6445 (item
6446 (org-agenda-format-item
6447 ;; Insert appropriate suffixes before deadlines.
6448 ;; Those only apply to today agenda.
6449 (pcase-let ((`(,now ,future ,past)
6450 org-agenda-deadline-leaders))
6451 (cond
6452 ((and today? (< deadline today)) (format past (- diff)))
6453 ((and today? (> deadline today)) (format future diff))
6454 (t now)))
6455 (org-add-props head nil
6456 'effort effort
6457 'effort-minutes effort-minutes)
6458 level category tags time))
6459 (face (org-agenda-deadline-face
6460 (- 1 (/ (float diff) (max wdays 1)))))
6461 (upcoming? (and today? (> deadline today)))
6462 (warntime (get-text-property (point) 'org-appt-warntime)))
6463 (org-add-props item props
6464 'org-marker (org-agenda-new-marker pos)
6465 'org-hd-marker (org-agenda-new-marker (line-beginning-position))
6466 'warntime warntime
6467 'level level
6468 'effort effort 'effort-minutes effort-minutes
6469 'ts-date deadline
6470 'priority
6471 ;; Adjust priority to today reminders about deadlines.
6472 ;; Overdue deadlines get the highest priority
6473 ;; increase, then imminent deadlines and eventually
6474 ;; more distant deadlines.
6475 (let ((adjust (if today? (- diff) 0)))
6476 (+ adjust (org-get-priority item)))
6477 'todo-state todo-state
6478 'type (if upcoming? "upcoming-deadline" "deadline")
6479 'date (if upcoming? date deadline)
6480 'face (if done? 'org-agenda-done face)
6481 'undone-face face
6482 'done-face 'org-agenda-done)
6483 (push item deadline-items)))))))
6484 :next-re regexp
6485 :fail-re regexp
6486 :narrow t)
6487 (while (re-search-forward regexp nil t)
6488 (catch :skip
6489 (unless (save-match-data (org-at-planning-p)) (throw :skip nil))
6490 (org-agenda-skip)
6491 (let* ((s (match-string 1))
6492 (pos (1- (match-beginning 1)))
6493 (todo-state (save-match-data (org-get-todo-state)))
6494 (done? (member todo-state org-done-keywords))
6495 (sexp? (string-prefix-p "%%" s))
6496 ;; DEADLINE is the deadline date for the entry. It is
6497 ;; either the base date or the last repeat, according
6498 ;; to `org-agenda-prefer-last-repeat'.
6499 (deadline
6500 (cond
6501 (sexp? (org-agenda--timestamp-to-absolute s current))
6502 ((or (eq org-agenda-prefer-last-repeat t)
6503 (member todo-state org-agenda-prefer-last-repeat))
62216504 (org-agenda--timestamp-to-absolute
6222 s base 'future (current-buffer) pos)))))
6223 (diff (- deadline current))
6224 (suppress-prewarning
6225 (let ((scheduled
6226 (and org-agenda-skip-deadline-prewarning-if-scheduled
6227 (org-entry-get nil "SCHEDULED"))))
6505 s today 'past (current-buffer) pos))
6506 (t (org-agenda--timestamp-to-absolute s))))
6507 ;; REPEAT is the future repeat closest from CURRENT,
6508 ;; according to `org-agenda-show-future-repeats'. If
6509 ;; the latter is nil, or if the time stamp has no
6510 ;; repeat part, default to DEADLINE.
6511 (repeat
62286512 (cond
6229 ((not scheduled) nil)
6230 ;; The current item has a scheduled date, so
6231 ;; evaluate its prewarning lead time.
6232 ((integerp org-agenda-skip-deadline-prewarning-if-scheduled)
6233 ;; Use global prewarning-restart lead time.
6234 org-agenda-skip-deadline-prewarning-if-scheduled)
6235 ((eq org-agenda-skip-deadline-prewarning-if-scheduled
6236 'pre-scheduled)
6237 ;; Set pre-warning to no earlier than SCHEDULED.
6238 (min (- deadline
6239 (org-agenda--timestamp-to-absolute scheduled))
6240 org-deadline-warning-days))
6241 ;; Set pre-warning to deadline.
6242 (t 0))))
6243 (wdays (or suppress-prewarning (org-get-wdays s))))
6244 (cond
6245 ;; Only display deadlines at their base date, at future
6246 ;; repeat occurrences or in today agenda.
6247 ((= current deadline) nil)
6248 ((= current repeat) nil)
6249 ((not today?) (throw :skip nil))
6250 ;; Upcoming deadline: display within warning period WDAYS.
6251 ((> deadline current) (when (> diff wdays) (throw :skip nil)))
6252 ;; Overdue deadline: warn about it for
6253 ;; `org-deadline-past-days' duration.
6254 (t (when (< org-deadline-past-days (- diff)) (throw :skip nil))))
6255 ;; Possibly skip done tasks.
6256 (when (and done?
6257 (or org-agenda-skip-deadline-if-done
6258 (/= deadline current)))
6259 (throw :skip nil))
6260 (save-excursion
6261 (re-search-backward "^\\*+[ \t]+" nil t)
6262 (goto-char (match-end 0))
6263 (let* ((category (org-get-category))
6264 (level (make-string (org-reduced-level (org-outline-level))
6265 ?\s))
6266 (head (buffer-substring (point) (line-end-position)))
6267 (inherited-tags
6268 (or (eq org-agenda-show-inherited-tags 'always)
6269 (and (listp org-agenda-show-inherited-tags)
6270 (memq 'agenda org-agenda-show-inherited-tags))
6271 (and (eq org-agenda-show-inherited-tags t)
6272 (or (eq org-agenda-use-tag-inheritance t)
6273 (memq 'agenda
6274 org-agenda-use-tag-inheritance)))))
6275 (tags (org-get-tags nil (not inherited-tags)))
6276 (time
6513 (sexp? deadline)
6514 ((<= current today) deadline)
6515 ((not org-agenda-show-future-repeats) deadline)
6516 (t
6517 (let ((base (if (eq org-agenda-show-future-repeats 'next)
6518 (1+ today)
6519 current)))
6520 (org-agenda--timestamp-to-absolute
6521 s base 'future (current-buffer) pos)))))
6522 (diff (- deadline current))
6523 (suppress-prewarning
6524 (let ((scheduled
6525 (and org-agenda-skip-deadline-prewarning-if-scheduled
6526 (org-entry-get nil "SCHEDULED"))))
62776527 (cond
6278 ;; No time of day designation if it is only
6279 ;; a reminder.
6280 ((and (/= current deadline) (/= current repeat)) nil)
6281 ((string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
6282 (concat (substring s (match-beginning 1)) " "))
6283 (t 'time)))
6284 (item
6285 (org-agenda-format-item
6286 ;; Insert appropriate suffixes before deadlines.
6287 ;; Those only apply to today agenda.
6288 (pcase-let ((`(,now ,future ,past)
6289 org-agenda-deadline-leaders))
6290 (cond
6291 ((and today? (< deadline today)) (format past (- diff)))
6292 ((and today? (> deadline today)) (format future diff))
6293 (t now)))
6294 head level category tags time))
6295 (face (org-agenda-deadline-face
6296 (- 1 (/ (float diff) (max wdays 1)))))
6297 (upcoming? (and today? (> deadline today)))
6298 (warntime (get-text-property (point) 'org-appt-warntime)))
6299 (org-add-props item props
6300 'org-marker (org-agenda-new-marker pos)
6301 'org-hd-marker (org-agenda-new-marker (line-beginning-position))
6302 'warntime warntime
6303 'level level
6304 'ts-date deadline
6305 'priority
6306 ;; Adjust priority to today reminders about deadlines.
6307 ;; Overdue deadlines get the highest priority
6308 ;; increase, then imminent deadlines and eventually
6309 ;; more distant deadlines.
6310 (let ((adjust (if today? (- diff) 0)))
6311 (+ adjust (org-get-priority item)))
6312 'todo-state todo-state
6313 'type (if upcoming? "upcoming-deadline" "deadline")
6314 'date (if upcoming? date deadline)
6315 'face (if done? 'org-agenda-done face)
6316 'undone-face face
6317 'done-face 'org-agenda-done)
6318 (push item deadline-items))))))
6528 ((not scheduled) nil)
6529 ;; The current item has a scheduled date, so
6530 ;; evaluate its prewarning lead time.
6531 ((integerp org-agenda-skip-deadline-prewarning-if-scheduled)
6532 ;; Use global prewarning-restart lead time.
6533 org-agenda-skip-deadline-prewarning-if-scheduled)
6534 ((eq org-agenda-skip-deadline-prewarning-if-scheduled
6535 'pre-scheduled)
6536 ;; Set pre-warning to no earlier than SCHEDULED.
6537 (min (- deadline
6538 (org-agenda--timestamp-to-absolute scheduled))
6539 org-deadline-warning-days))
6540 ;; Set pre-warning to deadline.
6541 (t 0))))
6542 (wdays (or suppress-prewarning (org-get-wdays s))))
6543 (cond
6544 ;; Only display deadlines at their base date, at future
6545 ;; repeat occurrences or in today agenda.
6546 ((= current deadline) nil)
6547 ((= current repeat) nil)
6548 ((not today?) (throw :skip nil))
6549 ;; Upcoming deadline: display within warning period WDAYS.
6550 ((> deadline current) (when (> diff wdays) (throw :skip nil)))
6551 ;; Overdue deadline: warn about it for
6552 ;; `org-deadline-past-days' duration.
6553 (t (when (< org-deadline-past-days (- diff)) (throw :skip nil))))
6554 ;; Possibly skip done tasks.
6555 (when (and done?
6556 (or org-agenda-skip-deadline-if-done
6557 (/= deadline current)))
6558 (throw :skip nil))
6559 (save-excursion
6560 (re-search-backward "^\\*+[ \t]+" nil t)
6561 (goto-char (match-end 0))
6562 (let* ((category (org-get-category))
6563 (effort (save-match-data (or (get-text-property (point) 'effort)
6564 (org-entry-get (point) org-effort-property))))
6565 (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort))))
6566 (level (make-string (org-reduced-level (org-outline-level))
6567 ?\s))
6568 (head (buffer-substring-no-properties
6569 (point) (line-end-position)))
6570 (inherited-tags
6571 (or (eq org-agenda-show-inherited-tags 'always)
6572 (and (listp org-agenda-show-inherited-tags)
6573 (memq 'agenda org-agenda-show-inherited-tags))
6574 (and (eq org-agenda-show-inherited-tags t)
6575 (or (eq org-agenda-use-tag-inheritance t)
6576 (memq 'agenda
6577 org-agenda-use-tag-inheritance)))))
6578 (tags (org-get-tags nil (not inherited-tags)))
6579 (time
6580 (cond
6581 ;; No time of day designation if it is only
6582 ;; a reminder.
6583 ((and (/= current deadline) (/= current repeat)) nil)
6584 ((string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
6585 (concat (substring s (match-beginning 1)) " "))
6586 (t 'time)))
6587 (item
6588 (org-agenda-format-item
6589 ;; Insert appropriate suffixes before deadlines.
6590 ;; Those only apply to today agenda.
6591 (pcase-let ((`(,now ,future ,past)
6592 org-agenda-deadline-leaders))
6593 (cond
6594 ((and today? (< deadline today)) (format past (- diff)))
6595 ((and today? (> deadline today)) (format future diff))
6596 (t now)))
6597 (org-add-props head nil
6598 'effort effort
6599 'effort-minutes effort-minutes)
6600 level category tags time))
6601 (face (org-agenda-deadline-face
6602 (- 1 (/ (float diff) (max wdays 1)))))
6603 (upcoming? (and today? (> deadline today)))
6604 (warntime (get-text-property (point) 'org-appt-warntime)))
6605 (org-add-props item props
6606 'org-marker (org-agenda-new-marker pos)
6607 'org-hd-marker (org-agenda-new-marker (line-beginning-position))
6608 'warntime warntime
6609 'level level
6610 'effort effort 'effort-minutes effort-minutes
6611 'ts-date deadline
6612 'priority
6613 ;; Adjust priority to today reminders about deadlines.
6614 ;; Overdue deadlines get the highest priority
6615 ;; increase, then imminent deadlines and eventually
6616 ;; more distant deadlines.
6617 (let ((adjust (if today? (- diff) 0)))
6618 (+ adjust (org-get-priority item)))
6619 'todo-state todo-state
6620 'type (if upcoming? "upcoming-deadline" "deadline")
6621 'date (if upcoming? date deadline)
6622 'face (if done? 'org-agenda-done face)
6623 'undone-face face
6624 'done-face 'org-agenda-done)
6625 (push item deadline-items)))))))
63196626 (nreverse deadline-items)))
63206627
63216628 (defun org-agenda-deadline-face (fraction)
63506657 deadlines))
63516658 scheduled-items)
63526659 (goto-char (point-min))
6353 (while (re-search-forward regexp nil t)
6354 (catch :skip
6355 (unless (save-match-data (org-at-planning-p)) (throw :skip nil))
6356 (org-agenda-skip)
6357 (let* ((s (match-string 1))
6358 (pos (1- (match-beginning 1)))
6359 (todo-state (save-match-data (org-get-todo-state)))
6360 (donep (member todo-state org-done-keywords))
6361 (sexp? (string-prefix-p "%%" s))
6362 ;; SCHEDULE is the scheduled date for the entry. It is
6363 ;; either the bare date or the last repeat, according
6364 ;; to `org-agenda-prefer-last-repeat'.
6365 (schedule
6366 (cond
6367 (sexp? (org-agenda--timestamp-to-absolute s current))
6368 ((or (eq org-agenda-prefer-last-repeat t)
6369 (member todo-state org-agenda-prefer-last-repeat))
6370 (org-agenda--timestamp-to-absolute
6371 s today 'past (current-buffer) pos))
6372 (t (org-agenda--timestamp-to-absolute s))))
6373 ;; REPEAT is the future repeat closest from CURRENT,
6374 ;; according to `org-agenda-show-future-repeats'. If
6375 ;; the latter is nil, or if the time stamp has no
6376 ;; repeat part, default to SCHEDULE.
6377 (repeat
6378 (cond
6379 (sexp? schedule)
6380 ((<= current today) schedule)
6381 ((not org-agenda-show-future-repeats) schedule)
6382 (t
6383 (let ((base (if (eq org-agenda-show-future-repeats 'next)
6384 (1+ today)
6385 current)))
6660 (if (org-element--cache-active-p)
6661 (org-element-cache-map
6662 (lambda (el)
6663 (when (and (org-element-property :scheduled el)
6664 (or (not with-hour)
6665 (org-element-property
6666 :hour-start
6667 (org-element-property :scheduled el))
6668 (org-element-property
6669 :hour-end
6670 (org-element-property :scheduled el))))
6671 (goto-char (org-element-property :contents-begin el))
6672 (catch :skip
6673 (org-agenda-skip el)
6674 (let* ((s (substring (org-element-property
6675 :raw-value
6676 (org-element-property :scheduled el))
6677 1 -1))
6678 (pos (save-excursion
6679 (goto-char (org-element-property :contents-begin el))
6680 ;; We intentionally leave NOERROR
6681 ;; argument in `re-search-forward' nil. If
6682 ;; the search fails here, something went
6683 ;; wrong and we are looking at
6684 ;; non-matching headline.
6685 (re-search-forward regexp (line-end-position))
6686 (1- (match-beginning 1))))
6687 (todo-state (org-element-property :todo-keyword el))
6688 (donep (eq 'done (org-element-property :todo-type el)))
6689 (sexp? (eq 'diary
6690 (org-element-property
6691 :type (org-element-property :scheduled el))))
6692 ;; SCHEDULE is the scheduled date for the entry. It is
6693 ;; either the bare date or the last repeat, according
6694 ;; to `org-agenda-prefer-last-repeat'.
6695 (schedule
6696 (cond
6697 (sexp? (org-agenda--timestamp-to-absolute s current))
6698 ((or (eq org-agenda-prefer-last-repeat t)
6699 (member todo-state org-agenda-prefer-last-repeat))
6700 (org-agenda--timestamp-to-absolute
6701 s today 'past (current-buffer) pos))
6702 (t (org-agenda--timestamp-to-absolute s))))
6703 ;; REPEAT is the future repeat closest from CURRENT,
6704 ;; according to `org-agenda-show-future-repeats'. If
6705 ;; the latter is nil, or if the time stamp has no
6706 ;; repeat part, default to SCHEDULE.
6707 (repeat
6708 (cond
6709 (sexp? schedule)
6710 ((<= current today) schedule)
6711 ((not org-agenda-show-future-repeats) schedule)
6712 (t
6713 (let ((base (if (eq org-agenda-show-future-repeats 'next)
6714 (1+ today)
6715 current)))
6716 (org-agenda--timestamp-to-absolute
6717 s base 'future (current-buffer) pos)))))
6718 (diff (- current schedule))
6719 (warntime (get-text-property (point) 'org-appt-warntime))
6720 (pastschedp (< schedule today))
6721 (futureschedp (> schedule today))
6722 (habitp (and (fboundp 'org-is-habit-p)
6723 (string= "habit" (org-element-property :STYLE el))))
6724 (suppress-delay
6725 (let ((deadline (and org-agenda-skip-scheduled-delay-if-deadline
6726 (org-element-property
6727 :raw-value
6728 (org-element-property :deadline el)))))
6729 (cond
6730 ((not deadline) nil)
6731 ;; The current item has a deadline date, so
6732 ;; evaluate its delay time.
6733 ((integerp org-agenda-skip-scheduled-delay-if-deadline)
6734 ;; Use global delay time.
6735 (- org-agenda-skip-scheduled-delay-if-deadline))
6736 ((eq org-agenda-skip-scheduled-delay-if-deadline
6737 'post-deadline)
6738 ;; Set delay to no later than DEADLINE.
6739 (min (- schedule
6740 (org-agenda--timestamp-to-absolute deadline))
6741 org-scheduled-delay-days))
6742 (t 0))))
6743 (ddays
6744 (cond
6745 ;; Nullify delay when a repeater triggered already
6746 ;; and the delay is of the form --Xd.
6747 ((and (string-match-p "--[0-9]+[hdwmy]" s)
6748 (> schedule (org-agenda--timestamp-to-absolute s)))
6749 0)
6750 (suppress-delay
6751 (let ((org-scheduled-delay-days suppress-delay))
6752 (org-get-wdays s t t)))
6753 (t (org-get-wdays s t)))))
6754 ;; Display scheduled items at base date (SCHEDULE), today if
6755 ;; scheduled before the current date, and at any repeat past
6756 ;; today. However, skip delayed items and items that have
6757 ;; been displayed for more than `org-scheduled-past-days'.
6758 (unless (and todayp
6759 habitp
6760 (bound-and-true-p org-habit-show-all-today))
6761 (when (or (and (> ddays 0) (< diff ddays))
6762 (> diff (or (and habitp org-habit-scheduled-past-days)
6763 org-scheduled-past-days))
6764 (> schedule current)
6765 (and (/= current schedule)
6766 (/= current today)
6767 (/= current repeat)))
6768 (throw :skip nil)))
6769 ;; Possibly skip done tasks.
6770 (when (and donep
6771 (or org-agenda-skip-scheduled-if-done
6772 (/= schedule current)))
6773 (throw :skip nil))
6774 ;; Skip entry if it already appears as a deadline, per
6775 ;; `org-agenda-skip-scheduled-if-deadline-is-shown'. This
6776 ;; doesn't apply to habits.
6777 (when (pcase org-agenda-skip-scheduled-if-deadline-is-shown
6778 ((guard
6779 (or (not (memq (line-beginning-position 0) deadline-pos))
6780 habitp))
6781 nil)
6782 (`repeated-after-deadline
6783 (let ((deadline (time-to-days
6784 (when (org-element-property :deadline el)
6785 (org-time-string-to-time
6786 (org-element-property :deadline el))))))
6787 (and (<= schedule deadline) (> current deadline))))
6788 (`not-today pastschedp)
6789 (`t t)
6790 (_ nil))
6791 (throw :skip nil))
6792 ;; Skip habits if `org-habit-show-habits' is nil, or if we
6793 ;; only show them for today. Also skip done habits.
6794 (when (and habitp
6795 (or donep
6796 (not (bound-and-true-p org-habit-show-habits))
6797 (and (not todayp)
6798 (bound-and-true-p
6799 org-habit-show-habits-only-for-today))))
6800 (throw :skip nil))
6801 (save-excursion
6802 (goto-char (org-element-property :begin el))
6803 (let* ((category (org-get-category))
6804 (effort (save-match-data
6805 (or (get-text-property (point) 'effort)
6806 (org-element-property (intern (concat ":" (upcase org-effort-property))) el))))
6807 (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort))))
6808 (inherited-tags
6809 (or (eq org-agenda-show-inherited-tags 'always)
6810 (and (listp org-agenda-show-inherited-tags)
6811 (memq 'agenda org-agenda-show-inherited-tags))
6812 (and (eq org-agenda-show-inherited-tags t)
6813 (or (eq org-agenda-use-tag-inheritance t)
6814 (memq 'agenda
6815 org-agenda-use-tag-inheritance)))))
6816 (tags (org-get-tags el (not inherited-tags)))
6817 (level (make-string (org-element-property :level el)
6818 ?\s))
6819 (head (save-excursion
6820 (goto-char (org-element-property :begin el))
6821 (re-search-forward org-outline-regexp-bol)
6822 (buffer-substring (point) (line-end-position))))
6823 (time
6824 (cond
6825 ;; No time of day designation if it is only a
6826 ;; reminder, except for habits, which always show
6827 ;; the time of day. Habits are an exception
6828 ;; because if there is a time of day, that is
6829 ;; interpreted to mean they should usually happen
6830 ;; then, even if doing the habit was missed.
6831 ((and
6832 (not habitp)
6833 (/= current schedule)
6834 (/= current repeat))
6835 nil)
6836 ((string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
6837 (concat (substring s (match-beginning 1)) " "))
6838 (t 'time)))
6839 (item
6840 (org-agenda-format-item
6841 (pcase-let ((`(,first ,past) org-agenda-scheduled-leaders))
6842 ;; Show a reminder of a past scheduled today.
6843 (if (and todayp pastschedp)
6844 (format past diff)
6845 first))
6846 (org-add-props head nil
6847 'effort effort
6848 'effort-minutes effort-minutes)
6849 level category tags time nil habitp))
6850 (face (cond ((and (not habitp) pastschedp)
6851 'org-scheduled-previously)
6852 ((and habitp futureschedp)
6853 'org-agenda-done)
6854 (todayp 'org-scheduled-today)
6855 (t 'org-scheduled)))
6856 (habitp (and habitp (org-habit-parse-todo (org-element-property :begin el)))))
6857 (org-add-props item props
6858 'undone-face face
6859 'face (if donep 'org-agenda-done face)
6860 'org-marker (org-agenda-new-marker pos)
6861 'org-hd-marker (org-agenda-new-marker (line-beginning-position))
6862 'type (if pastschedp "past-scheduled" "scheduled")
6863 'date (if pastschedp schedule date)
6864 'ts-date schedule
6865 'warntime warntime
6866 'level level
6867 'effort effort 'effort-minutes effort-minutes
6868 'priority (if habitp (org-habit-get-priority habitp)
6869 (+ 99 diff (org-get-priority item)))
6870 'org-habit-p habitp
6871 'todo-state todo-state)
6872 (push item scheduled-items)))))))
6873 :next-re regexp
6874 :fail-re regexp
6875 :narrow t)
6876 (while (re-search-forward regexp nil t)
6877 (catch :skip
6878 (unless (save-match-data (org-at-planning-p)) (throw :skip nil))
6879 (org-agenda-skip)
6880 (let* ((s (match-string 1))
6881 (pos (1- (match-beginning 1)))
6882 (todo-state (save-match-data (org-get-todo-state)))
6883 (donep (member todo-state org-done-keywords))
6884 (sexp? (string-prefix-p "%%" s))
6885 ;; SCHEDULE is the scheduled date for the entry. It is
6886 ;; either the bare date or the last repeat, according
6887 ;; to `org-agenda-prefer-last-repeat'.
6888 (schedule
6889 (cond
6890 (sexp? (org-agenda--timestamp-to-absolute s current))
6891 ((or (eq org-agenda-prefer-last-repeat t)
6892 (member todo-state org-agenda-prefer-last-repeat))
63866893 (org-agenda--timestamp-to-absolute
6387 s base 'future (current-buffer) pos)))))
6388 (diff (- current schedule))
6389 (warntime (get-text-property (point) 'org-appt-warntime))
6390 (pastschedp (< schedule today))
6391 (futureschedp (> schedule today))
6392 (habitp (and (fboundp 'org-is-habit-p) (org-is-habit-p)))
6393 (suppress-delay
6394 (let ((deadline (and org-agenda-skip-scheduled-delay-if-deadline
6395 (org-entry-get nil "DEADLINE"))))
6894 s today 'past (current-buffer) pos))
6895 (t (org-agenda--timestamp-to-absolute s))))
6896 ;; REPEAT is the future repeat closest from CURRENT,
6897 ;; according to `org-agenda-show-future-repeats'. If
6898 ;; the latter is nil, or if the time stamp has no
6899 ;; repeat part, default to SCHEDULE.
6900 (repeat
63966901 (cond
6397 ((not deadline) nil)
6398 ;; The current item has a deadline date, so
6399 ;; evaluate its delay time.
6400 ((integerp org-agenda-skip-scheduled-delay-if-deadline)
6401 ;; Use global delay time.
6402 (- org-agenda-skip-scheduled-delay-if-deadline))
6403 ((eq org-agenda-skip-scheduled-delay-if-deadline
6404 'post-deadline)
6405 ;; Set delay to no later than DEADLINE.
6406 (min (- schedule
6407 (org-agenda--timestamp-to-absolute deadline))
6408 org-scheduled-delay-days))
6409 (t 0))))
6410 (ddays
6411 (cond
6412 ;; Nullify delay when a repeater triggered already
6413 ;; and the delay is of the form --Xd.
6414 ((and (string-match-p "--[0-9]+[hdwmy]" s)
6415 (> schedule (org-agenda--timestamp-to-absolute s)))
6416 0)
6417 (suppress-delay
6418 (let ((org-scheduled-delay-days suppress-delay))
6419 (org-get-wdays s t t)))
6420 (t (org-get-wdays s t)))))
6421 ;; Display scheduled items at base date (SCHEDULE), today if
6422 ;; scheduled before the current date, and at any repeat past
6423 ;; today. However, skip delayed items and items that have
6424 ;; been displayed for more than `org-scheduled-past-days'.
6425 (unless (and todayp
6426 habitp
6427 (bound-and-true-p org-habit-show-all-today))
6428 (when (or (and (> ddays 0) (< diff ddays))
6429 (> diff (or (and habitp org-habit-scheduled-past-days)
6430 org-scheduled-past-days))
6431 (> schedule current)
6432 (and (/= current schedule)
6433 (/= current today)
6434 (/= current repeat)))
6435 (throw :skip nil)))
6436 ;; Possibly skip done tasks.
6437 (when (and donep
6438 (or org-agenda-skip-scheduled-if-done
6439 (/= schedule current)))
6440 (throw :skip nil))
6441 ;; Skip entry if it already appears as a deadline, per
6442 ;; `org-agenda-skip-scheduled-if-deadline-is-shown'. This
6443 ;; doesn't apply to habits.
6444 (when (pcase org-agenda-skip-scheduled-if-deadline-is-shown
6445 ((guard
6446 (or (not (memq (line-beginning-position 0) deadline-pos))
6447 habitp))
6448 nil)
6449 (`repeated-after-deadline
6450 (let ((deadline (time-to-days
6451 (org-get-deadline-time (point)))))
6452 (and (<= schedule deadline) (> current deadline))))
6453 (`not-today pastschedp)
6454 (`t t)
6455 (_ nil))
6456 (throw :skip nil))
6457 ;; Skip habits if `org-habit-show-habits' is nil, or if we
6458 ;; only show them for today. Also skip done habits.
6459 (when (and habitp
6460 (or donep
6461 (not (bound-and-true-p org-habit-show-habits))
6462 (and (not todayp)
6463 (bound-and-true-p
6464 org-habit-show-habits-only-for-today))))
6465 (throw :skip nil))
6466 (save-excursion
6467 (re-search-backward "^\\*+[ \t]+" nil t)
6468 (goto-char (match-end 0))
6469 (let* ((category (org-get-category))
6470 (inherited-tags
6471 (or (eq org-agenda-show-inherited-tags 'always)
6472 (and (listp org-agenda-show-inherited-tags)
6473 (memq 'agenda org-agenda-show-inherited-tags))
6474 (and (eq org-agenda-show-inherited-tags t)
6475 (or (eq org-agenda-use-tag-inheritance t)
6476 (memq 'agenda
6477 org-agenda-use-tag-inheritance)))))
6478 (tags (org-get-tags nil (not inherited-tags)))
6479 (level (make-string (org-reduced-level (org-outline-level))
6480 ?\s))
6481 (head (buffer-substring (point) (line-end-position)))
6482 (time
6902 (sexp? schedule)
6903 ((<= current today) schedule)
6904 ((not org-agenda-show-future-repeats) schedule)
6905 (t
6906 (let ((base (if (eq org-agenda-show-future-repeats 'next)
6907 (1+ today)
6908 current)))
6909 (org-agenda--timestamp-to-absolute
6910 s base 'future (current-buffer) pos)))))
6911 (diff (- current schedule))
6912 (warntime (get-text-property (point) 'org-appt-warntime))
6913 (pastschedp (< schedule today))
6914 (futureschedp (> schedule today))
6915 (habitp (and (fboundp 'org-is-habit-p) (org-is-habit-p)))
6916 (suppress-delay
6917 (let ((deadline (and org-agenda-skip-scheduled-delay-if-deadline
6918 (org-entry-get nil "DEADLINE"))))
64836919 (cond
6484 ;; No time of day designation if it is only a
6485 ;; reminder, except for habits, which always show
6486 ;; the time of day. Habits are an exception
6487 ;; because if there is a time of day, that is
6488 ;; interpreted to mean they should usually happen
6489 ;; then, even if doing the habit was missed.
6490 ((and
6491 (not habitp)
6492 (/= current schedule)
6493 (/= current repeat))
6494 nil)
6495 ((string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
6496 (concat (substring s (match-beginning 1)) " "))
6497 (t 'time)))
6498 (item
6499 (org-agenda-format-item
6500 (pcase-let ((`(,first ,past) org-agenda-scheduled-leaders))
6501 ;; Show a reminder of a past scheduled today.
6502 (if (and todayp pastschedp)
6503 (format past diff)
6504 first))
6505 head level category tags time nil habitp))
6506 (face (cond ((and (not habitp) pastschedp)
6507 'org-scheduled-previously)
6508 ((and habitp futureschedp)
6509 'org-agenda-done)
6510 (todayp 'org-scheduled-today)
6511 (t 'org-scheduled)))
6512 (habitp (and habitp (org-habit-parse-todo))))
6513 (org-add-props item props
6514 'undone-face face
6515 'face (if donep 'org-agenda-done face)
6516 'org-marker (org-agenda-new-marker pos)
6517 'org-hd-marker (org-agenda-new-marker (line-beginning-position))
6518 'type (if pastschedp "past-scheduled" "scheduled")
6519 'date (if pastschedp schedule date)
6520 'ts-date schedule
6521 'warntime warntime
6522 'level level
6523 'priority (if habitp (org-habit-get-priority habitp)
6524 (+ 99 diff (org-get-priority item)))
6525 'org-habit-p habitp
6526 'todo-state todo-state)
6527 (push item scheduled-items))))))
6920 ((not deadline) nil)
6921 ;; The current item has a deadline date, so
6922 ;; evaluate its delay time.
6923 ((integerp org-agenda-skip-scheduled-delay-if-deadline)
6924 ;; Use global delay time.
6925 (- org-agenda-skip-scheduled-delay-if-deadline))
6926 ((eq org-agenda-skip-scheduled-delay-if-deadline
6927 'post-deadline)
6928 ;; Set delay to no later than DEADLINE.
6929 (min (- schedule
6930 (org-agenda--timestamp-to-absolute deadline))
6931 org-scheduled-delay-days))
6932 (t 0))))
6933 (ddays
6934 (cond
6935 ;; Nullify delay when a repeater triggered already
6936 ;; and the delay is of the form --Xd.
6937 ((and (string-match-p "--[0-9]+[hdwmy]" s)
6938 (> schedule (org-agenda--timestamp-to-absolute s)))
6939 0)
6940 (suppress-delay
6941 (let ((org-scheduled-delay-days suppress-delay))
6942 (org-get-wdays s t t)))
6943 (t (org-get-wdays s t)))))
6944 ;; Display scheduled items at base date (SCHEDULE), today if
6945 ;; scheduled before the current date, and at any repeat past
6946 ;; today. However, skip delayed items and items that have
6947 ;; been displayed for more than `org-scheduled-past-days'.
6948 (unless (and todayp
6949 habitp
6950 (bound-and-true-p org-habit-show-all-today))
6951 (when (or (and (> ddays 0) (< diff ddays))
6952 (> diff (or (and habitp org-habit-scheduled-past-days)
6953 org-scheduled-past-days))
6954 (> schedule current)
6955 (and (/= current schedule)
6956 (/= current today)
6957 (/= current repeat)))
6958 (throw :skip nil)))
6959 ;; Possibly skip done tasks.
6960 (when (and donep
6961 (or org-agenda-skip-scheduled-if-done
6962 (/= schedule current)))
6963 (throw :skip nil))
6964 ;; Skip entry if it already appears as a deadline, per
6965 ;; `org-agenda-skip-scheduled-if-deadline-is-shown'. This
6966 ;; doesn't apply to habits.
6967 (when (pcase org-agenda-skip-scheduled-if-deadline-is-shown
6968 ((guard
6969 (or (not (memq (line-beginning-position 0) deadline-pos))
6970 habitp))
6971 nil)
6972 (`repeated-after-deadline
6973 (let ((deadline (time-to-days
6974 (org-get-deadline-time (point)))))
6975 (and (<= schedule deadline) (> current deadline))))
6976 (`not-today pastschedp)
6977 (`t t)
6978 (_ nil))
6979 (throw :skip nil))
6980 ;; Skip habits if `org-habit-show-habits' is nil, or if we
6981 ;; only show them for today. Also skip done habits.
6982 (when (and habitp
6983 (or donep
6984 (not (bound-and-true-p org-habit-show-habits))
6985 (and (not todayp)
6986 (bound-and-true-p
6987 org-habit-show-habits-only-for-today))))
6988 (throw :skip nil))
6989 (save-excursion
6990 (re-search-backward "^\\*+[ \t]+" nil t)
6991 (goto-char (match-end 0))
6992 (let* ((category (org-get-category))
6993 (effort (save-match-data (or (get-text-property (point) 'effort)
6994 (org-entry-get (point) org-effort-property))))
6995 (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort))))
6996 (inherited-tags
6997 (or (eq org-agenda-show-inherited-tags 'always)
6998 (and (listp org-agenda-show-inherited-tags)
6999 (memq 'agenda org-agenda-show-inherited-tags))
7000 (and (eq org-agenda-show-inherited-tags t)
7001 (or (eq org-agenda-use-tag-inheritance t)
7002 (memq 'agenda
7003 org-agenda-use-tag-inheritance)))))
7004 (tags (org-get-tags nil (not inherited-tags)))
7005 (level (make-string (org-reduced-level (org-outline-level))
7006 ?\s))
7007 (head (buffer-substring (point) (line-end-position)))
7008 (time
7009 (cond
7010 ;; No time of day designation if it is only a
7011 ;; reminder, except for habits, which always show
7012 ;; the time of day. Habits are an exception
7013 ;; because if there is a time of day, that is
7014 ;; interpreted to mean they should usually happen
7015 ;; then, even if doing the habit was missed.
7016 ((and
7017 (not habitp)
7018 (/= current schedule)
7019 (/= current repeat))
7020 nil)
7021 ((string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
7022 (concat (substring s (match-beginning 1)) " "))
7023 (t 'time)))
7024 (item
7025 (org-agenda-format-item
7026 (pcase-let ((`(,first ,past) org-agenda-scheduled-leaders))
7027 ;; Show a reminder of a past scheduled today.
7028 (if (and todayp pastschedp)
7029 (format past diff)
7030 first))
7031 (org-add-props head nil
7032 'effort effort
7033 'effort-minutes effort-minutes)
7034 level category tags time nil habitp))
7035 (face (cond ((and (not habitp) pastschedp)
7036 'org-scheduled-previously)
7037 ((and habitp futureschedp)
7038 'org-agenda-done)
7039 (todayp 'org-scheduled-today)
7040 (t 'org-scheduled)))
7041 (habitp (and habitp (org-habit-parse-todo))))
7042 (org-add-props item props
7043 'undone-face face
7044 'face (if donep 'org-agenda-done face)
7045 'org-marker (org-agenda-new-marker pos)
7046 'org-hd-marker (org-agenda-new-marker (line-beginning-position))
7047 'type (if pastschedp "past-scheduled" "scheduled")
7048 'date (if pastschedp schedule date)
7049 'ts-date schedule
7050 'warntime warntime
7051 'level level
7052 'effort effort 'effort-minutes effort-minutes
7053 'priority (if habitp (org-habit-get-priority habitp)
7054 (+ 99 diff (org-get-priority item)))
7055 'org-habit-p habitp
7056 'todo-state todo-state)
7057 (push item scheduled-items)))))))
65287058 (nreverse scheduled-items)))
65297059
65307060 (defun org-agenda-get-blocks ()
65417071 (regexp org-tr-regexp)
65427072 (d0 (calendar-absolute-from-gregorian date))
65437073 marker hdmarker ee txt d1 d2 s1 s2 category
6544 level todo-state tags pos head donep inherited-tags)
7074 level todo-state tags pos head donep inherited-tags
7075 effort effort-minutes)
65457076 (goto-char (point-min))
65467077 (while (re-search-forward regexp nil t)
65477078 (catch :skip
65817112 (throw :skip t))
65827113 (setq marker (org-agenda-new-marker (point))
65837114 category (org-get-category))
7115 (setq effort (save-match-data (or (get-text-property (point) 'effort)
7116 (org-entry-get (point) org-effort-property))))
7117 (setq effort-minutes (when effort (save-match-data (org-duration-to-minutes effort))))
65847118 (if (not (re-search-backward org-outline-regexp-bol nil t))
65857119 (throw :skip nil)
65867120 (goto-char (match-beginning 0))
66087142 (nth (if (= d1 d2) 0 1)
66097143 org-agenda-timerange-leaders)
66107144 (1+ (- d0 d1)) (1+ (- d2 d1)))
6611 head level category tags
7145 (org-add-props head nil
7146 'effort effort
7147 'effort-minutes effort-minutes)
7148 level category tags
66127149 (save-match-data
66137150 (let ((hhmm1 (and (string-match org-ts-regexp1 s1)
66147151 (match-string 6 s1)))
66277164 'org-marker marker 'org-hd-marker hdmarker
66287165 'type "block" 'date date
66297166 'level level
7167 'effort effort 'effort-minutes effort-minutes
66307168 'todo-state todo-state
66317169 'priority (org-get-priority txt))
66327170 (push txt ee))))
67917329 (let ((s (org-format-outline-path (org-get-outline-path)
67927330 (1- (frame-width))
67937331 nil org-agenda-breadcrumbs-separator)))
6794 (if (eq "" s) "" (concat s org-agenda-breadcrumbs-separator))))))
7332 (if (equal "" s) "" (concat s org-agenda-breadcrumbs-separator))))))
67957333 (setq time (cond (s2 (concat
67967334 (org-agenda-time-of-day-to-ampm-maybe s1)
67977335 "-" (org-agenda-time-of-day-to-ampm-maybe s2)
69157453
69167454 (defun org-compile-prefix-format (key)
69177455 "Compile the prefix format into a Lisp form that can be evaluated.
7456 KEY is the agenda type (see `org-agenda-prefix-format').
69187457 The resulting form and associated variable bindings is returned
69197458 and stored in the variable `org-prefix-format-compiled'."
69207459 (setq org-prefix-has-time nil
71437682 (save-excursion
71447683 (beginning-of-line 1)
71457684 (setq re (org-get-at-bol 'org-todo-regexp))
7146 (goto-char (or (text-property-any (point-at-bol) (point-at-eol) 'org-heading t) (point)))
7685 (goto-char (or (text-property-any (line-beginning-position)
7686 (line-end-position)
7687 'org-heading t)
7688 (point)))
71477689 (when (looking-at (concat "[ \t]*\\.*\\(" re "\\) +"))
71487690 (add-text-properties (match-beginning 0) (match-end 1)
71497691 (list 'face (org-get-todo-face 1)))
71767718 (concat
71777719 (substring x 0 (match-end 1))
71787720 (unless (string= org-agenda-todo-keyword-format "")
7179 (format org-agenda-todo-keyword-format
7180 (match-string 2 x)))
7181 ;; Remove `display' property as the icon could leak
7182 ;; on the white space.
7183 (org-add-props " " (org-plist-delete (text-properties-at 0 x)
7184 'display))
7721 (format org-agenda-todo-keyword-format
7722 (match-string 2 x)))
7723 (unless (string= org-agenda-todo-keyword-format "")
7724 ;; Remove `display' property as the icon could leak
7725 ;; on the white space.
7726 (apply #'propertize " " (org-plist-delete (text-properties-at 0 x) 'display)))
71857727 (substring x (match-end 3)))))))
71867728 x)))
71877729
72847826 \"timestamp_ia\", compare within each of these type. When TYPE
72857827 is the empty string, compare all timestamps without respect of
72867828 their type."
7287 (let* ((def (and (not org-agenda-sort-notime-is-late) -1))
7829 (let* ((def (if org-agenda-sort-notime-is-late 99999999 -1))
72887830 (ta (or (and (string-match type (or (get-text-property 1 'type a) ""))
72897831 (get-text-property 1 'ts-date a))
72907832 def))
73947936 When in a restricted subtree, remove it.
73957937
73967938 The restriction will span over the entire file if TYPE is `file',
7397 or if type is '(4), or if the cursor is before the first headline
7939 or if TYPE is (4), or if the cursor is before the first headline
73987940 in the file. Otherwise, only apply the restriction to the current
73997941 subtree."
74007942 (interactive "P")
74237965 (point)
74247966 (if org-agenda-restriction-lock-highlight-subtree
74257967 (save-excursion (org-end-of-subtree t t) (point))
7426 (point-at-eol)))
7968 (line-end-position)))
74277969 (move-marker org-agenda-restrict-begin (point))
74287970 (move-marker org-agenda-restrict-end
74297971 (save-excursion (org-end-of-subtree t t)))
74307972 (message "Locking agenda restriction to subtree"))
74317973 (put 'org-agenda-files 'org-restrict
74327974 (list (buffer-file-name (buffer-base-buffer))))
7433 (setq org-agenda-restrict nil)
7975 (setq org-agenda-restrict t)
74347976 (setq org-agenda-overriding-restriction 'file)
74357977 (move-marker org-agenda-restrict-begin nil)
74367978 (move-marker org-agenda-restrict-end nil)
75848126 org-agenda-buffer-name))
75858127 (org-agenda-keep-modes t)
75868128 (tag-filter org-agenda-tag-filter)
7587 (tag-preset (get 'org-agenda-tag-filter :preset-filter))
8129 (tag-preset (assoc-default 'tag org-agenda-filters-preset))
75888130 (top-hl-filter org-agenda-top-headline-filter)
75898131 (cat-filter org-agenda-category-filter)
7590 (cat-preset (get 'org-agenda-category-filter :preset-filter))
8132 (cat-preset (assoc-default 'category org-agenda-filters-preset))
75918133 (re-filter org-agenda-regexp-filter)
7592 (re-preset (get 'org-agenda-regexp-filter :preset-filter))
8134 (re-preset (assoc-default 'regexp org-agenda-filters-preset))
75938135 (effort-filter org-agenda-effort-filter)
7594 (effort-preset (get 'org-agenda-effort-filter :preset-filter))
8136 (effort-preset (assoc-default 'effort org-agenda-filters-preset))
75958137 (org-agenda-tag-filter-while-redo (or tag-filter tag-preset))
75968138 (cols org-agenda-columns-active)
75978139 (line (org-current-line))
75988140 (window-line (- line (org-current-line (window-start))))
7599 (lprops (get 'org-agenda-redo-command 'org-lprops))
8141 (lprops (get-text-property p 'org-lprops))
76008142 (redo-cmd (get-text-property p 'org-redo-cmd))
76018143 (last-args (get-text-property p 'org-last-args))
76028144 (org-agenda-overriding-cmd (get-text-property p 'org-series-cmd))
76078149 ((stringp last-args)
76088150 last-args))))
76098151 (series-redo-cmd (get-text-property p 'org-series-redo-cmd)))
7610 (put 'org-agenda-tag-filter :preset-filter nil)
7611 (put 'org-agenda-category-filter :preset-filter nil)
7612 (put 'org-agenda-regexp-filter :preset-filter nil)
7613 (put 'org-agenda-effort-filter :preset-filter nil)
76148152 (and cols (org-columns-quit))
76158153 (message "Rebuilding agenda buffer...")
76168154 (if series-redo-cmd
76188156 (cl-progv
76198157 (mapcar #'car lprops)
76208158 (mapcar (lambda (binding) (eval (cadr binding) t)) lprops)
7621 (eval redo-cmd t)))
8159 (eval redo-cmd t))
8160 (let ((inhibit-read-only t))
8161 (add-text-properties (point-min) (point-max) `(org-lprops ,lprops))))
76228162 (setq org-agenda-undo-list nil
76238163 org-agenda-pending-undo-list nil
76248164 org-agenda-tag-filter tag-filter
76278167 org-agenda-effort-filter effort-filter
76288168 org-agenda-top-headline-filter top-hl-filter)
76298169 (message "Rebuilding agenda buffer...done")
7630 (put 'org-agenda-tag-filter :preset-filter tag-preset)
7631 (put 'org-agenda-category-filter :preset-filter cat-preset)
7632 (put 'org-agenda-regexp-filter :preset-filter re-preset)
7633 (put 'org-agenda-effort-filter :preset-filter effort-preset)
76348170 (let ((tag (or tag-filter tag-preset))
76358171 (cat (or cat-filter cat-preset))
76368172 (effort (or effort-filter effort-preset))
76738209 (if (and org-agenda-filtered-by-category
76748210 org-agenda-category-filter)
76758211 (org-agenda-filter-show-all-cat)
7676 (let ((cat (org-no-properties (org-get-at-eol 'org-category 1))))
8212 (let ((cat (org-no-properties (org-agenda-get-category))))
76778213 (cond
76788214 ((and cat strip)
76798215 (org-agenda-filter-apply
80268562 (org-agenda-filter-apply org-agenda-tag-filter 'tag expand))))
80278563 ((eq char ?\\)
80288564 (org-agenda-filter-show-all-tag)
8029 (when (get 'org-agenda-tag-filter :preset-filter)
8565 (when (assoc-default 'tag org-agenda-filters-preset)
80308566 (org-agenda-filter-apply org-agenda-tag-filter 'tag expand)))
80318567 ((eq char ?.)
80328568 (setq org-agenda-tag-filter
80998635 ((eq type 'tag)
81008636 (setq filter
81018637 (delete-dups
8102 (append (get 'org-agenda-tag-filter :preset-filter)
8638 (append (assoc-default 'tag org-agenda-filters-preset)
81038639 filter)))
81048640 (dolist (x filter)
81058641 (let ((op (string-to-char x)))
81118647 ((eq type 'category)
81128648 (setq filter
81138649 (delete-dups
8114 (append (get 'org-agenda-category-filter :preset-filter)
8650 (append (assoc-default 'category org-agenda-filters-preset)
81158651 filter)))
81168652 (dolist (x filter)
81178653 (if (equal "-" (substring x 0 1))
81228658 ((eq type 'regexp)
81238659 (setq filter
81248660 (delete-dups
8125 (append (get 'org-agenda-regexp-filter :preset-filter)
8661 (append (assoc-default 'regexp org-agenda-filters-preset)
81268662 filter)))
81278663 (dolist (x filter)
81288664 (if (equal "-" (substring x 0 1))
81338669 ((eq type 'effort)
81348670 (setq filter
81358671 (delete-dups
8136 (append (get 'org-agenda-effort-filter :preset-filter)
8672 (append (assoc-default 'effort org-agenda-filters-preset)
81378673 filter)))
81388674 (dolist (x filter)
81398675 (push (org-agenda-filter-effort-form x) f))))
82498785 (defun org-agenda-filter-hide-line (type)
82508786 "If current line is TYPE, hide it in the agenda buffer."
82518787 (let* (buffer-invisibility-spec
8252 (beg (max (point-min) (1- (point-at-bol))))
8253 (end (point-at-eol)))
8788 (beg (max (point-min) (1- (line-beginning-position))))
8789 (end (line-end-position)))
82548790 (let ((inhibit-read-only t))
82558791 (add-text-properties
82568792 beg end `(invisible org-filtered org-filter-type ,type)))))
83348870 (set var (concat (symbol-value var) string)))
83358871
83368872 (defun org-agenda-goto-date (date)
8337 "Jump to DATE in agenda."
8873 "Jump to DATE in the agenda buffer.
8874
8875 When called interactively, prompt for the date.
8876 When called from Lisp, DATE should be a date as returned by
8877 `org-read-date'.
8878
8879 See also:
8880 `org-agenda-earlier' (\\[org-agenda-earlier])
8881 `org-agenda-later' (\\[org-agenda-later])
8882 `org-agenda-goto-today' (\\[org-agenda-goto-today])"
83388883 (interactive
83398884 (list
83408885 (let ((org-read-date-prefer-future org-agenda-jump-prefer-future))
83668911 org-agenda-this-buffer-is-sticky org-agenda-sticky))))
83678912
83688913 (defun org-agenda-goto-today ()
8369 "Go to today."
8914 "Go to today's date in the agenda buffer.
8915
8916 See also:
8917 `org-agenda-later' (\\[org-agenda-later])
8918 `org-agenda-earlier' (\\[org-agenda-earlier])
8919 `org-agenda-goto-date' (\\[org-agenda-goto-date])"
83708920 (interactive)
83718921 (org-agenda-check-type t 'agenda)
83728922 (let* ((args (get-text-property (min (1- (point-max)) (point)) 'org-last-args))
84258975 (message "No %s block" (if backward "previous" "further")))))))
84268976
84278977 (defun org-agenda-later (arg)
8428 "Go forward in time by the current span.
8429 With prefix ARG, go forward that many times the current span."
8978 "Go forward in time by the current span in the agenda buffer.
8979 With prefix ARG, go forward that many times the current span.
8980
8981 See also:
8982 `org-agenda-earlier' (\\[org-agenda-earlier])
8983 `org-agenda-goto-today' (\\[org-agenda-goto-today])
8984 `org-agenda-goto-date' (\\[org-agenda-goto-date])"
84308985 (interactive "p")
84318986 (org-agenda-check-type t 'agenda)
84328987 (let* ((wstart (window-start))
84679022 (set-window-start nil wstart)))
84689023
84699024 (defun org-agenda-earlier (arg)
8470 "Go backward in time by the current span.
8471 With prefix ARG, go backward that many times the current span."
9025 "Go backward in time by the current span in the agenda buffer.
9026 With prefix ARG, go backward that many times the current span.
9027
9028 See also:
9029 `org-agenda-later' (\\[org-agenda-later])
9030 `org-agenda-goto-today' (\\[org-agenda-goto-today])
9031 `org-agenda-goto-date' (\\[org-agenda-goto-date])"
84729032 (interactive "p")
84739033 (org-agenda-later (- arg)))
84749034
88029362 (t ""))
88039363 (if (org-agenda-filter-any) " " "")
88049364 (if (or org-agenda-category-filter
8805 (get 'org-agenda-category-filter :preset-filter))
9365 (assoc-default 'category org-agenda-filters-preset))
88069366 '(:eval (propertize
88079367 (concat "["
88089368 (mapconcat
88099369 #'identity
88109370 (append
8811 (get 'org-agenda-category-filter :preset-filter)
9371 (assoc-default 'category org-agenda-filters-preset)
88129372 org-agenda-category-filter)
88139373 "")
88149374 "]")
88169376 'help-echo "Category used in filtering"))
88179377 "")
88189378 (if (or org-agenda-tag-filter
8819 (get 'org-agenda-tag-filter :preset-filter))
9379 (assoc-default 'tag org-agenda-filters-preset))
88209380 '(:eval (propertize
88219381 (concat (mapconcat
88229382 #'identity
88239383 (append
8824 (get 'org-agenda-tag-filter :preset-filter)
9384 (assoc-default 'tag org-agenda-filters-preset)
88259385 org-agenda-tag-filter)
88269386 ""))
88279387 'face 'org-agenda-filter-tags
88289388 'help-echo "Tags used in filtering"))
88299389 "")
88309390 (if (or org-agenda-effort-filter
8831 (get 'org-agenda-effort-filter :preset-filter))
9391 (assoc-default 'effort org-agenda-filters-preset))
88329392 '(:eval (propertize
88339393 (concat (mapconcat
88349394 #'identity
88359395 (append
8836 (get 'org-agenda-effort-filter :preset-filter)
9396 (assoc-default 'effort org-agenda-filters-preset)
88379397 org-agenda-effort-filter)
88389398 ""))
88399399 'face 'org-agenda-filter-effort
88409400 'help-echo "Effort conditions used in filtering"))
88419401 "")
88429402 (if (or org-agenda-regexp-filter
8843 (get 'org-agenda-regexp-filter :preset-filter))
9403 (assoc-default 'regexp org-agenda-filters-preset))
88449404 '(:eval (propertize
88459405 (concat (mapconcat
88469406 (lambda (x) (concat (substring x 0 1) "/" (substring x 1) "/"))
88479407 (append
8848 (get 'org-agenda-regexp-filter :preset-filter)
9408 (assoc-default 'regexp org-agenda-filters-preset)
88499409 org-agenda-regexp-filter)
88509410 ""))
88519411 'face 'org-agenda-filter-regexp
88829442 (interactive "p")
88839443 (let ((col (current-column)))
88849444 (dotimes (_ n)
8885 (when (next-single-property-change (point-at-eol) 'org-marker)
9445 (when (next-single-property-change (line-end-position) 'org-marker)
88869446 (move-end-of-line 1)
88879447 (goto-char (next-single-property-change (point) 'org-marker))))
88889448 (org-move-to-column col))
89099469 (org-agenda-tree-to-indirect-buffer nil)
89109470 (org-agenda-show)))
89119471 (and org-agenda-show-outline-path
8912 (org-with-point-at m (org-display-outline-path t))))))
9472 (org-with-point-at m (org-display-outline-path org-agenda-show-outline-path))))))
89139473
89149474 (defun org-agenda-show-tags ()
89159475 "Show the tags applicable to the current item."
89339493 (push-mark)
89349494 (goto-char pos)
89359495 (when (derived-mode-p 'org-mode)
8936 (org-show-context 'agenda)
9496 (org-fold-show-context 'agenda)
89379497 (recenter (/ (window-height) 2))
89389498 (org-back-to-heading t)
89399499 (let ((case-fold-search nil))
89409500 (when (re-search-forward org-complex-heading-regexp nil t)
89419501 (goto-char (match-beginning 4)))))
89429502 (run-hooks 'org-agenda-after-show-hook)
8943 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
9503 (and highlight (org-highlight (line-beginning-position)
9504 (line-end-position)))))
89449505
89459506 (defvar org-agenda-after-show-hook nil
89469507 "Normal hook run after an item has been shown from the agenda.
89639524 (level (and (eq org-agenda-loop-over-headlines-in-active-region 'start-level)
89649525 (org-get-at-bol 'level))))
89659526 (while (< (point) mend)
8966 (let ((ov (make-overlay (point) (point-at-eol))))
9527 (let ((ov (make-overlay (point) (line-end-position))))
89679528 (if (not (or all
8968 (and match (looking-at-p match))
8969 (eq level (org-get-at-bol 'level))))
9529 (and match (looking-at-p match))
9530 (eq level (org-get-at-bol 'level))))
89709531 (org-agenda-next-item 1)
89719532 (overlay-put ov 'face 'region)
89729533 (if (or arg force-arg) (funcall cmd arg) (funcall cmd))
90089569 (if (and (derived-mode-p 'org-mode) (not (member type '("sexp"))))
90099570 (setq dbeg (progn (org-back-to-heading t) (point))
90109571 dend (org-end-of-subtree t t))
9011 (setq dbeg (point-at-bol)
9012 dend (min (point-max) (1+ (point-at-eol)))))
9572 (setq dbeg (line-beginning-position)
9573 dend (min (point-max) (1+ (line-end-position)))))
90139574 (goto-char dbeg)
90149575 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
90159576 (when (or (eq t org-agenda-confirm-kill)
90219582 (prog2
90229583 (org-agenda-tree-to-indirect-buffer nil)
90239584 (not (y-or-n-p
9024 (format "Delete entry with %d lines in buffer \"%s\"? "
9025 n (buffer-name buffer))))
9585 (format "Delete entry with %d lines in buffer \"%s\"? "
9586 n (buffer-name buffer))))
90269587 (kill-buffer org-last-indirect-buffer))
90279588 (error "Abort"))
90289589 (set-window-configuration win-conf))))
91089669 (>= p beg)
91099670 (< p end))
91109671 (let ((inhibit-read-only t))
9111 (delete-region (point-at-bol) (1+ (point-at-eol)))))
9672 (delete-region (line-beginning-position)
9673 (1+ (line-end-position)))))
91129674 (beginning-of-line 0))))))
91139675
91149676 (defun org-agenda-refile (&optional goto rfloc no-update)
91579719 (let* ((marker (or (org-get-at-bol 'org-hd-marker)
91589720 (org-get-at-bol 'org-marker)))
91599721 (buffer (and marker (marker-buffer marker)))
9160 (prefix (buffer-substring (point-at-bol) (point-at-eol)))
9722 (prefix (buffer-substring (line-beginning-position)
9723 (line-end-position)))
91619724 (lkall (and buffer (org-offer-links-in-entry
91629725 buffer marker arg prefix)))
91639726 (lk0 (car lkall))
92229785 (widen)
92239786 (goto-char pos)
92249787 (when (derived-mode-p 'org-mode)
9225 (org-show-context 'agenda)
9788 (org-fold-show-context 'agenda)
92269789 (run-hooks 'org-agenda-after-show-hook)))))
92279790
92289791 (defun org-agenda-goto-mouse (ev)
92389801 (interactive "P")
92399802 (let ((win (selected-window)))
92409803 (org-agenda-goto t)
9241 (when full-entry (org-show-entry))
9804 (when full-entry (org-fold-show-entry 'hide-drawers))
92429805 (select-window win)))
92439806
92449807 (defvar org-agenda-show-window nil)
92579820 (select-window org-agenda-show-window)
92589821 (ignore-errors (scroll-up)))
92599822 (org-agenda-goto t)
9260 (org-show-entry)
9823 (org-fold-show-entry 'hide-drawers)
92619824 (if arg (org-cycle-hide-drawers 'children)
92629825 (org-with-wide-buffer
92639826 (narrow-to-region (org-entry-beginning-position)
92649827 (org-entry-end-position))
9265 (org-show-all '(drawers))))
9828 (org-fold-show-all '(drawers))))
92669829 (setq org-agenda-show-window (selected-window)))
92679830 (select-window win)))
92689831
92909853 (let ((win (selected-window)))
92919854 (org-agenda-goto t)
92929855 (org-back-to-heading)
9293 (set-window-start (selected-window) (point-at-bol))
9856 (set-window-start (selected-window) (line-beginning-position))
92949857 (cond
92959858 ((= more 0)
9296 (org-flag-subtree t)
9859 (org-fold-subtree t)
92979860 (save-excursion
92989861 (org-back-to-heading)
92999862 (run-hook-with-args 'org-cycle-hook 'folded))
93019864 ((and (called-interactively-p 'any) (= more 1))
93029865 (message "Remote: show with default settings"))
93039866 ((= more 2)
9304 (outline-show-entry)
9305 (org-show-children)
9867 (org-fold-show-entry 'hide-drawers)
9868 (org-fold-show-children)
93069869 (save-excursion
93079870 (org-back-to-heading)
93089871 (run-hook-with-args 'org-cycle-hook 'children))
93099872 (message "Remote: CHILDREN"))
93109873 ((= more 3)
9311 (outline-show-subtree)
9874 (org-fold-show-subtree)
93129875 (save-excursion
93139876 (org-back-to-heading)
93149877 (run-hook-with-args 'org-cycle-hook 'subtree))
93159878 (message "Remote: SUBTREE"))
93169879 ((> more 3)
9317 (outline-show-subtree)
9880 (org-fold-show-subtree)
93189881 (message "Remote: SUBTREE AND ALL DRAWERS")))
93199882 (select-window win)))
93209883
944610009 (with-current-buffer buffer
944710010 (widen)
944810011 (goto-char pos)
9449 (org-show-context 'agenda)
10012 (org-fold-show-context 'agenda)
945010013 (let ((current-prefix-arg arg))
945110014 (call-interactively 'org-todo)
945210015 ;; Make sure that log is recorded in current undo.
948710050 (with-current-buffer buffer
948810051 (widen)
948910052 (goto-char pos)
9490 (org-show-context 'agenda)
10053 (org-fold-show-context 'agenda)
949110054 (org-add-note))))
949210055
949310056 (defun org-agenda-change-all-lines (newhead hdmarker
9494 &optional fixface just-this)
10057 &optional fixface just-this)
949510058 "Change all lines in the agenda buffer which match HDMARKER.
949610059 The new content of the line will be NEWHEAD (as modified by
949710060 `org-agenda-format-item'). HDMARKER is checked with
950510068 (org-agenda-buffer (current-buffer))
950610069 (thetags (with-current-buffer (marker-buffer hdmarker)
950710070 (org-get-tags hdmarker)))
9508 props m undone-face done-face finish new dotime level cat tags) ;; pl
10071 props m undone-face done-face finish new dotime level cat tags
10072 effort effort-minutes) ;; pl
950910073 (save-excursion
951010074 (goto-char (point-max))
951110075 (beginning-of-line 1)
951910083 cat (org-agenda-get-category)
952010084 level (org-get-at-bol 'level)
952110085 tags thetags
10086 effort (org-get-at-bol 'effort)
10087 effort-minutes (org-get-at-bol 'effort-minutes)
952210088 new
952310089 (let ((org-prefix-format-compiled
952410090 (or (get-text-property (min (1- (point-max)) (point)) 'format)
952610092 (extra (org-get-at-bol 'extra)))
952710093 (with-current-buffer (marker-buffer hdmarker)
952810094 (org-with-wide-buffer
9529 (org-agenda-format-item extra newhead level cat tags dotime))))
9530 ;; pl (text-property-any (point-at-bol) (point-at-eol) 'org-heading t)
10095 (org-agenda-format-item extra
10096 (org-add-props newhead nil
10097 'effort effort
10098 'effort-minutes effort-minutes)
10099 level cat tags dotime))))
10100 ;; pl (text-property-any (line-beginning-position)
10101 ;; (line-end-position) 'org-heading t)
953110102 undone-face (org-get-at-bol 'undone-face)
953210103 done-face (org-get-at-bol 'done-face))
953310104 (beginning-of-line 1)
954410115 (replace-match new t t)
954510116 (beginning-of-line)
954610117 (when mark (move-overlay mark (point) (+ 2 (point)))))
9547 (add-text-properties (point-at-bol) (point-at-eol) props)
10118 (add-text-properties (line-beginning-position)
10119 (line-end-position) props)
954810120 (when fixface
954910121 (add-text-properties
9550 (point-at-bol) (point-at-eol)
10122 (line-beginning-position) (line-end-position)
955110123 (list 'face
955210124 (if org-last-todo-state-is-todo
955310125 undone-face done-face))))
955510127 (beginning-of-line 1))
955610128 (t (error "Line update did not work")))
955710129 (save-restriction
9558 (narrow-to-region (point-at-bol) (point-at-eol))
10130 (narrow-to-region (line-beginning-position) (line-end-position))
955910131 (org-agenda-finalize)))
956010132 (beginning-of-line 0)))))
956110133
956510137 current line."
956610138 (let ((inhibit-read-only t)
956710139 (org-agenda-tags-column (if (eq 'auto org-agenda-tags-column)
9568 (- (window-text-width))
9569 org-agenda-tags-column))
10140 (- (window-max-chars-per-line))
10141 org-agenda-tags-column))
957010142 (end (and line (line-end-position)))
957110143 l c)
9572 (save-excursion
9573 (goto-char (if line (line-beginning-position) (point-min)))
9574 (while (re-search-forward org-tag-group-re end t)
9575 (add-text-properties
9576 (match-beginning 1) (match-end 1)
9577 (list 'face (delq nil (let ((prop (get-text-property
10144 (org-fold-core-ignore-modifications
10145 (save-excursion
10146 (goto-char (if line (line-beginning-position) (point-min)))
10147 (while (re-search-forward org-tag-group-re end t)
10148 (add-text-properties
10149 (match-beginning 1) (match-end 1)
10150 (list 'face (delq nil (let ((prop (get-text-property
957810151 (match-beginning 1) 'face)))
9579 (or (listp prop) (setq prop (list prop)))
9580 (if (memq 'org-tag prop)
10152 (or (listp prop) (setq prop (list prop)))
10153 (if (memq 'org-tag prop)
958110154 prop
958210155 (cons 'org-tag prop))))))
9583 (setq l (string-width (match-string 1))
9584 c (if (< org-agenda-tags-column 0)
9585 (- (abs org-agenda-tags-column) l)
9586 org-agenda-tags-column))
9587 (goto-char (match-beginning 1))
9588 (delete-region (save-excursion (skip-chars-backward " \t") (point))
9589 (point))
9590 (insert (org-add-props
9591 (make-string (max 1 (- c (current-column))) ?\s)
9592 (plist-put (copy-sequence (text-properties-at (point)))
9593 'face nil))))
9594 (goto-char (point-min))
9595 (org-font-lock-add-tag-faces (point-max)))))
10156 (setq l (string-width (match-string 1))
10157 c (if (< org-agenda-tags-column 0)
10158 (- (abs org-agenda-tags-column) l)
10159 org-agenda-tags-column))
10160 (goto-char (match-beginning 1))
10161 (delete-region (save-excursion (skip-chars-backward " \t") (point))
10162 (point))
10163 (insert (org-add-props
10164 (make-string (max 1 (- c (current-column))) ?\s)
10165 (plist-put (copy-sequence (text-properties-at (point)))
10166 'face nil))))
10167 (goto-char (point-min))
10168 (org-font-lock-add-tag-faces (point-max))))))
959610169
959710170 (defun org-agenda-priority-up ()
959810171 "Increase the priority of line at point, also in Org file."
962910202 (with-current-buffer buffer
963010203 (widen)
963110204 (goto-char pos)
9632 (org-show-context 'agenda)
10205 (org-fold-show-context 'agenda)
963310206 (org-priority force-direction)
963410207 (end-of-line 1)
963510208 (setq newhead (org-get-heading)))
965310226 (with-current-buffer buffer
965410227 (widen)
965510228 (goto-char pos)
9656 (org-show-context 'agenda)
10229 (org-fold-show-context 'agenda)
965710230 (if tag
965810231 (org-toggle-tag tag onoff)
965910232 (call-interactively #'org-set-tags-command))
967810251 (with-current-buffer buffer
967910252 (widen)
968010253 (goto-char pos)
9681 (org-show-context 'agenda)
10254 (org-fold-show-context 'agenda)
968210255 (call-interactively 'org-set-property))))))
968310256
968410257 (defun org-agenda-set-effort ()
969710270 (with-current-buffer buffer
969810271 (widen)
969910272 (goto-char pos)
9700 (org-show-context 'agenda)
10273 (org-fold-show-context 'agenda)
970110274 (call-interactively 'org-set-effort)
970210275 (end-of-line 1)
970310276 (setq newhead (org-get-heading)))
971910292 (with-current-buffer buffer
972010293 (widen)
972110294 (goto-char pos)
9722 (org-show-context 'agenda)
10295 (org-fold-show-context 'agenda)
972310296 (call-interactively 'org-toggle-archive-tag)
972410297 (end-of-line 1)
972510298 (setq newhead (org-get-heading)))
978610359 (setq arg (- today cdate))))
978710360 (org-timestamp-change arg (or what 'day))
978810361 (when (and (org-at-date-range-p)
9789 (re-search-backward org-tr-regexp-both (point-at-bol)))
10362 (re-search-backward org-tr-regexp-both
10363 (line-beginning-position)))
979010364 (let ((end org-last-changed-timestamp))
979110365 (org-timestamp-change arg (or what 'day))
979210366 (setq org-last-changed-timestamp
983410408 (line-end-position)
983510409 '(display nil))
983610410 (org-move-to-column
9837 (- (if (fboundp 'window-font-width)
9838 (/ (window-width nil t) (window-font-width))
9839 ;; Fall back to pre-9.3.3 behavior on Emacs <25.
9840 (window-width))
10411 (- (window-max-chars-per-line)
984110412 (length stamp))
984210413 t)
984310414 (add-text-properties
9844 (1- (point)) (point-at-eol)
10415 (1- (point)) (line-end-position)
984510416 (list 'display (org-add-props stamp nil
984610417 'face '(secondary-selection default))))
984710418 (beginning-of-line 1))
992910500 (with-current-buffer (marker-buffer marker)
993010501 (widen)
993110502 (goto-char pos)
9932 (org-show-context 'agenda)
10503 (org-fold-show-context 'agenda)
993310504 (org-clock-in arg)
993410505 (setq newhead (org-get-heading)))
993510506 (org-agenda-change-all-lines newhead hdmarker))
998510556 (if (equal (buffer-name) "*Calendar*")
998610557 (setq d1 (calendar-cursor-to-date t)
998710558 d2 (car calendar-mark-ring))
9988 (setq dp1 (get-text-property (point-at-bol) 'day))
10559 (setq dp1 (get-text-property (line-beginning-position) 'day))
998910560 (unless dp1 (user-error "No date defined in current line"))
999010561 (setq d1 (calendar-gregorian-from-absolute dp1)
999110562 d2 (and (ignore-errors (mark))
999210563 (save-excursion
999310564 (goto-char (mark))
9994 (setq dp2 (get-text-property (point-at-bol) 'day)))
10565 (setq dp2 (get-text-property (line-beginning-position) 'day)))
999510566 (calendar-gregorian-from-absolute dp2))))
999610567 (message "Diary entry: [d]ay [a]nniversary [b]lock [j]ump to date tree")
999710568 (setq char (read-char-exclusive))
1001810589 (find-file-noselect org-agenda-diary-file))
1001910590 (require 'org-datetree)
1002010591 (org-datetree-find-date-create d1)
10021 (org-reveal t))
10592 (org-fold-reveal t))
1002210593 (t (user-error "Invalid selection character `%c'" char)))))
1002310594
1002410595 (defcustom org-agenda-insert-diary-strategy 'date-tree
1006010631 (anniversary
1006110632 (or (re-search-forward "^\\*[ \t]+Anniversaries" nil t)
1006210633 (progn
10063 (or (org-at-heading-p t)
10634 (or (org-at-heading-p)
1006410635 (progn
1006510636 (outline-next-heading)
1006610637 (insert "* Anniversaries\n\n")
1012010691 (message "%s entry added to %s"
1012110692 (capitalize (symbol-name type))
1012210693 (abbreviate-file-name org-agenda-diary-file)))
10123 (org-reveal t)
10694 (org-fold-reveal t)
1012410695 (message "Please finish entry here"))))
1012510696
1012610697 (defun org-agenda-insert-diary-as-top-level (text)
1015810729 (unless (bolp) (insert "\n"))
1015910730 (unless (looking-at-p "^[ \t]*$") (save-excursion (insert "\n")))
1016010731 (when org-adapt-indentation (indent-to-column col)))
10161 (org-show-set-visibility 'lineage))
10732 (org-fold-show-set-visibility 'lineage))
1016210733
1016310734 (defun org-agenda-diary-entry ()
1016410735 "Make a diary entry, like the `i' command from the calendar.
1031410885
1031510886 (defun org-agenda-bulk-marked-p ()
1031610887 "Non-nil when current entry is marked for bulk action."
10317 (eq (get-char-property (point-at-bol) 'type)
10888 (eq (get-char-property (line-beginning-position) 'type)
1031810889 'org-marked-entry-overlay))
1031910890
1032010891 (defun org-agenda-bulk-mark (&optional arg)
1033910910 (unless (org-agenda-bulk-marked-p)
1034010911 (unless m (user-error "Nothing to mark at point"))
1034110912 (push m org-agenda-bulk-marked-entries)
10342 (setq ov (make-overlay (point-at-bol) (+ 2 (point-at-bol))))
10913 (setq ov (make-overlay (line-beginning-position)
10914 (+ 2 (line-beginning-position))))
1034310915 (org-overlay-display ov (concat org-agenda-bulk-mark-char " ")
1034410916 (org-get-todo-face "TODO")
1034510917 'evaporate)
1038310955 (org-agenda-bulk-unmark-all)
1038410956 (cond ((org-agenda-bulk-marked-p)
1038510957 (org-agenda-bulk-remove-overlays
10386 (point-at-bol) (+ 2 (point-at-bol)))
10958 (line-beginning-position) (+ 2 (line-beginning-position)))
1038710959 (setq org-agenda-bulk-marked-entries
1038810960 (delete (org-get-at-bol 'org-hd-marker)
1038910961 org-agenda-bulk-marked-entries))
1061011182 (ignore-errors
1061111183 (let* ((date (calendar-gregorian-from-absolute
1061211184 (+ (org-today) distance)))
10613 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date)
10614 (nth 2 date))))
11185 (time (org-encode-time
11186 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
1061511187 (org-agenda-schedule nil time))))))))
1061611188
1061711189 (?f
1068511257 (,org-agenda-category-filter category)
1068611258 (,org-agenda-regexp-filter regexp)
1068711259 (,org-agenda-effort-filter effort)
10688 (,(get 'org-agenda-tag-filter :preset-filter) tag)
10689 (,(get 'org-agenda-category-filter :preset-filter) category)
10690 (,(get 'org-agenda-effort-filter :preset-filter) effort)
10691 (,(get 'org-agenda-regexp-filter :preset-filter) regexp))))
11260 (,(assoc-default 'tag org-agenda-filters-preset) tag)
11261 (,(assoc-default 'category org-agenda-filters-preset) category)
11262 (,(assoc-default 'effort org-agenda-filters-preset) effort)
11263 (,(assoc-default 'regexp org-agenda-filters-preset) regexp))))
1069211264
1069311265 (defun org-agenda-drag-line-forward (arg &optional backward)
1069411266 "Drag an agenda line forward by ARG lines.
1076311335 (message "Entry unflagged")))
1076411336
1076511337 (defun org-agenda-get-any-marker (&optional pos)
10766 (or (get-text-property (or pos (point-at-bol)) 'org-hd-marker)
10767 (get-text-property (or pos (point-at-bol)) 'org-marker)))
11338 (or (get-text-property (or pos (line-beginning-position)) 'org-hd-marker)
11339 (get-text-property (or pos (line-beginning-position)) 'org-marker)))
1076811340
1076911341 ;;; Appointment reminders
1077011342
1079011362 FILTER can also be an alist with the car of each cell being
1079111363 either `headline' or `category'. For example:
1079211364
10793 \\='((headline \"IMPORTANT\")
11365 ((headline \"IMPORTANT\")
1079411366 (category \"Work\"))
1079511367
1079611368 will only add headlines containing IMPORTANT or headlines
00 ;;; org-archive.el --- Archiving for Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2727
2828 ;;; Code:
2929
30 (require 'org-macs)
31 (org-assert-version)
32
3033 (require 'org)
3134 (require 'cl-lib)
3235
3336 (declare-function org-element-type "org-element" (element))
3437 (declare-function org-datetree-find-date-create "org-datetree" (date &optional keep-restriction))
3538 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
39
40 ;; From org-element.el
41 (defvar org-element--cache-avoid-synchronous-headline-re-parsing)
3642
3743 (defcustom org-archive-default-command 'org-archive-subtree
3844 "The default archiving command."
232238 (tr-org-odd-levels-only org-odd-levels-only)
233239 (this-buffer (current-buffer))
234240 (time (format-time-string
235 (substring (cdr org-time-stamp-formats) 1 -1)))
241 (org-time-stamp-format 'with-time 'no-brackets)))
236242 (file (abbreviate-file-name
237243 (or (buffer-file-name (buffer-base-buffer))
238244 (error "No file associated to buffer"))))
252258 (if (local-variable-p 'org-odd-levels-only (current-buffer))
253259 org-odd-levels-only
254260 tr-org-odd-levels-only))
255 level datetree-date datetree-subheading-p)
261 level datetree-date datetree-subheading-p
262 ;; Suppress on-the-fly headline updates.
263 (org-element--cache-avoid-synchronous-headline-re-parsing t))
256264 (when (string-match "\\`datetree/\\(\\**\\)" heading)
257265 ;; "datetree/" corresponds to 3 levels of headings.
258266 (let ((nsub (length (match-string 1 heading))))
318326 (org-todo-regexp tr-org-todo-regexp)
319327 (org-todo-line-regexp tr-org-todo-line-regexp))
320328 (goto-char (point-min))
321 (org-show-all '(headings blocks))
329 (org-fold-show-all '(headings blocks))
322330 (if (and heading (not (and datetree-date (not datetree-subheading-p))))
323331 (progn
324332 (if (re-search-forward
333341 (insert (if datetree-date "" "\n") heading "\n")
334342 (end-of-line 0))
335343 ;; Make the subtree visible
336 (outline-show-subtree)
344 (org-fold-show-subtree)
337345 (if org-archive-reversed-order
338346 (progn
339347 (org-back-to-heading t)
411419 (if (eq this-buffer buffer)
412420 (concat "under heading: " heading)
413421 (concat "in file: " (abbreviate-file-name afile)))))))
414 (org-reveal)
422 (org-fold-reveal)
415423 (if (looking-at "^[ \t]*$")
416424 (outline-next-visible-heading 1))))
417425
447455 (setq leader (match-string 0)
448456 level (funcall outline-level))
449457 (setq pos (point-marker))
458 ;; Advance POS upon insertion in front of it.
459 (set-marker-insertion-type pos t)
450460 (condition-case nil
451461 (outline-up-heading 1 t)
452462 (error (setq e (point-max)) (goto-char (point-min))))
479489 (org-set-property
480490 "ARCHIVE_TIME"
481491 (format-time-string
482 (substring (cdr org-time-stamp-formats) 1 -1)))
492 (org-time-stamp-format 'with-time 'no-brackets)))
483493 (outline-up-heading 1 t)
484 (org-flag-subtree t)
494 (org-fold-subtree t)
485495 (org-cycle-show-empty-lines 'folded)
486496 (when org-provide-todo-statistics
487497 ;; Update TODO statistics of parent.
488498 (org-update-parent-todo-statistics))
489499 (goto-char pos)))
490 (org-reveal)
500 (org-fold-reveal)
491501 (if (looking-at "^[ \t]*$")
492502 (outline-next-visible-heading 1))))
493503
596606 (save-excursion
597607 (org-back-to-heading t)
598608 (setq set (org-toggle-tag org-archive-tag))
599 (when set (org-flag-subtree t)))
609 (when set (org-fold-subtree t)))
600610 (and set (beginning-of-line 1))
601611 (message "Subtree %s" (if set "archived" "unarchived"))))))
602612
00 ;;; org-attach-git.el --- Automatic git commit extension to org-attach -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2019-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2019-2023 Free Software Foundation, Inc.
33
44 ;; Original Author: John Wiegley <johnw@newartisans.com>
55 ;; Restructurer: Gustav Wikström <gustav@whil.se>
2828
2929 ;;; Code:
3030
31 (require 'org-macs)
32 (org-assert-version)
33
3134 (require 'org-attach)
3235 (require 'vc-git)
3336
4245
4346 (defcustom org-attach-git-annex-auto-get 'ask
4447 "Confirmation preference for automatically getting annex files.
45 If \\='ask, prompt using `y-or-n-p'. If t, always get. If nil, never get."
48 If this is the symbol `ask', prompt using `y-or-n-p'.
49 If t, always get. If nil, never get."
4650 :group 'org-attach
4751 :package-version '(Org . "9.0")
4852 :version "26.1"
00 ;;; org-attach.el --- Manage file attachments to Org outlines -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2008-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2008-2023 Free Software Foundation, Inc.
33
44 ;; Author: John Wiegley <johnw@newartisans.com>
55 ;; Keywords: org data attachment
3333
3434 ;;; Code:
3535
36 (require 'org-macs)
37 (org-assert-version)
38
3639 (require 'cl-lib)
3740 (require 'org)
3841 (require 'ol)
122125
123126 Enabling inheritance for `org-attach' implies two things. First,
124127 that attachment links will look through all parent headings until
125 it finds the linked attachment. Second, that running org-attach
126 inside a node without attachments will make org-attach operate on
128 it finds the linked attachment. Second, that running `org-attach'
129 inside a node without attachments will make `org-attach' operate on
127130 the first parent heading it finds with an attachment.
128131
129132 Selective means to respect the inheritance setting in
135138 (const :tag "Respect org-use-property-inheritance" selective)))
136139
137140 (defcustom org-attach-store-link-p nil
138 "Non-nil means store a link to a file when attaching it."
141 "Non-nil means store a link to a file when attaching it.
142 When t, store the link to original file location.
143 When `file', store link to the attached file location.
144 When `attached', store attach: link to the attached file."
139145 :group 'org-attach
140146 :version "24.1"
141147 :type '(choice
159165 "Translate an UUID ID into a folder-path.
160166 Default format for how Org translates ID properties to a path for
161167 attachments. Useful if ID is generated with UUID."
162 (format "%s/%s"
163 (substring id 0 2)
164 (substring id 2)))
168 (and (< 2 (length id))
169 (format "%s/%s"
170 (substring id 0 2)
171 (substring id 2))))
165172
166173 (defun org-attach-id-ts-folder-format (id)
167174 "Translate an ID based on a timestamp to a folder-path.
168175 Useful way of translation if ID is generated based on ISO8601
169176 timestamp. Splits the attachment folder hierarchy into
170177 year-month, the rest."
171 (format "%s/%s"
172 (substring id 0 6)
173 (substring id 6)))
174
175 (defcustom org-attach-id-to-path-function-list '(org-attach-id-uuid-folder-format
176 org-attach-id-ts-folder-format)
177 "List of functions parsing an ID string into a folder-path.
178 The first function in this list defines the preferred function
179 which will be used when creating new attachment folders. All
180 functions of this list will be tried when looking for existing
181 attachment folders based on ID."
182 :group 'org-attach
183 :package-version '(Org . "9.3")
178 (and (< 6 (length id))
179 (format "%s/%s"
180 (substring id 0 6)
181 (substring id 6))))
182
183 (defun org-attach-id-fallback-folder-format (id)
184 "Return \"__/X/ID\" folder path as a dumb fallback.
185 X is the first character in the ID string.
186
187 This function may be appended to `org-attach-id-path-function-list' to
188 provide a fallback for non-standard ID values that other functions in
189 `org-attach-id-path-function-list' are unable to handle. For example,
190 when the ID is too short for `org-attach-id-ts-folder-format'.
191
192 However, we recommend to define a more specific function spreading
193 entries over multiple folders. This function may create a large
194 number of entries in a single folder, which may cause issues on some
195 systems."
196 (format "__/%s/%s" (substring id 0 1) id))
197
198 (defcustom org-attach-id-to-path-function-list
199 '(org-attach-id-uuid-folder-format
200 org-attach-id-ts-folder-format
201 org-attach-id-fallback-folder-format)
202 "List of functions used to derive attachment path from an ID string.
203 The functions are called with a single ID argument until the return
204 value is an existing folder. If no folder has been created yet for
205 the given ID, then the first non-nil value defines the attachment
206 dir to be created.
207
208 Usually, the ID format passed to the functions is defined by
209 `org-id-method'. It is advised that the first function in the list do
210 not generate all the attachment dirs inside the same parent dir. Some
211 file systems may have performance issues in such scenario.
212
213 Care should be taken when customizing this variable. Previously
214 created attachment folders might not be correctly mapped upon removing
215 functions from the list. Then, Org will not be able to detect the
216 existing attachments."
217 :group 'org-attach
218 :package-version '(Org . "9.6")
184219 :type '(repeat (function :tag "Function with ID as input")))
185220
186221 (defvar org-attach-after-change-hook nil
313348 (concat (mapcar #'caar org-attach-commands)))))
314349 (message msg)
315350 (while (and (setq c (read-char-exclusive))
316 (memq c '(14 16 22 134217846)))
351 (memq c '(?\C-n ?\C-p ?\C-v ?\M-v)))
317352 (org-scroll c t)))
318353 (and (get-buffer "*Org Attach*") (kill-buffer "*Org Attach*"))))
319354 (let ((command (cl-some (lambda (entry)
320355 (and (memq c (nth 0 entry)) (nth 1 entry)))
321356 org-attach-commands)))
322 (if (commandp command t)
323 (call-interactively command)
357 (if (commandp command)
358 (command-execute command)
324359 (error "No such attachment command: %c" c))))))
325360
361 ;;;###autoload
326362 (defun org-attach-dir (&optional create-if-not-exists-p no-fs-check)
327363 "Return the directory associated with the current outline node.
328364 First check for DIR property, then ID property.
334370 Note that this method returns the directory as declared by ID or
335371 DIR even if the directory doesn't exist in the filesystem.
336372
337 If CREATE-IF-NOT-EXIST-P is non-nil, `org-attach-dir-get-create'
373 If CREATE-IF-NOT-EXISTS-P is non-nil, `org-attach-dir-get-create'
338374 is run. If NO-FS-CHECK is non-nil, the function returns the path
339375 to the attachment even if it has not yet been initialized in the
340376 filesystem.
352388 (org-attach-check-absolute-path attach-dir))
353389 ((setq id (org-entry-get nil "ID" org-attach-use-inheritance))
354390 (org-attach-check-absolute-path nil)
355 (setq attach-dir (org-attach-dir-from-id id 'try-all))))
391 (setq attach-dir (org-attach-dir-from-id id 'existing))))
356392 (if no-fs-check
357393 attach-dir
358394 (when (and attach-dir (file-directory-p attach-dir))
373409 (setq answer (read-char-exclusive)))
374410 (cond
375411 ((or (eq org-attach-preferred-new-method 'id) (eq answer ?1))
376 (setq attach-dir (org-attach-dir-from-id (org-id-get nil t))))
412 (let ((id (org-id-get nil t)))
413 (or (setq attach-dir (org-attach-dir-from-id id))
414 (error "Failed to get folder for id %s, \
415 adjust `org-attach-id-to-path-function-list'"
416 id))))
377417 ((or (eq org-attach-preferred-new-method 'dir) (eq answer ?2))
378418 (setq attach-dir (org-attach-set-directory)))
379419 ((eq org-attach-preferred-new-method 'nil)
380 (error "No existing directory. DIR or ID property has to be explicitly created")))))
420 (error "No existing directory. DIR or ID property has to be explicitly created")))))
381421 (unless attach-dir
382422 (error "No attachment directory is associated with the current node"))
383423 (unless (file-directory-p attach-dir)
384424 (make-directory attach-dir t))
385425 attach-dir))
386426
387 (defun org-attach-dir-from-id (id &optional try-all)
427 (defun org-attach-dir-from-id (id &optional existing)
388428 "Return a folder path based on `org-attach-id-dir' and ID.
389 If TRY-ALL is non-nil, try all id-to-path functions in
390 `org-attach-id-to-path-function-list' and return the first path
391 that exist in the filesystem, or the first one if none exist.
392 Otherwise only use the first function in that list."
393 (let ((attach-dir-preferred (expand-file-name
394 (funcall (car org-attach-id-to-path-function-list) id)
395 (expand-file-name org-attach-id-dir))))
396 (if try-all
397 (let ((attach-dir attach-dir-preferred)
398 (fun-list (cdr org-attach-id-to-path-function-list)))
399 (while (and fun-list (not (file-directory-p attach-dir)))
400 (setq attach-dir (expand-file-name
401 (funcall (car fun-list) id)
402 (expand-file-name org-attach-id-dir)))
403 (setq fun-list (cdr fun-list)))
404 (if (file-directory-p attach-dir)
405 attach-dir
406 attach-dir-preferred))
407 attach-dir-preferred)))
429 Try id-to-path functions in `org-attach-id-to-path-function-list'
430 ignoring nils. If EXISTING is non-nil, then return the first path
431 found in the filesystem. Otherwise return the first non-nil value."
432 (let ((fun-list org-attach-id-to-path-function-list)
433 (base-dir (expand-file-name org-attach-id-dir))
434 preferred first)
435 (while (and fun-list
436 (not preferred))
437 (let* ((name (funcall (car fun-list) id))
438 (candidate (and name (expand-file-name name base-dir))))
439 (setq fun-list (cdr fun-list))
440 (when candidate
441 (if (or (not existing) (file-directory-p candidate))
442 (setq preferred candidate)
443 (unless first
444 (setq first candidate))))))
445 (or preferred first)))
408446
409447 (defun org-attach-check-absolute-path (dir)
410448 "Check if we have enough information to root the attachment directory.
482520 (org-attach-tag 'off))
483521
484522 (defun org-attach-url (url)
523 "Attach URL."
485524 (interactive "MURL of the file to attach: \n")
486 (let ((org-attach-method 'url))
525 (let ((org-attach-method 'url)
526 (org-safe-remote-resources ; Assume safety if in an interactive session.
527 (if noninteractive org-safe-remote-resources '(""))))
487528 (org-attach-attach url)))
488529
489530 (defun org-attach-buffer (buffer-name)
502543
503544 (defun org-attach-attach (file &optional visit-dir method)
504545 "Move/copy/link FILE into the attachment directory of the current outline node.
505 If VISIT-DIR is non-nil, visit the directory with dired.
546 If VISIT-DIR is non-nil, visit the directory with `dired'.
506547 METHOD may be `cp', `mv', `ln', `lns' or `url' default taken from
507548 `org-attach-method'."
508549 (interactive
515556 current-prefix-arg
516557 nil))
517558 (setq method (or method org-attach-method))
559 (when (file-directory-p file)
560 (setq file (directory-file-name file)))
518561 (let ((basename (file-name-nondirectory file)))
519562 (let* ((attach-dir (org-attach-dir 'get-create))
520563 (attach-file (expand-file-name basename attach-dir)))
521564 (cond
522565 ((eq method 'mv) (rename-file file attach-file))
523 ((eq method 'cp) (copy-file file attach-file))
566 ((eq method 'cp)
567 (if (file-directory-p file)
568 (copy-directory file attach-file nil nil t)
569 (copy-file file attach-file)))
524570 ((eq method 'ln) (add-name-to-file file attach-file))
525 ((eq method 'lns) (make-symbolic-link file attach-file))
526 ((eq method 'url) (url-copy-file file attach-file)))
571 ((eq method 'lns) (make-symbolic-link file attach-file 1))
572 ((eq method 'url)
573 (if (org--should-fetch-remote-resource-p file)
574 (url-copy-file file attach-file)
575 (error "The remote resource %S is considered unsafe, and will not be downloaded."
576 file))))
527577 (run-hook-with-args 'org-attach-after-change-hook attach-dir)
528578 (org-attach-tag)
529579 (cond ((eq org-attach-store-link-p 'attached)
573623 (find-file (expand-file-name file attach-dir))
574624 (message "New attachment %s" file)))
575625
576 (defun org-attach-delete-one (&optional file)
577 "Delete a single attachment."
626 (defun org-attach-delete-one (&optional attachment)
627 "Delete a single ATTACHMENT."
578628 (interactive)
579629 (let* ((attach-dir (org-attach-dir))
580630 (files (org-attach-file-list attach-dir))
581 (file (or file
631 (attachment (or attachment
582632 (completing-read
583633 "Delete attachment: "
584634 (mapcar (lambda (f)
585635 (list (file-name-nondirectory f)))
586636 files)))))
587 (setq file (expand-file-name file attach-dir))
588 (unless (file-exists-p file)
589 (error "No such attachment: %s" file))
590 (delete-file file)
637 (setq attachment (expand-file-name attachment attach-dir))
638 (unless (file-exists-p attachment)
639 (error "No such attachment: %s" attachment))
640 (delete-file attachment)
591641 (run-hook-with-args 'org-attach-after-change-hook attach-dir)))
592642
593643 (defun org-attach-delete-all (&optional force)
594644 "Delete all attachments from the current outline node.
595645 This actually deletes the entire attachment directory.
596 A safer way is to open the directory in dired and delete from there.
646 A safer way is to open the directory in `dired' and delete from there.
597647
598648 With prefix argument FORCE, directory will be recursively deleted
599649 with no prompts."
628678 t))
629679 (delete-directory attach-dir))))))
630680
631 (defun org-attach-file-list (dir)
632 "Return a list of files in the attachment directory.
681 (defun org-attach-file-list (directory)
682 "Return a list of files in the attachment DIRECTORY.
633683 This ignores files ending in \"~\"."
634684 (delq nil
635685 (mapcar (lambda (x) (if (string-match "^\\.\\.?\\'" x) nil x))
636 (directory-files dir nil "[^~]\\'"))))
686 (directory-files directory nil "[^~]\\'"))))
637687
638688 (defun org-attach-reveal ()
639689 "Show the attachment directory of the current outline node.
644694 (org-open-file (org-attach-dir-get-create)))
645695
646696 (defun org-attach-reveal-in-emacs ()
647 "Show the attachment directory of the current outline node in dired.
697 "Show the attachment directory of the current outline node in `dired'.
648698 Will create an attachment and folder if it doesn't exist yet.
649699 Respects `org-attach-preferred-new-method'."
650700 (interactive)
748798
749799 ;;;###autoload
750800 (defun org-attach-dired-to-subtree (files)
751 "Attach FILES marked or current file in dired to subtree in other window.
801 "Attach FILES marked or current file in `dired' to subtree in other window.
752802 Takes the method given in `org-attach-method' for the attach action.
753 Precondition: Point must be in a dired buffer.
803 Precondition: Point must be in a `dired' buffer.
754804 Idea taken from `gnus-dired-attach'."
755805 (interactive
756806 (list (dired-get-marked-files)))
757807 (unless (eq major-mode 'dired-mode)
758 (user-error "This command must be triggered in a dired buffer"))
808 (user-error "This command must be triggered in a `dired' buffer"))
759809 (let ((start-win (selected-window))
760810 (other-win
761811 (get-window-with-predicate
775825
776826
777827 (add-hook 'org-archive-hook 'org-attach-archive-delete-maybe)
778 (add-hook 'org-export-before-parsing-hook 'org-attach-expand-links)
828 (add-hook 'org-export-before-parsing-functions 'org-attach-expand-links)
779829
780830 (provide 'org-attach)
781831
00 ;;; org-capture.el --- Fast note taking in Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
4646
4747 ;;; Code:
4848
49 (require 'org-macs)
50 (org-assert-version)
51
4952 (require 'cl-lib)
5053 (require 'org)
5154 (require 'org-refile)
5659 (declare-function org-datetree-find-date-create "org-datetree" (date &optional keep-restriction))
5760 (declare-function org-datetree-find-month-create (d &optional keep-restriction))
5861 (declare-function org-decrypt-entry "org-crypt" ())
59 (declare-function org-element-at-point "org-element" ())
62 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
6063 (declare-function org-element-lineage "org-element" (datum &optional types with-self))
6164 (declare-function org-element-property "org-element" (property element))
6265 (declare-function org-encrypt-entry "org-crypt" ())
8285 (defvar org-table-hlines)
8386
8487 (defvar org-capture-clock-was-started nil
85 "Internal flag, noting if the clock was started.")
88 "Internal flag, keeping marker to the started clock.")
8689
8790 (defvar org-capture-last-stored-marker (make-marker)
8891 "Marker pointing to the entry most recently stored with `org-capture'.")
293296
294297 :no-save Do not save the target file after finishing the capture.
295298
299 :hook A nullary function or list of nullary functions run before
300 `org-capture-mode-hook' when the template is selected.
301
302 :prepare-finalize A nullary function or list of nullary functions run before
303 `org-capture-prepare-finalize-hook'
304 when the template is selected.
305
306 :before-finalize A nullary function or list of nullary functions run before
307 `org-capture-before-finalize-hook'
308 when the template is selected.
309
310 :after-finalize A nullary function or list of nullary functions run before
311 `org-capture-after-finalize-hook'
312 when the template is selected.
313
296314 The template defines the text to be inserted. Often this is an
297315 Org mode entry (so the first line should start with a star) that
298316 will be filed as a child of the target headline. It can also be
308326 introduced with %[pathname] are expanded this way.
309327 Since this happens after expanding non-interactive
310328 %-escapes, those can be used to fill the expression.
329 The evaluation happens with Org mode set as major mode
330 in a temporary buffer.
311331 %<...> The result of `format-time-string' on the ... format
312332 specification.
313333 %t Time stamp, date only. The time stamp is the current
372392 When you need to insert a literal percent sign in the template,
373393 you can escape ambiguous cases with a backward slash, e.g., \\%i."
374394 :group 'org-capture
375 :package-version '(Org . "9.5")
376 :set (lambda (s v) (set s (org-capture-upgrade-templates v)))
395 :package-version '(Org . "9.6")
396 :set (lambda (s v) (set-default-toplevel-value s (org-capture-upgrade-templates v)))
377397 :type
378398 (let ((file-variants '(choice :tag "Filename "
379399 (file :tag "Literal")
557577 this template to be accessible only from `message-mode' buffers,
558578 use this:
559579
560 \\='((\"c\" ((in-mode . \"message-mode\"))))
580 (setq org-capture-templates-contexts
581 \\='((\"c\" ((in-mode . \"message-mode\")))))
561582
562583 Here are the available contexts definitions:
563584
575596 You can also bind a key to another capture template depending on
576597 contextual rules.
577598
578 \\='((\"c\" \"d\" ((in-mode . \"message-mode\"))))
599 (setq org-capture-templates-contexts
600 \\='((\"c\" \"d\" ((in-mode . \"message-mode\")))))
579601
580602 Here it means: in `message-mode buffers', use \"c\" as the
581603 key for the capture template otherwise associated with \"d\".
711733 (org-capture-put :interrupted-clock
712734 (copy-marker org-clock-marker)))
713735 (org-clock-in)
714 (setq-local org-capture-clock-was-started t))
736 (setq-local org-capture-clock-was-started
737 (copy-marker org-clock-marker)))
715738 (error "Could not start the clock in this capture buffer")))
716739 (when (org-capture-get :immediate-finish)
717740 (org-capture-finalize))))))))
732755 (format "* Template function %S not found" f)))
733756 (_ "* Invalid capture template"))))
734757
758 (defun org-capture--run-template-functions (keyword &optional local)
759 "Run functions associated with KEYWORD on template's plist.
760 For valid values of KEYWORD see `org-capture-templates'.
761 If LOCAL is non-nil use the buffer-local value of `org-capture-plist'."
762 ;; Used in place of `run-hooks' because these functions have no associated symbol.
763 ;; They are stored directly on `org-capture-plist'.
764 (let ((value (org-capture-get keyword local)))
765 (if (functionp value)
766 (funcall value)
767 (mapc #'funcall value))))
768
735769 (defun org-capture-finalize (&optional stay-with-capture)
736770 "Finalize the capture process.
737771 With prefix argument STAY-WITH-CAPTURE, jump to the location of the
743777 (buffer-base-buffer (current-buffer)))
744778 (error "This does not seem to be a capture buffer for Org mode"))
745779
780 (org-capture--run-template-functions :prepare-finalize 'local)
746781 (run-hooks 'org-capture-prepare-finalize-hook)
747782
748783 ;; Update `org-capture-plist' with the buffer-local value. Since
752787
753788 ;; Did we start the clock in this capture buffer?
754789 (when (and org-capture-clock-was-started
755 org-clock-marker
756 (eq (marker-buffer org-clock-marker) (buffer-base-buffer))
757 (>= org-clock-marker (point-min))
758 (< org-clock-marker (point-max)))
790 (equal org-clock-marker org-capture-clock-was-started))
759791 ;; Looks like the clock we started is still running.
760792 (if org-capture-clock-keep
761793 ;; User may have completed clocked heading from the template.
815847 ;; the indirect buffer has been killed.
816848 (org-capture-store-last-position)
817849
850 (org-capture--run-template-functions :before-finalize 'local)
818851 ;; Run the hook
819852 (run-hooks 'org-capture-before-finalize-hook))
820853
863896 ;; Restore the window configuration before capture
864897 (set-window-configuration return-wconf))
865898
899 ;; Do not use the local arg to `org-capture--run-template-functions' here.
900 ;; The buffer-local value has been stored on `org-capture-plist'.
901 (org-capture--run-template-functions :after-finalize)
866902 (run-hooks 'org-capture-after-finalize-hook)
867903 ;; Special cases
868904 (cond
10491085 prompt-time
10501086 ;; Use 00:00 when no time is given for another
10511087 ;; date than today?
1052 (apply #'encode-time 0 0
1053 org-extend-today-until
1054 (cl-cdddr (decode-time prompt-time)))))
1088 (org-encode-time
1089 (apply #'list
1090 0 0 org-extend-today-until
1091 (cl-cdddr (decode-time prompt-time))))))
10551092 (time-to-days prompt-time)))
10561093 (t
10571094 ;; Current date, possibly corrected for late night
11281165 (org-switch-to-buffer-other-window
11291166 (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
11301167 (widen)
1131 (org-show-all)
1168 (org-fold-show-all)
11321169 (goto-char (org-capture-get :pos))
11331170 (setq-local outline-level 'org-outline-level)
11341171 (pcase (org-capture-get :type)
11381175 (`item (org-capture-place-item))
11391176 (`checkitem (org-capture-place-item)))
11401177 (setq-local org-capture-current-plist org-capture-plist)
1178 (org-capture--run-template-functions :hook 'local)
11411179 (org-capture-mode 1))
11421180
11431181 (defun org-capture-place-entry ()
11701208 (goto-char (point-min))
11711209 (unless (org-at-heading-p) (outline-next-heading)))
11721210 ;; Otherwise, insert as a top-level entry at the end of the file.
1173 (t (goto-char (point-max))))
1174 (let ((origin (point)))
1211 (t (goto-char (point-max))
1212 ;; Make sure that last point is not folded.
1213 (org-fold-core-cycle-over-indirect-buffers
1214 (org-fold-region (max 1 (1- (point-max))) (point-max) nil))))
1215 (let ((origin (point-marker)))
11751216 (unless (bolp) (insert "\n"))
11761217 (org-capture-empty-lines-before)
11771218 (let ((beg (point)))
12361277 (point))
12371278 beg)))))))
12381279 ;; Insert template.
1239 (let ((origin (point)))
1280 (let ((origin (point-marker)))
12401281 (unless (bolp) (insert "\n"))
12411282 ;; When a new list is created, always obey to `:empty-lines' and
12421283 ;; friends.
12631304 (when item
12641305 (let ((i (save-excursion
12651306 (goto-char (org-element-property :post-affiliated item))
1266 (current-indentation))))
1307 (org-current-text-indentation))))
12671308 (save-excursion
12681309 (goto-char beg)
12691310 (save-excursion
13371378 ;; No table found. Create it with an empty header.
13381379 (goto-char end)
13391380 (unless (bolp) (insert "\n"))
1340 (let ((origin (point)))
1381 (let ((origin (point-marker)))
13411382 (insert "| |\n|---|\n")
13421383 (narrow-to-region origin (point))))
13431384 ;; In the current table, find the appropriate location for TEXT.
13661407 (t
13671408 (goto-char (org-table-end))))
13681409 ;; Insert text and position point according to template.
1369 (let ((origin (point)))
1410 (let ((origin (point-marker)))
13701411 (unless (bolp) (insert "\n"))
13711412 (let ((beg (point))
13721413 (end (save-excursion
13981439 (t
13991440 ;; Beginning or end of file.
14001441 (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))))
1401 (let ((origin (point)))
1442 (let ((origin (point-marker)))
14021443 (unless (bolp) (insert "\n"))
14031444 (org-capture-empty-lines-before)
14041445 (org-capture-position-for-last-stored (point))
14461487 (if (org-at-table-p)
14471488 (save-excursion
14481489 (org-table-goto-line (nth 1 where))
1449 (point-at-bol))
1490 (line-beginning-position))
14501491 (point))))))
14511492 (with-current-buffer (buffer-base-buffer (current-buffer))
14521493 (org-with-point-at pos
14531494 (when org-capture-bookmark
14541495 (let ((bookmark (plist-get org-bookmark-names-plist :last-capture)))
1455 (when bookmark (with-demoted-errors (bookmark-set bookmark)))))
1496 (when bookmark (with-demoted-errors "Bookmark set error: %S"
1497 (bookmark-set bookmark)))))
14561498 (move-marker org-capture-last-stored-marker (point))))))
14571499
14581500 (defun org-capture-narrow (beg end)
15671609 "Fill a TEMPLATE and return the filled template as a string.
15681610 The template may still contain \"%?\" for cursor positioning.
15691611 INITIAL content and/or ANNOTATION may be specified, but will be overridden
1570 by their respective `org-store-link-plist' properties if present."
1612 by their respective `org-store-link-plist' properties if present.
1613
1614 Expansion occurs in a temporary Org mode buffer."
15711615 (let* ((template (or template (org-capture-get :template)))
15721616 (buffer (org-capture-get :buffer))
15731617 (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
15741618 (time (let* ((c (or (org-capture-get :default-time) (current-time)))
15751619 (d (decode-time c)))
15761620 (if (< (nth 2 d) org-extend-today-until)
1577 (encode-time 0 59 23 (1- (nth 3 d)) (nth 4 d) (nth 5 d))
1621 (org-encode-time 0 59 23 (1- (nth 3 d)) (nth 4 d) (nth 5 d))
15781622 c)))
15791623 (v-t (format-time-string (org-time-stamp-format nil) time))
15801624 (v-T (format-time-string (org-time-stamp-format t) time))
16401684 (setq buffer-file-name nil)
16411685 (setq mark-active nil)
16421686 (insert template)
1687 (org-mode)
16431688 (goto-char (point-min))
16441689 ;; %[] insert contents of a file.
16451690 (save-excursion
16541699 (condition-case error
16551700 (insert-file-contents filename)
16561701 (error
1657 (insert (format "%%![couldn not insert %s: %s]"
1702 (insert (format "%%![could not insert %s: %s]"
16581703 filename
16591704 error))))))))
16601705 ;; Mark %() embedded elisp for later evaluation.
18141859 ;; Load history list for current prompt.
18151860 (setq org-capture--prompt-history
18161861 (gethash prompt org-capture--prompt-history-table))
1817 (push (org-completing-read
1818 (concat (or prompt "Enter string")
1819 (and default (format " [%s]" default))
1820 ": ")
1862 (push (org-completing-read
1863 (org-format-prompt (or prompt "Enter string") default)
18211864 completions
18221865 nil nil nil 'org-capture--prompt-history default)
18231866 strings)
00 ;;; org-clock.el --- The time clocking code for Org mode -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2727
2828 ;;; Code:
2929
30 (require 'org-macs)
31 (org-assert-version)
32
3033 (require 'cl-lib)
3134 (require 'org)
3235
3437 (declare-function notifications-notify "notifications" (&rest params))
3538 (declare-function org-element-property "org-element" (property element))
3639 (declare-function org-element-type "org-element" (element))
40 (declare-function org-element--cache-active-p "org-element" ())
41 (defvar org-element-use-cache)
3742 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
3843 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3944 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4954 (defvar org-frame-title-format-backup nil)
5055 (defvar org-state)
5156 (defvar org-link-bracket-re)
52 (defvar org-time-stamp-formats)
5357
5458 (defgroup org-clock nil
5559 "Options concerning clocking working time in Org mode."
218222 (const :tag "Clock and history" t)
219223 (const :tag "No persistence" nil)))
220224
221 (defcustom org-clock-persist-file (convert-standard-filename
222 (concat user-emacs-directory "org-clock-save.el"))
225 (defcustom org-clock-persist-file (locate-user-emacs-file "org-clock-save.el")
223226 "File to save clock data to."
224227 :group 'org-clock
225228 :type 'string)
321324 :link nil
322325 :narrow '40!
323326 :indent t
327 :filetitle nil
324328 :hidefiles nil
325329 :formula nil
326330 :timestamp nil
329333 :formatter nil)
330334 "Default properties for clock tables."
331335 :group 'org-clock
332 :version "24.1"
336 :package-version '(Org . "9.6")
333337 :type 'plist)
334338
335339 (defcustom org-clock-clocktable-formatter 'org-clocktable-write-default
428432 or `both', clocking in will replace `frame-title-format' with
429433 this value. Clocking out will restore `frame-title-format'.
430434
431 `org-frame-title-string' is a format string using the same
432 specifications than `frame-title-format', which see."
435 This uses the same format as `frame-title-format', which see."
433436 :version "24.1"
434437 :group 'org-clock
435438 :type 'sexp)
440443 you can do \"~$ sudo apt-get install xprintidle\" if you are using
441444 a Debian-based distribution.
442445
443 Alternatively, can find x11idle.c in the org-contrib repository at
444 https://git.sr.ht/~bzg/org-contrib"
446 Alternatively, can find x11idle.c in
447 https://orgmode.org/worg/code/scripts/x11idle.c"
445448 :group 'org-clock
446449 :version "24.4"
447450 :package-version '(Org . "8.0")
490493 (if value
491494 (add-hook 'kill-emacs-query-functions #'org-clock-kill-emacs-query)
492495 (remove-hook 'kill-emacs-query-functions #'org-clock-kill-emacs-query))
493 (set symbol value))
496 (set-default-toplevel-value symbol value))
494497 :type 'boolean
495498 :package-version '(Org . "9.5"))
496499
658661 (if (< i 10)
659662 (+ i ?0)
660663 (+ i (- ?A 10))) m))
661 (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
662664 (push s sel-list)))
663665 (run-hooks 'org-clock-before-select-task-hook)
664666 (goto-char (point-min))
696698 org-odd-levels-only)
697699 (length prefix))))))
698700 (when (and cat task)
699 (insert (format "[%c] %-12s %s\n" i cat task))
701 (if (string-match-p "[[:print:]]" (make-string 1 i))
702 (insert (format "[%c] %-12s %s\n" i cat task))
703 ;; Avoid non-printable characters.
704 (insert (format "[N/A] %-12s %s\n" cat task)))
700705 (cons i marker)))))
701706
702707 (defvar org-clock-task-overrun nil
720725 'org-mode-line-clock-overrun
721726 'org-mode-line-clock)))
722727 (effort-str (org-duration-from-minutes effort-in-minutes)))
723 (format (propertize " [%s/%s] (%s)" 'face 'org-mode-line-clock)
728 (format (propertize "[%s/%s] (%s) " 'face 'org-mode-line-clock)
724729 work-done-str effort-str org-clock-heading))
725 (format (propertize " [%s] (%s)" 'face 'org-mode-line-clock)
730 (format (propertize "[%s] (%s) " 'face 'org-mode-line-clock)
726731 (org-duration-from-minutes clocked-time)
727732 org-clock-heading))))
728733
769774 previous clocking intervals."
770775 (let ((currently-clocked-time
771776 (floor (org-time-convert-to-integer
772 (org-time-since org-clock-start-time))
777 (time-since org-clock-start-time))
773778 60)))
774779 (+ currently-clocked-time (or org-clock-total-time 0))))
775780
9991004 (org-clock-clock-out clock fail-quietly))
10001005 ((org-is-active-clock clock) nil)
10011006 (t (org-clock-clock-in clock t))))
1002 ((pred (org-time-less-p nil))
1007 ((pred (time-less-p nil))
10031008 (error "RESOLVE-TO must refer to a time in the past"))
10041009 (_
10051010 (when restart (error "RESTART is not valid here"))
10321037 (let ((element (org-element-at-point)))
10331038 (when (eq (org-element-type element) 'drawer)
10341039 (when (> (org-element-property :end element) (car clock))
1035 (org-hide-drawer-toggle 'off nil element))
1040 (org-fold-hide-drawer-toggle 'off nil element))
10361041 (throw 'exit nil)))))))))))
10371042
10381043 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
10961101 ?j ?J ?i ?q ?t ?T)))
10971102 (or (ding) t)))
10981103 (setq char-pressed
1099 (read-char (concat (funcall prompt-fn clock)
1100 " [jkKtTgGSscCiq]? ")
1101 nil 45)))
1104 (read-char-exclusive (concat (funcall prompt-fn clock)
1105 " [jkKtTgGSscCiq]? ")
1106 nil 45)))
11021107 (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
11031108 (default
1104 (floor (org-time-convert-to-integer (org-time-since last-valid))
1109 (floor (org-time-convert-to-integer (time-since last-valid))
11051110 60))
11061111 (keep
11071112 (or (and (memq ch '(?k ?K))
1108 (read-number "Keep how many minutes? " default))
1113 (read-number "Keep how many minutes: " default))
11091114 (and (memq ch '(?t ?T))
11101115 (floor
11111116 (/ (float-time
1112 (org-time-subtract (org-read-date t t) last-valid))
1117 (time-subtract (org-read-date t t) last-valid))
11131118 60)))))
11141119 (gotback
11151120 (and (memq ch '(?g ?G))
1116 (read-number "Got back how many minutes ago? " default)))
1121 (read-number "Got back how many minutes ago: " default)))
11171122 (subtractp (memq ch '(?s ?S)))
1118 (barely-started-p (org-time-less-p
1119 (org-time-subtract last-valid (cdr clock))
1123 (barely-started-p (time-less-p
1124 (time-subtract last-valid (cdr clock))
11201125 45))
11211126 (start-over (and subtractp barely-started-p)))
11221127 (cond
11431148 (and gotback (= gotback default)))
11441149 'now)
11451150 (keep
1146 (org-time-add last-valid (* 60 keep)))
1151 (time-add last-valid (* 60 keep)))
11471152 (gotback
1148 (org-time-since (* 60 gotback)))
1153 (time-since (* 60 gotback)))
11491154 (t
11501155 (error "Unexpected, please report this as a bug")))
11511156 (and gotback last-valid)
11751180 (format
11761181 "Dangling clock started %d mins ago"
11771182 (floor (org-time-convert-to-integer
1178 (org-time-since (cdr clock)))
1183 (time-since (cdr clock)))
11791184 60))))
11801185 (or last-valid
11811186 (cdr clock)))))))))))
11921197 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
11931198
11941199 (defvar org-x11idle-exists-p
1195 ;; Check that x11idle exists
1196 (and (eq window-system 'x)
1200 ;; Check that x11idle exists. But don't do that on DOS/Windows,
1201 ;; since the command definitely does NOT exist there, and invoking
1202 ;; COMMAND.COM on MS-Windows is a bad idea -- it hangs.
1203 (and (null (memq system-type '(windows-nt ms-dos)))
11971204 (eq 0 (call-process-shell-command
11981205 (format "command -v %s" org-clock-x11idle-program-name)))
11991206 ;; Check that x11idle can retrieve the idle time
12261233 org-clock-marker (marker-buffer org-clock-marker))
12271234 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
12281235 (org-clock-user-idle-start
1229 (org-time-since org-clock-user-idle-seconds))
1236 (time-since org-clock-user-idle-seconds))
12301237 (org-clock-resolving-clocks-due-to-idleness t))
1231 (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
1238 (when (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
1239 (cancel-timer org-clock-idle-timer)
1240 (setq org-clock-idle-timer nil)
12321241 (org-clock-resolve
12331242 (cons org-clock-marker
12341243 org-clock-start-time)
12371246 (/ (float-time
12381247 (time-since org-clock-user-idle-start))
12391248 60)))
1240 org-clock-user-idle-start)))))
1249 org-clock-user-idle-start)
1250 (when (and (org-clocking-p) (not org-clock-idle-timer))
1251 (setq org-clock-idle-timer
1252 (run-with-timer 60 60 #'org-resolve-clocks-if-idle)))))))
12411253
12421254 (defvar org-clock-current-task nil "Task currently clocked in.")
12431255 (defvar org-clock-out-time nil) ; store the time of the last clock-out
12641276 the default behavior."
12651277 (interactive "P")
12661278 (setq org-clock-notification-was-shown nil)
1267 (org-refresh-effort-properties)
1279 (unless org-element-use-cache
1280 (org-refresh-effort-properties))
12681281 (catch 'abort
12691282 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
12701283 (org-clocking-p)))
13181331 ;; Clock in at which position?
13191332 (setq target-pos
13201333 (if (and (eobp) (not (org-at-heading-p)))
1321 (point-at-bol 0)
1334 (org-with-wide-buffer (line-beginning-position 0))
13221335 (point)))
13231336 (save-excursion
13241337 (when (and selected-task (marker-buffer selected-task))
13421355 (when newstate (org-todo newstate))))
13431356 ((and org-clock-in-switch-to-state
13441357 (not (looking-at (concat org-outline-regexp "[ \t]*"
1345 org-clock-in-switch-to-state
1346 "\\>"))))
1358 org-clock-in-switch-to-state
1359 "\\>"))))
13471360 (org-todo org-clock-in-switch-to-state)))
13481361 (setq org-clock-heading (org-clock--mode-line-heading))
13491362 (org-clock-find-position org-clock-in-resume)
13691382 (sit-for 2)
13701383 (throw 'abort nil))
13711384 (t
1372 (insert-before-markers "\n")
1385 (insert-before-markers-and-inherit "\n")
13731386 (backward-char 1)
13741387 (when (and (save-excursion
13751388 (end-of-line 0)
13761389 (org-in-item-p)))
13771390 (beginning-of-line 1)
13781391 (indent-line-to (max 0 (- (current-indentation) 2))))
1379 (insert org-clock-string " ")
1392 (insert-and-inherit org-clock-string " ")
13801393 (setq org-clock-effort (org-entry-get (point) org-effort-property))
13811394 (setq org-clock-total-time (org-clock-sum-current-item
13821395 (org-clock-get-sum-start)))
13871400 (format
13881401 "You stopped another clock %d mins ago; start this one from then? "
13891402 (/ (org-time-convert-to-integer
1390 (org-time-subtract
1403 (time-subtract
13911404 (org-current-time org-clock-rounding-minutes t)
13921405 leftover))
13931406 60)))
15161529 (day (nth 3 dt)))
15171530 (if (< hour org-extend-today-until) (setf (nth 3 dt) (1- day)))
15181531 (setf (nth 2 dt) org-extend-today-until)
1519 (apply #'encode-time 0 0 (nthcdr 2 dt))))
1532 (org-encode-time (apply #'list 0 0 (nthcdr 2 dt)))))
15201533 ((or (equal cmt "all")
15211534 (and (or (not cmt) (equal cmt "auto"))
15221535 (not lr)))
15771590 count (1+ count))))))
15781591 (cond
15791592 ((null positions)
1580 ;; Skip planning line and property drawer, if any.
1581 (org-end-of-meta-data)
1582 (unless (bolp) (insert "\n"))
1583 ;; Create a new drawer if necessary.
1584 (when (and org-clock-into-drawer
1585 (or (not (wholenump org-clock-into-drawer))
1586 (< org-clock-into-drawer 2)))
1587 (let ((beg (point)))
1588 (insert ":" drawer ":\n:END:\n")
1589 (org-indent-region beg (point))
1590 (org-flag-region
1591 (line-end-position -1) (1- (point)) t 'outline)
1592 (forward-line -1))))
1593 (org-fold-core-ignore-modifications
1594 ;; Skip planning line and property drawer, if any.
1595 (org-end-of-meta-data)
1596 (unless (bolp) (insert-and-inherit "\n"))
1597 ;; Create a new drawer if necessary.
1598 (when (and org-clock-into-drawer
1599 (or (not (wholenump org-clock-into-drawer))
1600 (< org-clock-into-drawer 2)))
1601 (let ((beg (point)))
1602 (insert-and-inherit ":" drawer ":\n:END:\n")
1603 (org-indent-region beg (point))
1604 (if (eq org-fold-core-style 'text-properties)
1605 (org-fold-region
1606 (line-end-position -1) (1- (point)) t 'drawer)
1607 (org-fold-region
1608 (line-end-position -1) (1- (point)) t 'outline))
1609 (forward-line -1)))))
15931610 ;; When a clock drawer needs to be created because of the
15941611 ;; number of clock items or simply if it is missing, collect
15951612 ;; all clocks in the section and wrap them within the drawer.
15981615 drawer)
15991616 ;; Skip planning line and property drawer, if any.
16001617 (org-end-of-meta-data)
1601 (let ((beg (point)))
1602 (insert
1603 (mapconcat
1604 (lambda (p)
1605 (save-excursion
1606 (goto-char p)
1607 (org-trim (delete-and-extract-region
1608 (save-excursion (skip-chars-backward " \r\t\n")
1609 (line-beginning-position 2))
1610 (line-beginning-position 2)))))
1611 positions "\n")
1612 "\n:END:\n")
1613 (let ((end (point-marker)))
1614 (goto-char beg)
1615 (save-excursion (insert ":" drawer ":\n"))
1616 (org-flag-region (line-end-position) (1- end) t 'outline)
1617 (org-indent-region (point) end)
1618 (forward-line)
1619 (unless org-log-states-order-reversed
1620 (goto-char end)
1621 (beginning-of-line -1))
1622 (set-marker end nil))))
1618 (org-fold-core-ignore-modifications
1619 (let ((beg (point)))
1620 (insert-and-inherit
1621 (mapconcat
1622 (lambda (p)
1623 (save-excursion
1624 (goto-char p)
1625 (org-trim (delete-and-extract-region
1626 (save-excursion (skip-chars-backward " \r\t\n")
1627 (line-beginning-position 2))
1628 (line-beginning-position 2)))))
1629 positions "\n")
1630 "\n:END:\n")
1631 (let ((end (point-marker)))
1632 (goto-char beg)
1633 (save-excursion (insert-and-inherit ":" drawer ":\n"))
1634 (org-fold-region (line-end-position) (1- end) t 'outline)
1635 (org-indent-region (point) end)
1636 (forward-line)
1637 (unless org-log-states-order-reversed
1638 (goto-char end)
1639 (beginning-of-line -1))
1640 (set-marker end nil)))))
16231641 (org-log-states-order-reversed (goto-char (car (last positions))))
16241642 (t (goto-char (car positions))))))))
16251643
16671685 (setq ts (match-string 2))
16681686 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
16691687 (goto-char (match-end 0))
1670 (delete-region (point) (point-at-eol))
1671 (insert "--")
1672 (setq te (org-insert-time-stamp (or at-time now) 'with-hm 'inactive))
1673 (setq s (org-time-convert-to-integer
1674 (time-subtract
1675 (org-time-string-to-time te)
1676 (org-time-string-to-time ts)))
1677 h (floor s 3600)
1678 m (floor (mod s 3600) 60))
1679 (insert " => " (format "%2d:%02d" h m))
1680 (move-marker org-clock-marker nil)
1681 (move-marker org-clock-hd-marker nil)
1682 ;; Possibly remove zero time clocks.
1683 (when (and org-clock-out-remove-zero-time-clocks
1684 (= 0 h m))
1685 (setq remove t)
1686 (delete-region (line-beginning-position)
1687 (line-beginning-position 2)))
1688 (org-clock-remove-empty-clock-drawer)
1688 (delete-region (point) (line-end-position))
1689 (org-fold-core-ignore-modifications
1690 (insert-and-inherit "--")
1691 (setq te (org-insert-time-stamp (or at-time now) 'with-hm 'inactive))
1692 (setq s (org-time-convert-to-integer
1693 (time-subtract
1694 (org-time-string-to-time te)
1695 (org-time-string-to-time ts)))
1696 h (floor s 3600)
1697 m (floor (mod s 3600) 60))
1698 (insert-and-inherit " => " (format "%2d:%02d" h m))
1699 (move-marker org-clock-marker nil)
1700 (move-marker org-clock-hd-marker nil)
1701 ;; Possibly remove zero time clocks.
1702 (when (and org-clock-out-remove-zero-time-clocks
1703 (= 0 h m))
1704 (setq remove t)
1705 (delete-region (line-beginning-position)
1706 (line-beginning-position 2)))
1707 (org-clock-remove-empty-clock-drawer))
16891708 (when org-clock-mode-line-timer
16901709 (cancel-timer org-clock-mode-line-timer)
16911710 (setq org-clock-mode-line-timer nil))
17071726 (match-string 2))))
17081727 (when newstate (org-todo newstate))))
17091728 ((and org-clock-out-switch-to-state
1710 (not (looking-at (concat org-outline-regexp "[ \t]*"
1711 org-clock-out-switch-to-state
1712 "\\>"))))
1729 (not (looking-at
1730 (concat
1731 org-outline-regexp "[ \t]*"
1732 org-clock-out-switch-to-state
1733 "\\>"))))
17131734 (org-todo org-clock-out-switch-to-state))))))
17141735 (force-mode-line-update)
17151736 (message (if remove
17461767 (org-clock-timestamps-change 'up n))
17471768
17481769 (defun org-clock-timestamps-down (&optional n)
1749 "Increase CLOCK timestamps at cursor.
1770 "Decrease CLOCK timestamps at cursor.
17501771 Optional argument N tells to change by that many units."
17511772 (interactive "P")
17521773 (org-clock-timestamps-change 'down n))
17761797 (begts (if updatets1 begts1 begts2)))
17771798 (setq tdiff
17781799 (time-subtract
1779 (org-time-string-to-time org-last-changed-timestamp)
1800 (org-time-string-to-time
1801 (save-excursion
1802 (goto-char (if updatets1 begts2 begts1))
1803 (looking-at org-ts-regexp3)
1804 (match-string 0)))
17801805 (org-time-string-to-time ts)))
1781 (save-excursion
1782 (goto-char begts)
1783 (org-timestamp-change
1784 (round (/ (float-time tdiff)
1785 (pcase timestamp?
1786 (`minute 60)
1787 (`hour 3600)
1788 (`day (* 24 3600))
1789 (`month (* 24 3600 31))
1790 (`year (* 24 3600 365.2)))))
1791 timestamp? 'updown)))))))
1806 ;; `save-excursion' won't work because
1807 ;; `org-timestamp-change' deletes and re-inserts the
1808 ;; timestamp.
1809 (let ((origin (point)))
1810 (save-excursion
1811 (goto-char begts)
1812 (org-timestamp-change
1813 (round (/ (float-time tdiff)
1814 (pcase timestamp?
1815 (`minute 60)
1816 (`hour 3600)
1817 (`day (* 24 3600))
1818 (`month (* 24 3600 31))
1819 (`year (* 24 3600 365.2)))))
1820 timestamp? 'updown))
1821 ;; Move back to initial position, but never beyond updated
1822 ;; clock.
1823 (unless (< (point) origin)
1824 (goto-char origin))))))))
17921825
17931826 ;;;###autoload
17941827 (defun org-clock-cancel ()
18051838 (goto-char org-clock-marker)
18061839 (if (looking-back (concat "^[ \t]*" org-clock-string ".*")
18071840 (line-beginning-position))
1808 (progn (delete-region (1- (point-at-bol)) (point-at-eol))
1841 (progn (delete-region (1- (line-beginning-position)) (line-end-position))
18091842 (org-remove-empty-drawer-at (point)))
18101843 (message "Clock gone, cancel the timer anyway")
18111844 (sit-for 2)))
18391872 (pop-to-buffer-same-window (marker-buffer m))
18401873 (if (or (< m (point-min)) (> m (point-max))) (widen))
18411874 (goto-char m)
1842 (org-show-entry)
1875 (org-fold-show-entry)
18431876 (org-back-to-heading t)
18441877 (recenter org-clock-goto-before-context)
1845 (org-reveal)
1878 (org-fold-reveal)
18461879 (if recent
18471880 (message "No running clock, this is the most recently clocked task"))
18481881 (run-hooks 'org-clock-goto-hook)))
19001933 (save-excursion
19011934 (goto-char (point-max))
19021935 (while (re-search-backward re nil t)
1903 (cond
1904 ((match-end 2)
1905 ;; Two time stamps.
1906 (let* ((ts (float-time
1907 (apply #'encode-time
1908 (save-match-data
1909 (org-parse-time-string (match-string 2))))))
1910 (te (float-time
1911 (apply #'encode-time
1912 (org-parse-time-string (match-string 3)))))
1913 (dt (- (if tend (min te tend) te)
1914 (if tstart (max ts tstart) ts))))
1915 (when (> dt 0) (cl-incf t1 (floor dt 60)))))
1916 ((match-end 4)
1917 ;; A naked time.
1918 (setq t1 (+ t1 (string-to-number (match-string 5))
1919 (* 60 (string-to-number (match-string 4))))))
1920 (t ;A headline
1921 ;; Add the currently clocking item time to the total.
1922 (when (and org-clock-report-include-clocking-task
1923 (eq (org-clocking-buffer) (current-buffer))
1924 (eq (marker-position org-clock-hd-marker) (point))
1925 tstart
1926 tend
1927 (>= (float-time org-clock-start-time) tstart)
1928 (<= (float-time org-clock-start-time) tend))
1929 (let ((time (floor (org-time-convert-to-integer
1930 (org-time-since org-clock-start-time))
1931 60)))
1932 (setq t1 (+ t1 time))))
1933 (let* ((headline-forced
1934 (get-text-property (point)
1935 :org-clock-force-headline-inclusion))
1936 (headline-included
1937 (or (null headline-filter)
1938 (save-excursion
1939 (save-match-data (funcall headline-filter))))))
1940 (setq level (- (match-end 1) (match-beginning 1)))
1941 (when (>= level lmax)
1942 (setq ltimes (vconcat ltimes (make-vector lmax 0)) lmax (* 2 lmax)))
1943 (when (or (> t1 0) (> (aref ltimes level) 0))
1944 (when (or headline-included headline-forced)
1945 (if headline-included
1946 (cl-loop for l from 0 to level do
1947 (aset ltimes l (+ (aref ltimes l) t1))))
1948 (setq time (aref ltimes level))
1949 (goto-char (match-beginning 0))
1950 (put-text-property (point) (point-at-eol)
1951 (or propname :org-clock-minutes) time)
1952 (when headline-filter
1953 (save-excursion
1954 (save-match-data
1955 (while (org-up-heading-safe)
1956 (put-text-property
1957 (point) (line-end-position)
1958 :org-clock-force-headline-inclusion t))))))
1959 (setq t1 0)
1960 (cl-loop for l from level to (1- lmax) do
1961 (aset ltimes l 0)))))))
1936 (let ((element-type
1937 (org-element-type
1938 (save-match-data
1939 (org-element-at-point)))))
1940 (cond
1941 ((and (eq element-type 'clock) (match-end 2))
1942 ;; Two time stamps.
1943 (let* ((ss (match-string 2))
1944 (se (match-string 3))
1945 (ts (org-time-string-to-seconds ss))
1946 (te (org-time-string-to-seconds se))
1947 (dt (- (if tend (min te tend) te)
1948 (if tstart (max ts tstart) ts))))
1949 (when (> dt 0) (cl-incf t1 (floor dt 60)))))
1950 ((match-end 4)
1951 ;; A naked time.
1952 (setq t1 (+ t1 (string-to-number (match-string 5))
1953 (* 60 (string-to-number (match-string 4))))))
1954 ((memq element-type '(headline inlinetask)) ;A headline
1955 ;; Add the currently clocking item time to the total.
1956 (when (and org-clock-report-include-clocking-task
1957 (eq (org-clocking-buffer) (current-buffer))
1958 (eq (marker-position org-clock-hd-marker) (point))
1959 tstart
1960 tend
1961 (>= (float-time org-clock-start-time) tstart)
1962 (<= (float-time org-clock-start-time) tend))
1963 (let ((time (floor (org-time-convert-to-integer
1964 (time-since org-clock-start-time))
1965 60)))
1966 (setq t1 (+ t1 time))))
1967 (let* ((headline-forced
1968 (get-text-property (point)
1969 :org-clock-force-headline-inclusion))
1970 (headline-included
1971 (or (null headline-filter)
1972 (save-excursion
1973 (save-match-data (funcall headline-filter))))))
1974 (setq level (- (match-end 1) (match-beginning 1)))
1975 (when (>= level lmax)
1976 (setq ltimes (vconcat ltimes (make-vector lmax 0)) lmax (* 2 lmax)))
1977 (when (or (> t1 0) (> (aref ltimes level) 0))
1978 (when (or headline-included headline-forced)
1979 (if headline-included
1980 (cl-loop for l from 0 to level do
1981 (aset ltimes l (+ (aref ltimes l) t1))))
1982 (setq time (aref ltimes level))
1983 (goto-char (match-beginning 0))
1984 (put-text-property (point) (line-end-position)
1985 (or propname :org-clock-minutes) time)
1986 (when headline-filter
1987 (save-excursion
1988 (save-match-data
1989 (while (org-up-heading-safe)
1990 (put-text-property
1991 (point) (line-end-position)
1992 :org-clock-force-headline-inclusion t))))))
1993 (setq t1 0)
1994 (cl-loop for l from level to (1- lmax) do
1995 (aset ltimes l 0))))))))
19621996 (setq org-clock-file-total-minutes (aref ltimes 0))))))
19631997
19641998 (defun org-clock-sum-current-item (&optional tstart)
20342068 h m))))
20352069
20362070 (defvar-local org-clock-overlays nil)
2071 (put 'org-clock-overlays 'permanent-local t)
20372072
20382073 (defun org-clock-put-overlay (time)
20392074 "Put an overlay on the headline at point, displaying TIME.
21112146 (org-mode)
21122147 (org-create-dblock props)
21132148 (org-update-dblock)
2114 (org-font-lock-ensure)
2149 (font-lock-ensure)
21152150 (forward-line 2)
21162151 (buffer-substring (point) (progn
21172152 (re-search-forward "^[ \t]*#\\+END" nil t)
2118 (point-at-bol)))))
2153 (line-beginning-position)))))
21192154
21202155 ;;;###autoload
21212156 (defun org-clock-report (&optional arg)
21252160 Otherwise, insert a new one.
21262161
21272162 The new table inherits its properties from the variable
2128 `org-clock-clocktable-default-properties'. The scope of the
2129 clocktable, when not specified in the previous variable, is
2130 `subtree' when the function is called from within a subtree, and
2131 `file' elsewhere.
2163 `org-clock-clocktable-default-properties'.
2164
2165 The scope of the clocktable, when not specified in the previous
2166 variable, is `subtree' of the current heading when the function is
2167 called from inside heading, and `file' elsewhere (before the first
2168 heading).
21322169
21332170 When called with a prefix argument, move to the first clock table
21342171 in the buffer and update it."
21362173 (org-clock-remove-overlays)
21372174 (when arg
21382175 (org-find-dblock "clocktable")
2139 (org-show-entry))
2176 (org-fold-show-entry))
21402177 (pcase (org-in-clocktable-p)
21412178 (`nil
21422179 (org-create-dblock
23442381 (let* ((start (pcase key
23452382 (`interactive (org-read-date nil t nil "Range start? "))
23462383 (`untilnow nil)
2347 (_ (encode-time 0 m h d month y))))
2384 (_ (org-encode-time 0 m h d month y))))
23482385 (end (pcase key
23492386 (`interactive (org-read-date nil t nil "Range end? "))
23502387 (`untilnow (current-time))
2351 (_ (encode-time 0
2352 m ;; (or m1 m)
2353 (or h1 h)
2354 (or d1 d)
2355 (or month1 month)
2356 (or y1 y)))))
2388 (_ (org-encode-time 0
2389 m ;; (or m1 m)
2390 (or h1 h)
2391 (or d1 d)
2392 (or month1 month)
2393 (or y1 y)))))
23572394 (text
23582395 (pcase key
23592396 ((or `day `today) (format-time-string "%A, %B %d, %Y" start))
23662403 (`interactive "(Range interactively set)")
23672404 (`untilnow "now"))))
23682405 (if (not as-strings) (list start end text)
2369 (let ((f (cdr org-time-stamp-formats)))
2406 (let ((f (org-time-stamp-format 'with-time)))
23702407 (list (and start (format-time-string f start))
23712408 (format-time-string f end)
23722409 text))))))
23912428 (setq n (prefix-numeric-value n))
23922429 (and (memq dir '(left down)) (setq n (- n)))
23932430 (save-excursion
2394 (goto-char (point-at-bol))
2431 (goto-char (line-beginning-position))
23952432 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
23962433 (user-error "Line needs a :block definition before this command works")
23972434 (let* ((b (match-beginning 1)) (e (match-end 1))
24212458 (cond
24222459 (d (setq ins (format-time-string
24232460 "%Y-%m-%d"
2424 (encode-time 0 0 0 (+ d n) nil y)))) ;; m
2461 (org-encode-time 0 0 0 (+ d n) nil y)))) ;; m
24252462 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
24262463 (require 'cal-iso)
24272464 (setq date (calendar-gregorian-from-absolute
24282465 (calendar-iso-to-absolute (list (+ mw n) 1 y))))
24292466 (setq ins (format-time-string
24302467 "%G-W%V"
2431 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2468 (org-encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
24322469 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
24332470 (require 'cal-iso)
24342471 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
24452482 (calendar-iso-to-absolute (org-quarter-to-date (+ mw n) y))))
24462483 (setq ins (format-time-string
24472484 (concat (number-to-string y) "-Q" (number-to-string (+ mw n)))
2448 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2485 (org-encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
24492486 (mw
24502487 (setq ins (format-time-string
24512488 "%Y-%m"
2452 (encode-time 0 0 0 1 (+ mw n) y))))
2489 (org-encode-time 0 0 0 1 (+ mw n) y))))
24532490 (y
24542491 (setq ins (number-to-string (+ y n))))))
24552492 (t (user-error "Cannot shift clocktable block")))
25052542 (when step
25062543 ;; Write many tables, in steps
25072544 (unless (or block (and ts te))
2508 (user-error "Clocktable `:step' can only be used with `:block' or `:tstart, :end'"))
2545 (user-error "Clocktable `:step' can only be used with `:block' or `:tstart', `:tend'"))
25092546 (org-clocktable-steps params)
25102547 (throw 'exit nil))
25112548
25762613 (emph (plist-get params :emphasize))
25772614 (compact? (plist-get params :compact))
25782615 (narrow (or (plist-get params :narrow) (and compact? '40!)))
2616 (filetitle (plist-get params :filetitle))
25792617 (level? (and (not compact?) (plist-get params :level)))
25802618 (timestamp (plist-get params :timestamp))
25812619 (tags (plist-get params :tags))
27152753 (if (eq formula '%) " %s |" "")
27162754 "\n")
27172755
2718 (file-name-nondirectory file-name)
2756 (if filetitle
2757 (or (org-get-title file-name)
2758 (file-name-nondirectory file-name))
2759 (file-name-nondirectory file-name))
27192760 (if level? "| " "") ;level column, maybe
27202761 (if timestamp "| " "") ;timestamp column, maybe
27212762 (if tags "| " "") ;tags column, maybe
28212862 (`semimonth "Semimonthly report starting on: ")
28222863 (`month "Monthly report starting on: ")
28232864 (`year "Annual report starting on: ")
2865 (`quarter "Quarterly report starting on: ")
28242866 (_ (user-error "Unknown `:step' specification: %S" step))))
28252867 (week-start (or (plist-get params :wstart) 1))
28262868 (month-start (or (plist-get params :mstart) 1))
28372879 (pcase (if range (car range) (plist-get params :tstart))
28382880 ((and (pred numberp) n)
28392881 (pcase-let ((`(,m ,d ,y) (calendar-gregorian-from-absolute n)))
2840 (apply #'encode-time (list 0 0 org-extend-today-until d m y))))
2882 (org-encode-time 0 0 org-extend-today-until d m y)))
28412883 (timestamp
28422884 (seconds-to-time
28432885 (org-matcher-time (or timestamp
28472889 (pcase (if range (nth 1 range) (plist-get params :tend))
28482890 ((and (pred numberp) n)
28492891 (pcase-let ((`(,m ,d ,y) (calendar-gregorian-from-absolute n)))
2850 (apply #'encode-time (list 0 0 org-extend-today-until d m y))))
2892 (org-encode-time 0 0 org-extend-today-until d m y)))
28512893 (timestamp (seconds-to-time (org-matcher-time timestamp))))))
28522894 (while (time-less-p start end)
28532895 (unless (bolp) (insert "\n"))
28592901 ;; Compute NEXT, which is the end of the current clock table,
28602902 ;; according to step.
28612903 (let* ((next
2862 (apply #'encode-time
2863 (pcase-let
2864 ((`(,_ ,_ ,_ ,d ,m ,y ,dow . ,_) (decode-time start)))
2865 (pcase step
2866 (`day (list 0 0 org-extend-today-until (1+ d) m y))
2867 (`week
2868 (let ((offset (if (= dow week-start) 7
2869 (mod (- week-start dow) 7))))
2870 (list 0 0 org-extend-today-until (+ d offset) m y)))
2871 (`semimonth (list 0 0 0
2872 (if (< d 16) 16 1)
2873 (if (< d 16) m (1+ m)) y))
2874 (`month (list 0 0 0 month-start (1+ m) y))
2875 (`year (list 0 0 org-extend-today-until 1 1 (1+ y)))))))
2904 ;; In Emacs-27 and Emacs-28 `encode-time' does not support 6 elements
2905 ;; list argument so `org-encode-time' can not be outside of `pcase'.
2906 (pcase-let
2907 ((`(,_ ,_ ,_ ,d ,m ,y ,dow . ,_) (decode-time start)))
2908 (pcase step
2909 (`day (org-encode-time 0 0 org-extend-today-until (1+ d) m y))
2910 (`week
2911 (let ((offset (if (= dow week-start) 7
2912 (mod (- week-start dow) 7))))
2913 (org-encode-time 0 0 org-extend-today-until (+ d offset) m y)))
2914 (`semimonth (org-encode-time 0 0 0
2915 (if (< d 16) 16 1)
2916 (if (< d 16) m (1+ m)) y))
2917 (`month (org-encode-time 0 0 0 month-start (1+ m) y))
2918 (`quarter (org-encode-time 0 0 0 month-start (+ 3 m) y))
2919 (`year (org-encode-time 0 0 org-extend-today-until 1 1 (1+ y))))))
28762920 (table-begin (line-beginning-position 0))
28772921 (step-time
28782922 ;; Write clock table between START and NEXT.
30173061 "If this is a CLOCK line, update it and return t.
30183062 Otherwise, return nil."
30193063 (interactive)
3020 (save-excursion
3021 (beginning-of-line 1)
3022 (skip-chars-forward " \t")
3023 (when (looking-at org-clock-string)
3024 (let ((re (concat "[ \t]*" org-clock-string
3025 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3026 "\\([ \t]*=>.*\\)?\\)?"))
3027 ts te h m s neg)
3028 (cond
3029 ((not (looking-at re))
3030 nil)
3031 ((not (match-end 2))
3032 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3033 (> org-clock-marker (point))
3034 (<= org-clock-marker (point-at-eol)))
3035 ;; The clock is running here
3036 (setq org-clock-start-time
3037 (org-time-string-to-time (match-string 1)))
3038 (org-clock-update-mode-line)))
3039 (t
3040 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3041 (end-of-line 1)
3042 (setq ts (match-string 1)
3043 te (match-string 3))
3044 (setq s (- (float-time
3045 (apply #'encode-time (org-parse-time-string te)))
3046 (float-time
3047 (apply #'encode-time (org-parse-time-string ts))))
3048 neg (< s 0)
3049 s (abs s)
3050 h (floor (/ s 3600))
3051 s (- s (* 3600 h))
3052 m (floor (/ s 60))
3053 s (- s (* 60 s)))
3054 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3055 t))))))
3064 (let ((origin (point))) ;; `save-excursion' may not work when deleting.
3065 (prog1
3066 (save-excursion
3067 (beginning-of-line 1)
3068 (skip-chars-forward " \t")
3069 (when (looking-at org-clock-string)
3070 (let ((re (concat "[ \t]*" org-clock-string
3071 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3072 "\\([ \t]*=>.*\\)?\\)?"))
3073 ts te h m s neg)
3074 (cond
3075 ((not (looking-at re))
3076 nil)
3077 ((not (match-end 2))
3078 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3079 (> org-clock-marker (point))
3080 (<= org-clock-marker (line-end-position)))
3081 ;; The clock is running here
3082 (setq org-clock-start-time
3083 (org-time-string-to-time (match-string 1)))
3084 (org-clock-update-mode-line)))
3085 (t
3086 ;; Prevent recursive call from `org-timestamp-change'.
3087 (cl-letf (((symbol-function 'org-clock-update-time-maybe) #'ignore))
3088 ;; Update timestamps.
3089 (save-excursion
3090 (goto-char (match-beginning 1)) ; opening timestamp
3091 (save-match-data (org-timestamp-change 0 'day)))
3092 ;; Refresh match data.
3093 (looking-at re)
3094 (save-excursion
3095 (goto-char (match-beginning 3)) ; closing timestamp
3096 (save-match-data (org-timestamp-change 0 'day))))
3097 ;; Refresh match data.
3098 (looking-at re)
3099 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3100 (end-of-line 1)
3101 (setq ts (match-string 1)
3102 te (match-string 3))
3103 (setq s (- (org-time-string-to-seconds te)
3104 (org-time-string-to-seconds ts))
3105 neg (< s 0)
3106 s (abs s)
3107 h (floor (/ s 3600))
3108 s (- s (* 3600 h))
3109 m (floor (/ s 60))
3110 s (- s (* 60 s)))
3111 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3112 t)))))
3113 ;; Move back to initial position, but never beyond updated
3114 ;; clock.
3115 (unless (< (point) origin)
3116 (goto-char origin)))))
30563117
30573118 (defun org-clock-save ()
30583119 "Persist various clock-related data to disk.
31213182 (let ((org-clock-in-resume 'auto-restart)
31223183 (org-clock-auto-clock-resolution nil))
31233184 (org-clock-in)
3124 (when (org-invisible-p) (org-show-context))))))
3185 (when (org-invisible-p) (org-fold-show-context))))))
31253186 (_ nil)))))
31263187
31273188 (defun org-clock-kill-emacs-query ()
00 ;;; org-colview.el --- Column View in Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2626 ;; This file contains the column view for Org.
2727
2828 ;;; Code:
29
30 (require 'org-macs)
31 (org-assert-version)
2932
3033 (require 'cl-lib)
3134 (require 'org)
112115
113116 (defvar-local org-columns-overlays nil
114117 "Holds the list of current column overlays.")
118 (put 'org-columns-overlays 'permanent-local t)
115119
116120 (defvar-local org-columns-current-fmt nil
117121 "Local variable, holds the currently active column format.")
158162 (defun org-columns-content ()
159163 "Switch to contents view while in columns view."
160164 (interactive)
161 (org-overview)
162 (org-content))
165 (org-cycle-overview)
166 (org-cycle-content))
163167
164168 (org-defkey org-columns-map "c" #'org-columns-content)
165169 (org-defkey org-columns-map "o" #'org-overview)
376380 COLUMNS is an alist (SPEC VALUE DISPLAYED). Optional argument
377381 DATELINE is non-nil when the face used should be
378382 `org-agenda-column-dateline'."
379 (when (ignore-errors (require 'face-remap))
383 (when (and (ignore-errors (require 'face-remap))
384 org-columns-header-line-remap)
380385 (setq org-columns-header-line-remap
381386 (face-remap-add-relative 'header-line '(:inherit default))))
382387 (save-excursion
511516 (defun org-columns-remove-overlays ()
512517 "Remove all currently active column overlays."
513518 (interactive)
514 (when (and (fboundp 'face-remap-remove-relative)
515 org-columns-header-line-remap)
516 (face-remap-remove-relative org-columns-header-line-remap))
519 (when org-columns-header-line-remap
520 (face-remap-remove-relative org-columns-header-line-remap)
521 (setq org-columns-header-line-remap nil))
517522 (when org-columns-overlays
518523 (when (local-variable-p 'org-previous-header-line-format)
519524 (setq header-line-format org-previous-header-line-format)
555560
556561 (defun org-columns-check-computed ()
557562 "Throw an error if current column value is computed."
558 (let ((spec (nth (current-column) org-columns-current-fmt-compiled)))
563 (let ((spec (nth (org-current-text-column) org-columns-current-fmt-compiled)))
559564 (and
560565 (nth 3 spec)
561566 (assoc spec (get-text-property (line-beginning-position) 'org-summaries))
696701 (let ((hide-body (and (/= (line-end-position) (point-max))
697702 (save-excursion
698703 (move-beginning-of-line 2)
699 (org-at-heading-p t)))))
704 (org-at-heading-p)))))
700705 (unwind-protect (funcall fun)
701 (when hide-body (outline-hide-entry)))))
706 (when hide-body (org-fold-hide-entry)))))
702707
703708 (defun org-columns-previous-allowed-value ()
704709 "Switch to the previous allowed value for this column."
711716 an integer, select that value."
712717 (interactive)
713718 (org-columns-check-computed)
714 (let* ((column (current-column))
719 (let* ((column (org-current-text-column))
720 (visible-column (current-column))
715721 (key (get-char-property (point) 'org-columns-key))
716722 (value (get-char-property (point) 'org-columns-value))
717723 (pom (or (get-text-property (line-beginning-position) 'org-hd-marker)
761767 ;; the right place on the current line.
762768 (let ((org-columns-inhibit-recalculation)) (org-columns-redo))
763769 (org-columns-update key)
764 (org-move-to-column column))))))
770 (org-move-to-column visible-column))))))
765771
766772 (defun org-colview-construct-allowed-dates (s)
767773 "Construct a list of three dates around the date in S.
771777 (when (and s (string-match (concat "^" org-ts-regexp3 "$") s))
772778 (let* ((time (org-parse-time-string s 'nodefaults))
773779 (active (equal (string-to-char s) ?<))
774 (fmt (funcall (if (nth 1 time) 'cdr 'car) org-time-stamp-formats))
780 (fmt (org-time-stamp-format (nth 1 time) (not active)))
775781 time-before time-after)
776 (unless active (setq fmt (concat "[" (substring fmt 1 -1) "]")))
777782 (setf (car time) (or (car time) 0))
778783 (setf (nth 1 time) (or (nth 1 time) 0))
779784 (setf (nth 2 time) (or (nth 2 time) 0))
781786 (setq time-after (copy-sequence time))
782787 (setf (nth 3 time-before) (1- (nth 3 time)))
783788 (setf (nth 3 time-after) (1+ (nth 3 time)))
784 (mapcar (lambda (x) (format-time-string fmt (apply #'encode-time x)))
789 (mapcar (lambda (x) (format-time-string fmt (org-encode-time x)))
785790 (list time-before time time-after)))))
786791
787792 (defun org-columns-open-link (&optional arg)
923928 (if spec
924929 (progn (setcar spec (car new))
925930 (setcdr spec (cdr new)))
926 (push new (nthcdr (current-column) org-columns-current-fmt-compiled)))
931 (push new (nthcdr (org-current-text-column) org-columns-current-fmt-compiled)))
927932 (org-columns-store-format)
928933 (org-columns-redo)))
929934
930935 (defun org-columns-delete ()
931936 "Delete the column at point from columns view."
932937 (interactive)
933 (let ((spec (nth (current-column) org-columns-current-fmt-compiled)))
938 (let ((spec (nth (org-current-text-column) org-columns-current-fmt-compiled)))
934939 (when (y-or-n-p (format "Are you sure you want to remove column %S? "
935940 (nth 1 spec)))
936941 (setq org-columns-current-fmt-compiled
940945 ;; updating it may prove counter-intuitive. See comments in
941946 ;; `org-columns-move-right' for details.
942947 (let ((org-columns-inhibit-recalculation t)) (org-columns-redo))
943 (when (>= (current-column) (length org-columns-current-fmt-compiled))
948 (when (>= (org-current-text-column) (length org-columns-current-fmt-compiled))
944949 (backward-char)))))
945950
946951 (defun org-columns-edit-attributes ()
947952 "Edit the attributes of the current column."
948953 (interactive)
949 (org-columns-new (nth (current-column) org-columns-current-fmt-compiled)))
954 (org-columns-new (nth (org-current-text-column) org-columns-current-fmt-compiled)))
950955
951956 (defun org-columns-widen (arg)
952957 "Make the column wider by ARG characters."
953958 (interactive "p")
954 (let* ((n (current-column))
959 (let* ((n (org-current-text-column))
955960 (entry (nth n org-columns-current-fmt-compiled))
956961 (width (aref org-columns-current-maxwidths n)))
957962 (setq width (max 1 (+ width arg)))
967972 (defun org-columns-move-right ()
968973 "Swap this column with the one to the right."
969974 (interactive)
970 (let* ((n (current-column))
975 (let* ((n (org-current-text-column))
971976 (cell (nthcdr n org-columns-current-fmt-compiled))
972977 e)
973978 (when (>= n (1- (length org-columns-current-fmt-compiled)))
991996 (defun org-columns-move-left ()
992997 "Swap this column with the one to the left."
993998 (interactive)
994 (let* ((n (current-column)))
999 (let* ((n (org-current-text-column)))
9951000 (when (= n 0)
9961001 (error "Cannot shift this column further to the left"))
9971002 (backward-char 1)
10231028 ;; No COLUMNS keyword in the buffer. Insert one at the
10241029 ;; beginning, right before the first heading, if any.
10251030 (goto-char (point-min))
1026 (unless (org-at-heading-p t) (outline-next-heading))
1031 (unless (org-at-heading-p) (outline-next-heading))
10271032 (let ((inhibit-read-only t))
10281033 (insert-before-markers "#+COLUMNS: " fmt "\n"))))
10291034 (setq-local org-columns-default-format fmt))))))
10371042 (let ((key (overlay-get ov 'org-columns-key)))
10381043 (when (and key (equal key p) (overlay-start ov))
10391044 (goto-char (overlay-start ov))
1040 (let* ((spec (nth (current-column) org-columns-current-fmt-compiled))
1045 (let* ((spec (nth (org-current-text-column) org-columns-current-fmt-compiled))
10411046 (value
10421047 (or (cdr (assoc spec
10431048 (get-text-property (line-beginning-position)
10471052 (let ((displayed (org-columns--displayed-value spec value))
10481053 (format (overlay-get ov 'org-columns-format))
10491054 (width
1050 (aref org-columns-current-maxwidths (current-column))))
1055 (aref org-columns-current-maxwidths (org-current-text-column))))
10511056 (overlay-put ov 'org-columns-value value)
10521057 (overlay-put ov 'org-columns-value-modified displayed)
10531058 (overlay-put ov
00 ;;; org-compat.el --- Compatibility Code for Older Emacsen -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2828
2929 ;;; Code:
3030
31
3132 (require 'cl-lib)
33 (require 'seq)
3234 (require 'org-macs)
35
36 (eval-when-compile (require 'subr-x)) ; Emacs < 28
37
38 ;; We rely on org-compat when generating Org version. Checking Org
39 ;; version here will interfere with Org build process.
40 ;; (org-assert-version)
3341
3442 (declare-function org-agenda-diary-entry "org-agenda")
3543 (declare-function org-agenda-maybe-redo "org-agenda" ())
3846 (declare-function org-calendar-goto-agenda "org-agenda" ())
3947 (declare-function org-align-tags "org" (&optional all))
4048 (declare-function org-at-heading-p "org" (&optional ignored))
41 (declare-function org-at-table.el-p "org" ())
42 (declare-function org-element-at-point "org-element" ())
49 (declare-function org-at-table.el-p "org-table" ())
50 (declare-function org-back-to-heading "org" (&optional invisible-ok))
51 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
52 (declare-function org-element-at-point-no-context "org-element" (&optional pom))
4353 (declare-function org-element-context "org-element" (&optional element))
4454 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
4555 (declare-function org-element-type "org-element" (element))
4757 (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
4858 (declare-function org-get-heading "org" (&optional no-tags no-todo no-priority no-comment))
4959 (declare-function org-get-tags "org" (&optional pos local))
50 (declare-function org-hide-block-toggle "org" (&optional force no-error element))
60 (declare-function org-fold-hide-block-toggle "org-fold" (&optional force no-error element))
5161 (declare-function org-link-display-format "ol" (s))
5262 (declare-function org-link-set-parameters "ol" (type &rest rest))
5363 (declare-function org-log-into-drawer "org" ())
5464 (declare-function org-make-tag-string "org" (tags))
65 (declare-function org-next-visible-heading "org" (arg))
5566 (declare-function org-reduced-level "org" (l))
5667 (declare-function org-return "org" (&optional indent arg interactive))
57 (declare-function org-show-context "org" (&optional key))
68 (declare-function org-fold-show-context "org-fold" (&optional key))
5869 (declare-function org-table-end "org-table" (&optional table-type))
5970 (declare-function outline-next-heading "outline" ())
6071 (declare-function speedbar-line-directory "speedbar" (&optional depth))
6172 (declare-function table--at-cell-p "table" (position &optional object at-column))
73 (declare-function org-fold-folded-p "org-fold" (&optional pos spec-or-alias))
74 (declare-function org-fold-hide-sublevels "org-fold" (levels))
75 (declare-function org-fold-hide-subtree "org-fold" ())
76 (declare-function org-fold-region "org-fold" (from to flag &optional spec))
77 (declare-function org-fold-show-all "org-fold" (&optional types))
78 (declare-function org-fold-show-children "org-fold" (&optional level))
79 (declare-function org-fold-show-entry "org-fold" (&optional hide-drawers))
80 ;; `org-string-equal-ignore-case' is in _this_ file but isn't at the
81 ;; top-level.
82 (declare-function org-string-equal-ignore-case "org-compat" (string1 string2))
6283
6384 (defvar calendar-mode-map)
6485 (defvar org-complex-heading-regexp)
6990 (defvar org-table-dataline-regexp)
7091 (defvar org-table-tab-recognizes-table.el)
7192 (defvar org-table1-hline-regexp)
93 (defvar org-fold-core-style)
94
95
96 ;;; Emacs < 29 compatibility
97
98 (defvar org-file-has-changed-p--hash-table (make-hash-table :test #'equal)
99 "Internal variable used by `org-file-has-changed-p'.")
100
101 (if (fboundp 'file-has-changed-p)
102 (defalias 'org-file-has-changed-p #'file-has-changed-p)
103 (defun org-file-has-changed-p (file &optional tag)
104 "Return non-nil if FILE has changed.
105 The size and modification time of FILE are compared to the size
106 and modification time of the same FILE during a previous
107 invocation of `org-file-has-changed-p'. Thus, the first invocation
108 of `org-file-has-changed-p' always returns non-nil when FILE exists.
109 The optional argument TAG, which must be a symbol, can be used to
110 limit the comparison to invocations with identical tags; it can be
111 the symbol of the calling function, for example."
112 (let* ((file (directory-file-name (expand-file-name file)))
113 (remote-file-name-inhibit-cache t)
114 (fileattr (file-attributes file 'integer))
115 (attr (and fileattr
116 (cons (file-attribute-size fileattr)
117 (file-attribute-modification-time fileattr))))
118 (sym (concat (symbol-name tag) "@" file))
119 (cachedattr (gethash sym org-file-has-changed-p--hash-table)))
120 (when (not (equal attr cachedattr))
121 (puthash sym attr org-file-has-changed-p--hash-table)))))
122
123 (if (fboundp 'string-equal-ignore-case)
124 (defalias 'org-string-equal-ignore-case #'string-equal-ignore-case)
125 ;; From Emacs subr.el.
126 (defun org-string-equal-ignore-case (string1 string2)
127 "Like `string-equal', but case-insensitive.
128 Upper-case and lower-case letters are treated as equal.
129 Unibyte strings are converted to multibyte for comparison."
130 (eq t (compare-strings string1 0 nil string2 0 nil t))))
72131
73132
74133 ;;; Emacs < 28.1 compatibility
134
135 (if (fboundp 'file-name-concat)
136 (defalias 'org-file-name-concat #'file-name-concat)
137 (defun org-file-name-concat (directory &rest components)
138 "Append COMPONENTS to DIRECTORY and return the resulting string.
139
140 Elements in COMPONENTS must be a string or nil.
141 DIRECTORY or the non-final elements in COMPONENTS may or may not end
142 with a slash -- if they don't end with a slash, a slash will be
143 inserted before contatenating."
144 (save-match-data
145 (mapconcat
146 #'identity
147 (delq nil
148 (mapcar
149 (lambda (str)
150 (when (and str (not (seq-empty-p str))
151 (string-match "\\(.+\\)/?" str))
152 (match-string 1 str)))
153 (cons directory components)))
154 "/"))))
75155
76156 (if (fboundp 'directory-empty-p)
77157 (defalias 'org-directory-empty-p #'directory-empty-p)
80160 (and (file-directory-p dir)
81161 (null (directory-files dir nil directory-files-no-dot-files-regexp t)))))
82162
163 (if (fboundp 'string-clean-whitespace)
164 (defalias 'org-string-clean-whitespace #'string-clean-whitespace)
165 ;; From Emacs subr-x.el.
166 (defun org-string-clean-whitespace (string)
167 "Clean up whitespace in STRING.
168 All sequences of whitespaces in STRING are collapsed into a
169 single space character, and leading/trailing whitespace is
170 removed."
171 (let ((blank "[[:blank:]\r\n]+"))
172 (string-trim (replace-regexp-in-string blank " " string t t)
173 blank blank))))
174
175 (if (fboundp 'format-prompt)
176 (defalias 'org-format-prompt #'format-prompt)
177 ;; From Emacs minibuffer.el, inlining
178 ;; `minibuffer-default-prompt-format' value and replacing `length<'
179 ;; (both new in Emacs 28.1).
180 (defun org-format-prompt (prompt default &rest format-args)
181 "Compatibility substitute for `format-prompt'."
182 (concat
183 (if (null format-args)
184 prompt
185 (apply #'format prompt format-args))
186 (and default
187 (or (not (stringp default))
188 (> (length default) 0))
189 (format " (default %s)"
190 (if (consp default)
191 (car default)
192 default)))
193 ": ")))
194
83195
84196 ;;; Emacs < 27.1 compatibility
197
198 (if (version< emacs-version "29")
199 ;; A stub when `combine-change-calls' was not yet there or had
200 ;; critical bugs (see Emacs bug#60467).
201 (defmacro org-combine-change-calls (_beg _end &rest body)
202 (declare (debug (form form def-body)) (indent 2))
203 `(progn ,@body))
204 (defalias 'org-combine-change-calls 'combine-change-calls))
205
206 (if (version< emacs-version "27.1")
207 (defsubst org-replace-buffer-contents (source &optional _max-secs _max-costs)
208 (replace-buffer-contents source))
209 (defalias 'org-replace-buffer-contents #'replace-buffer-contents))
85210
86211 (unless (fboundp 'proper-list-p)
87212 ;; `proper-list-p' was added in Emacs 27.1. The function below is
154279 (define-obsolete-function-alias 'org-babel-edit-distance 'org-string-distance
155280 "9.5")
156281
282 (unless (fboundp 'with-connection-local-variables)
283 ;; Added in Emacs 27: commit:21f54feee8, 2019-03-09.
284 ;; Redefining it using the old function `with-connection-local-profiles'.
285 (defmacro with-connection-local-variables (&rest body)
286 "Apply connection-local variables according to `default-directory'.
287 Execute BODY, and unwind connection-local variables."
288 (declare (debug t))
289 `(with-connection-local-profiles (connection-local-get-profiles nil)
290 ,@body)))
291
157292
158293 ;;; Emacs < 26.1 compatibility
159294
169304 (defsubst file-attribute-modification-time (attributes)
170305 "The modification time in ATTRIBUTES returned by `file-attributes'.
171306 This is the time of the last change to the file's contents, and
172 is a list of integers (HIGH LOW USEC PSEC) in the same style
173 as (current-time)."
307 is a Lisp timestamp in the same style as `current-time'."
174308 (nth 5 attributes)))
175309
176310 (unless (fboundp 'file-attribute-size)
178312 "The size (in bytes) in ATTRIBUTES returned by `file-attributes'.
179313 This is a floating point number if the size is too large for an integer."
180314 (nth 7 attributes)))
181
182
183 ;;; Emacs < 25.1 compatibility
184
185 (when (< emacs-major-version 25)
186 (defalias 'outline-hide-entry 'hide-entry)
187 (defalias 'outline-hide-sublevels 'hide-sublevels)
188 (defalias 'outline-hide-subtree 'hide-subtree)
189 (defalias 'outline-show-branches 'show-branches)
190 (defalias 'outline-show-children 'show-children)
191 (defalias 'outline-show-entry 'show-entry)
192 (defalias 'outline-show-subtree 'show-subtree)
193 (defalias 'xref-find-definitions 'find-tag)
194 (defalias 'format-message 'format)
195 (defalias 'gui-get-selection 'x-get-selection))
196
197 (unless (fboundp 'directory-name-p)
198 (defun directory-name-p (name)
199 "Return non-nil if NAME ends with a directory separator character."
200 (let ((len (length name))
201 (lastc ?.))
202 (if (> len 0)
203 (setq lastc (aref name (1- len))))
204 (or (= lastc ?/)
205 (and (memq system-type '(windows-nt ms-dos))
206 (= lastc ?\\))))))
207
208 ;; `string-collate-lessp' is new in Emacs 25.
209 (if (fboundp 'string-collate-lessp)
210 (defalias 'org-string-collate-lessp
211 'string-collate-lessp)
212 (defun org-string-collate-lessp (s1 s2 &rest _)
213 "Return non-nil if STRING1 is less than STRING2 in lexicographic order.
214 Case is significant."
215 (string< s1 s2)))
216
217 ;; The time- functions below translate nil to 'current-time' and
218 ;; accept an integer as of Emacs 25. 'decode-time' and
219 ;; 'format-time-string' accept nil on Emacs 24 but don't accept an
220 ;; integer until Emacs 25.
221 (if (< emacs-major-version 25)
222 (let ((convert
223 (lambda (time)
224 (cond ((not time) (current-time))
225 ((numberp time) (seconds-to-time time))
226 (t time)))))
227 (defun org-decode-time (&optional time)
228 (decode-time (funcall convert time)))
229 (defun org-format-time-string (format-string &optional time universal)
230 (format-time-string format-string (funcall convert time) universal))
231 (defun org-time-add (a b)
232 (time-add (funcall convert a) (funcall convert b)))
233 (defun org-time-subtract (a b)
234 (time-subtract (funcall convert a) (funcall convert b)))
235 (defun org-time-since (time)
236 (time-since (funcall convert time)))
237 (defun org-time-less-p (t1 t2)
238 (time-less-p (funcall convert t1) (funcall convert t2))))
239 (defalias 'org-decode-time 'decode-time)
240 (defalias 'org-format-time-string 'format-time-string)
241 (defalias 'org-time-add 'time-add)
242 (defalias 'org-time-subtract 'time-subtract)
243 (defalias 'org-time-since 'time-since)
244 (defalias 'org-time-less-p 'time-less-p))
245315
246316
247317 ;;; Obsolete aliases (remove them after the next major release).
264334 (define-obsolete-function-alias 'org-select-frame-set-input-focus 'select-frame-set-input-focus "9.0")
265335 (define-obsolete-function-alias 'org-file-remote-p 'file-remote-p "9.2")
266336
337 (define-obsolete-function-alias 'org-show-context 'org-fold-show-context "9.6")
338 (define-obsolete-function-alias 'org-show-entry 'org-fold-show-entry "9.6")
339 (define-obsolete-function-alias 'org-show-children 'org-fold-show-children "9.6")
340
341
267342 (defmacro org-re (s)
268343 "Replace posix classes in regular expression S."
269344 (declare (debug (form))
288363 "use cl-subseq (note the 0-based counting)."
289364 "9.0")
290365
366 ;;;; Functions available since Emacs 25.1
367 (define-obsolete-function-alias 'org-string-collate-lessp 'string-collate-lessp "9.6")
368 (define-obsolete-function-alias 'org-decode-time 'decode-time "9.6")
369 (define-obsolete-function-alias 'org-format-time-string 'format-time-string "9.6")
370 (define-obsolete-function-alias 'org-time-add 'time-add "9.6")
371 (define-obsolete-function-alias 'org-time-subtract 'time-subtract "9.6")
372 (define-obsolete-function-alias 'org-time-since 'time-since "9.6")
373 (define-obsolete-function-alias 'org-time-less-p 'time-less-p "9.6")
291374
292375 ;;;; Functions available since Emacs 24.3
293376 (define-obsolete-function-alias 'org-buffer-narrowed-p 'buffer-narrowed-p "9.0")
302385 (define-obsolete-function-alias 'org-string-match-p 'string-match-p "9.0")
303386
304387 ;;;; Functions and variables from previous releases now obsolete.
388 (define-obsolete-function-alias 'org-timestamp-format
389 'org-format-timestamp "Org 9.6")
390 (define-obsolete-variable-alias 'org-export-before-processing-hook
391 'org-export-before-processing-functions "Org 9.6")
392 (define-obsolete-variable-alias 'org-export-before-parsing-hook
393 'org-export-before-parsing-functions "Org 9.6")
305394 (define-obsolete-function-alias 'org-element-remove-indentation
306395 'org-remove-indentation "9.0")
307396 (define-obsolete-variable-alias 'org-latex-create-formula-image-program
308397 'org-preview-latex-default-process "9.0")
309398 (define-obsolete-variable-alias 'org-latex-preview-ltxpng-directory
310399 'org-preview-latex-image-directory "9.0")
400 (define-obsolete-variable-alias 'org-latex-listings
401 'org-latex-src-block-backend "9.6")
311402 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "9.0")
312403 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "9.0")
313404 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp "8.3")
365456 (define-obsolete-function-alias 'org-remove-latex-fragment-image-overlays
366457 'org-clear-latex-preview "9.3")
367458
459 (define-obsolete-function-alias 'org-hide-archived-subtrees
460 'org-fold-hide-archived-subtrees "9.6")
461
462 (define-obsolete-function-alias 'org-flag-region
463 'org-fold-region "9.6")
464
465 (define-obsolete-function-alias 'org-flag-subtree
466 'org-fold-subtree "9.6")
467
468 (define-obsolete-function-alias 'org-hide-entry
469 'org-fold-hide-entry "9.6")
470
471 (define-obsolete-function-alias 'org-show-subtree
472 'org-fold-show-subtree "9.6")
473
474 (define-obsolete-function-alias 'org--hide-wrapper-toggle
475 'org-fold--hide-wrapper-toggle "9.6")
476
477 (define-obsolete-function-alias 'org-hide-block-toggle
478 'org-fold-hide-block-toggle "9.6")
479
480 (define-obsolete-function-alias 'org-hide-drawer-toggle
481 'org-fold-hide-drawer-toggle "9.6")
482
483 (define-obsolete-function-alias 'org--hide-drawers
484 'org-fold--hide-drawers "9.6")
485
486 (define-obsolete-function-alias 'org-hide-block-all
487 'org-fold-hide-block-all "9.6")
488
489 (define-obsolete-function-alias 'org-hide-drawer-all
490 'org-fold-hide-drawer-all "9.6")
491
492 (define-obsolete-function-alias 'org-show-all
493 'org-fold-show-all "9.6")
494
495 (define-obsolete-function-alias 'org-set-startup-visibility
496 'org-cycle-set-startup-visibility "9.6")
497
498 (define-obsolete-function-alias 'org-show-set-visibility
499 'org-fold-show-set-visibility "9.6")
500
501 (define-obsolete-function-alias 'org-check-before-invisible-edit
502 'org-fold-check-before-invisible-edit "9.6")
503
504 (define-obsolete-function-alias 'org-flag-above-first-heading
505 'org-fold-flag-above-first-heading "9.6")
506
507 (define-obsolete-function-alias 'org-show-branches-buffer
508 'org-fold-show-branches-buffer "9.6")
509
510 (define-obsolete-function-alias 'org-show-siblings
511 'org-fold-show-siblings "9.6")
512
513 (define-obsolete-function-alias 'org-show-hidden-entry
514 'org-fold-show-hidden-entry "9.6")
515
516 (define-obsolete-function-alias 'org-flag-heading
517 'org-fold-heading "9.6")
518
519 (define-obsolete-function-alias 'org-set-startup-visibility
520 'org-cycle-set-startup-visibility "9.6")
521
522 (define-obsolete-function-alias 'org-set-visibility-according-to-property
523 'org-cycle-set-visibility-according-to-property "9.6")
524
525 (define-obsolete-variable-alias 'org-scroll-position-to-restore
526 'org-cycle-scroll-position-to-restore "9.6")
527 (define-obsolete-function-alias 'org-optimize-window-after-visibility-change
528 'org-cycle-optimize-window-after-visibility-change "9.6")
529
530 (define-obsolete-function-alias 'org-force-cycle-archived
531 'org-cycle-force-archived "9.6")
532
368533 (define-obsolete-variable-alias 'org-attach-directory
369534 'org-attach-id-dir "9.3")
370535 (make-obsolete 'org-attach-store-link "No longer used" "9.4")
372537
373538 (define-obsolete-function-alias 'org-file-url-p 'org-url-p "9.5")
374539
540 (define-obsolete-variable-alias 'org-show-context-detail
541 'org-fold-show-context-detail "9.6")
542
543 (define-obsolete-variable-alias 'org-catch-invisible-edits
544 'org-fold-catch-invisible-edits "9.6")
545
546 (define-obsolete-variable-alias 'org-reveal-start-hook
547 'org-fold-reveal-start-hook "9.6")
548 (define-obsolete-function-alias 'org-file-url-p 'org-url-p "9.6")
549 (define-obsolete-variable-alias 'org-plantuml-executable-args 'org-plantuml-args
550 "Org 9.6")
375551 (defun org-in-fixed-width-region-p ()
376552 "Non-nil if point in a fixed-width region."
377553 (save-match-data
379555 (make-obsolete 'org-in-fixed-width-region-p
380556 "use `org-element' library"
381557 "9.0")
558
559 ;; FIXME: Unused; obsoleted; to be removed.
560 (defun org-let (list &rest body) ;FIXME: So many kittens are suffering here.
561 (declare (indent 1) (obsolete cl-progv "2021"))
562 (eval (cons 'let (cons list body))))
563
564 ;; FIXME: Unused; obsoleted; to be removed.
565 (defun org-let2 (list1 list2 &rest body) ;FIXME: Where did our karma go?
566 (declare (indent 2) (obsolete cl-progv "2021"))
567 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
568
569 (make-obsolete 'org-let "to be removed" "9.6")
570 (make-obsolete 'org-let2 "to be removed" "9.6")
382571
383572 (defun org-compatible-face (inherits specs)
384573 "Make a compatible face specification.
648837 (defun org-show-block-all ()
649838 "Unfold all blocks in the current buffer."
650839 (interactive)
651 (remove-overlays nil nil 'invisible 'org-hide-block))
840 (org-fold-show-all '(blocks)))
652841
653842 (make-obsolete 'org-show-block-all
654843 "use `org-show-all' instead."
691880 When buffer positions BEG and END are provided, hide or show that
692881 region as a drawer without further ado."
693882 (declare (obsolete "use `org-hide-drawer-toggle' instead." "9.4"))
694 (if (and beg end) (org-flag-region beg end flag 'outline)
883 (if (and beg end) (org-fold-region beg end flag (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
695884 (let ((drawer
696885 (or element
697886 (and (save-excursion
700889 (org-element-at-point)))))
701890 (when (memq (org-element-type drawer) '(drawer property-drawer))
702891 (let ((post (org-element-property :post-affiliated drawer)))
703 (org-flag-region
892 (org-fold-region
704893 (save-excursion (goto-char post) (line-end-position))
705894 (save-excursion (goto-char (org-element-property :end drawer))
706895 (skip-chars-backward " \t\n")
707896 (line-end-position))
708 flag 'outline)
897 flag (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
709898 ;; When the drawer is hidden away, make sure point lies in
710899 ;; a visible part of the buffer.
711900 (when (invisible-p (max (1- (point)) (point-min)))
717906 an error. Return a non-nil value when toggling is successful."
718907 (declare (obsolete "use `org-hide-block-toggle' instead." "9.4"))
719908 (interactive)
720 (org-hide-block-toggle nil t))
909 (org-fold-hide-block-toggle nil t))
721910
722911 (defun org-hide-block-toggle-all ()
723912 "Toggle the visibility of all blocks in the current buffer."
733922 (save-excursion
734923 (save-match-data
735924 (goto-char (match-beginning 0))
736 (org-hide-block-toggle)))))))
925 (org-fold-hide-block-toggle)))))))
737926
738927 (defun org-return-indent ()
739928 "Goto next table row or insert a newline and indent.
773962
774963 (define-obsolete-function-alias 'org-get-last-sibling 'org-get-previous-sibling "9.4")
775964
965 (define-obsolete-function-alias 'org-publish-cache-ctime-of-src
966 'org-publish-cache-mtime-of-src "9.6")
967
968 (define-obsolete-function-alias 'org-truely-invisible-p
969 'org-truly-invisible-p "9.6"
970 "Compatibility alias for legacy misspelling of `org-truly-invisible-p'.")
971
972
973 (defconst org-latex-babel-language-alist
974 '(("af" . "afrikaans")
975 ("bg" . "bulgarian")
976 ("ca" . "catalan")
977 ("cs" . "czech")
978 ("cy" . "welsh")
979 ("da" . "danish")
980 ("de" . "germanb")
981 ("de-at" . "naustrian")
982 ("de-de" . "ngerman")
983 ("el" . "greek")
984 ("en" . "english")
985 ("en-au" . "australian")
986 ("en-ca" . "canadian")
987 ("en-gb" . "british")
988 ("en-ie" . "irish")
989 ("en-nz" . "newzealand")
990 ("en-us" . "american")
991 ("es" . "spanish")
992 ("et" . "estonian")
993 ("eu" . "basque")
994 ("fi" . "finnish")
995 ("fr" . "french")
996 ("fr-ca" . "canadien")
997 ("gl" . "galician")
998 ("hr" . "croatian")
999 ("hu" . "hungarian")
1000 ("id" . "indonesian")
1001 ("is" . "icelandic")
1002 ("it" . "italian")
1003 ("la" . "latin")
1004 ("ms" . "malay")
1005 ("nl" . "dutch")
1006 ("nb" . "norsk")
1007 ("nn" . "nynorsk")
1008 ("no" . "norsk")
1009 ("pl" . "polish")
1010 ("pt" . "portuguese")
1011 ("pt-br" . "brazilian")
1012 ("ro" . "romanian")
1013 ("ru" . "russian")
1014 ("sa" . "sanskrit")
1015 ("sb" . "uppersorbian")
1016 ("sk" . "slovak")
1017 ("sl" . "slovene")
1018 ("sq" . "albanian")
1019 ("sr" . "serbian")
1020 ("sv" . "swedish")
1021 ("ta" . "tamil")
1022 ("tr" . "turkish")
1023 ("uk" . "ukrainian"))
1024 "Alist between language code and corresponding Babel option.")
1025
1026 (defconst org-latex-polyglossia-language-alist
1027 '(("am" "amharic")
1028 ("ar" "arabic")
1029 ("ast" "asturian")
1030 ("bg" "bulgarian")
1031 ("bn" "bengali")
1032 ("bo" "tibetan")
1033 ("br" "breton")
1034 ("ca" "catalan")
1035 ("cop" "coptic")
1036 ("cs" "czech")
1037 ("cy" "welsh")
1038 ("da" "danish")
1039 ("de" "german" "german")
1040 ("de-at" "german" "austrian")
1041 ("de-de" "german" "german")
1042 ("dsb" "lsorbian")
1043 ("dv" "divehi")
1044 ("el" "greek")
1045 ("en" "english" "usmax")
1046 ("en-au" "english" "australian")
1047 ("en-gb" "english" "uk")
1048 ("en-nz" "english" "newzealand")
1049 ("en-us" "english" "usmax")
1050 ("eo" "esperanto")
1051 ("es" "spanish")
1052 ("et" "estonian")
1053 ("eu" "basque")
1054 ("fa" "farsi")
1055 ("fi" "finnish")
1056 ("fr" "french")
1057 ("fu" "friulan")
1058 ("ga" "irish")
1059 ("gd" "scottish")
1060 ("gl" "galician")
1061 ("he" "hebrew")
1062 ("hi" "hindi")
1063 ("hr" "croatian")
1064 ("hsb" "usorbian")
1065 ("hu" "magyar")
1066 ("hy" "armenian")
1067 ("ia" "interlingua")
1068 ("id" "bahasai")
1069 ("is" "icelandic")
1070 ("it" "italian")
1071 ("kn" "kannada")
1072 ("la" "latin" "modern")
1073 ("la-classic" "latin" "classic")
1074 ("la-medieval" "latin" "medieval")
1075 ("la-modern" "latin" "modern")
1076 ("lo" "lao")
1077 ("lt" "lithuanian")
1078 ("lv" "latvian")
1079 ("ml" "malayalam")
1080 ("mr" "maranthi")
1081 ("nb" "norsk")
1082 ("nko" "nko")
1083 ("nl" "dutch")
1084 ("nn" "nynorsk")
1085 ("no" "norsk")
1086 ("oc" "occitan")
1087 ("pl" "polish")
1088 ("pms" "piedmontese")
1089 ("pt" "portuges")
1090 ("pt-br" "brazilian")
1091 ("rm" "romansh")
1092 ("ro" "romanian")
1093 ("ru" "russian")
1094 ("sa" "sanskrit")
1095 ("se" "samin")
1096 ("sk" "slovak")
1097 ("sl" "slovenian")
1098 ("sq" "albanian")
1099 ("sr" "serbian")
1100 ("sv" "swedish")
1101 ("syr" "syriac")
1102 ("ta" "tamil")
1103 ("te" "telugu")
1104 ("th" "thai")
1105 ("tk" "turkmen")
1106 ("tr" "turkish")
1107 ("uk" "ukrainian")
1108 ("ur" "urdu")
1109 ("vi" "vietnamese"))
1110 "Alist between language code and corresponding Polyglossia option.")
1111
1112 (make-obsolete-variable 'org-latex-babel-language-alist
1113 "set `org-latex-language-alist' instead." "9.6")
1114
1115 (make-obsolete-variable 'org-latex-polyglossia-language-alist
1116 "set `org-latex-language-alist' instead." "9.6")
1117
7761118 ;;;; Obsolete link types
7771119
7781120 (eval-after-load 'ol
7791121 '(progn
7801122 (org-link-set-parameters "file+emacs") ;since Org 9.0
7811123 (org-link-set-parameters "file+sys"))) ;since Org 9.0
1124
1125
7821126
7831127
7841128
7971141 ((and (eq window-system 'w32) (fboundp 'w32-get-clipboard-data))
7981142 (w32-get-clipboard-data))))
7991143
800 ;; `set-transient-map' is only in Emacs >= 24.4
801 (defalias 'org-set-transient-map
802 (if (fboundp 'set-transient-map)
803 'set-transient-map
804 'set-temporary-overlay-map))
805
8061144
8071145 ;;; Region compatibility
8081146
8531191 (remove-text-properties 0 (length string) '(line-prefix t wrap-prefix t)
8541192 string)
8551193 (apply 'kill-new string args))
856
857 ;; `font-lock-ensure' is only available from 24.4.50 on
858 (defalias 'org-font-lock-ensure
859 (if (fboundp 'font-lock-ensure)
860 #'font-lock-ensure
861 (lambda (&optional _beg _end)
862 (with-no-warnings (font-lock-fontify-buffer)))))
8631194
8641195 ;; `file-local-name' was added in Emacs 26.1.
8651196 (defalias 'org-babel-local-file-name
8871218 (defun org-release () "N/A")
8881219 (defun org-git-version () "N/A !!check installation!!"))))))
8891220
890
891
892 ;;; Functions for Emacs < 24.4 compatibility
893
894 (defun org-define-error (name message)
895 "Define NAME as a new error signal.
896 MESSAGE is a string that will be output to the echo area if such
897 an error is signaled without being caught by a `condition-case'.
898 Implements `define-error' for older emacsen."
899 (if (fboundp 'define-error) (define-error name message)
900 (put name 'error-conditions
901 (copy-sequence (cons name (get 'error 'error-conditions))))))
902
903 (unless (fboundp 'string-suffix-p)
904 ;; From Emacs subr.el.
905 (defun string-suffix-p (suffix string &optional ignore-case)
906 "Return non-nil if SUFFIX is a suffix of STRING.
907 If IGNORE-CASE is non-nil, the comparison is done without paying
908 attention to case differences."
909 (let ((start-pos (- (length string) (length suffix))))
910 (and (>= start-pos 0)
911 (eq t (compare-strings suffix nil nil
912 string start-pos nil ignore-case))))))
1221 (define-obsolete-function-alias 'org-define-error #'define-error "9.6")
1222 (define-obsolete-function-alias 'org-without-partial-completion 'progn "9.6")
9131223
9141224
9151225 ;;; Integration with and fixes for other packages
9221232 (defcustom org-imenu-depth 2
9231233 "The maximum level for Imenu access to Org headlines.
9241234 This also applied for speedbar access."
925 :group 'org-imenu-and-speedbar
9261235 :type 'integer)
9271236
9281237 ;;;; Imenu
9621271 (add-hook 'imenu-after-jump-hook
9631272 (lambda ()
9641273 (when (derived-mode-p 'org-mode)
965 (org-show-context 'org-goto))))
1274 (org-fold-show-context 'org-goto))))
9661275 (add-hook 'org-mode-hook
9671276 (lambda ()
9681277 (setq imenu-create-index-function 'org-imenu-get-tree)))))
9861295 (require 'org-agenda)
9871296 (let (p m tp np dir txt)
9881297 (cond
989 ((setq p (text-property-any (point-at-bol) (point-at-eol)
1298 ((setq p (text-property-any (line-beginning-position) (line-end-position)
9901299 'org-imenu t))
9911300 (setq m (get-text-property p 'org-imenu-marker))
9921301 (with-current-buffer (marker-buffer m)
9961305 (overlays-at (point))))
9971306 (org-agenda-remove-restriction-lock 'noupdate)
9981307 (org-agenda-set-restriction-lock 'subtree))))
999 ((setq p (text-property-any (point-at-bol) (point-at-eol)
1308 ((setq p (text-property-any (line-beginning-position) (line-end-position)
10001309 'speedbar-function 'speedbar-find-file))
10011310 (setq tp (previous-single-property-change
10021311 (1+ p) 'speedbar-function)
10131322 (org-agenda-set-restriction-lock 'file)))
10141323 (t (user-error "Don't know how to restrict Org mode agenda")))
10151324 (move-overlay org-speedbar-restriction-lock-overlay
1016 (point-at-bol) (point-at-eol))
1325 (line-beginning-position) (line-end-position))
10171326 (setq current-prefix-arg nil)
10181327 (org-agenda-maybe-redo)))
10191328
10271336 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
10281337 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
10291338 (add-hook 'speedbar-visiting-tag-hook
1030 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
1339 (lambda () (and (derived-mode-p 'org-mode) (org-fold-show-context 'org-goto))))))
10311340
10321341 ;;;; Add Log
10331342
10481357 (cl-case (org-element-type object)
10491358 ;; Prevent checks in links due to keybinding conflict with
10501359 ;; Flyspell.
1051 ((code entity export-snippet inline-babel-call
1052 inline-src-block line-break latex-fragment link macro
1053 statistics-cookie target timestamp verbatim)
1360 ((citation citation-reference code entity export-snippet inline-babel-call
1361 inline-src-block line-break latex-fragment link macro
1362 statistics-cookie target timestamp verbatim)
10541363 nil)
10551364 (footnote-reference
10561365 ;; Only in inline footnotes, within the definition.
10751384 (or (not (match-beginning 5))
10761385 (< (point) (match-beginning 5)))
10771386 ;; Ignore checks in code, verbatim and others.
1078 (org--flyspell-object-check-p (org-element-at-point)))
1079 (let* ((element (org-element-at-point))
1387 (org--flyspell-object-check-p (org-element-at-point-no-context)))
1388 (let* ((element (org-element-at-point-no-context))
10801389 (post-affiliated (org-element-property :post-affiliated element)))
10811390 (cond
10821391 ;; Ignore checks in all affiliated keywords but captions.
10911400 (and log
10921401 (let ((drawer (org-element-lineage element '(drawer))))
10931402 (and drawer
1094 (eq (compare-strings
1095 log nil nil
1096 (org-element-property :drawer-name drawer) nil nil t)
1097 t)))))
1403 (org-string-equal-ignore-case
1404 log (org-element-property :drawer-name drawer))))))
10981405 nil)
10991406 (t
11001407 (cl-case (org-element-type element)
11351442
11361443 ;;;; Bookmark
11371444
1138 (defun org-bookmark-jump-unhide ()
1445 (defun org-bookmark-jump-unhide (&rest _)
11391446 "Unhide the current position, to show the bookmark location."
11401447 (and (derived-mode-p 'org-mode)
11411448 (or (org-invisible-p)
11421449 (save-excursion (goto-char (max (point-min) (1- (point))))
11431450 (org-invisible-p)))
1144 (org-show-context 'bookmark-jump)))
1451 (org-fold-show-context 'bookmark-jump)))
11451452
11461453 ;; Make `bookmark-jump' shows the jump location if it was hidden.
1147 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
1454 (add-hook 'bookmark-after-jump-hook #'org-bookmark-jump-unhide)
11481455
11491456 ;;;; Calendar
11501457
11971504 ;;;; Saveplace
11981505
11991506 ;; Make sure saveplace shows the location if it was hidden
1200 (eval-after-load 'saveplace
1201 '(defadvice save-place-find-file-hook (after org-make-visible activate)
1202 "Make the position visible."
1203 (org-bookmark-jump-unhide)))
1507 (advice-add 'save-place-find-file-hook :after #'org-bookmark-jump-unhide)
12041508
12051509 ;;;; Ecb
12061510
12071511 ;; Make sure ecb shows the location if it was hidden
1208 (eval-after-load 'ecb
1209 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
1210 "Make hierarchy visible when jumping into location from ECB tree buffer."
1211 (when (derived-mode-p 'org-mode)
1212 (org-show-context))))
1512 (advice-add 'ecb-method-clicked :after #'org--ecb-show-context)
1513 (defun org--ecb-show-context (&rest _)
1514 "Make hierarchy visible when jumping into location from ECB tree buffer."
1515 (when (derived-mode-p 'org-mode)
1516 (org-fold-show-context)))
12131517
12141518 ;;;; Simple
12151519
1216 (defun org-mark-jump-unhide ()
1520 (defun org-mark-jump-unhide (&rest _)
12171521 "Make the point visible with `org-show-context' after jumping to the mark."
12181522 (when (and (derived-mode-p 'org-mode)
12191523 (org-invisible-p))
1220 (org-show-context 'mark-goto)))
1221
1222 (eval-after-load 'simple
1223 '(defadvice pop-to-mark-command (after org-make-visible activate)
1224 "Make the point visible with `org-show-context'."
1225 (org-mark-jump-unhide)))
1226
1227 (eval-after-load 'simple
1228 '(defadvice exchange-point-and-mark (after org-make-visible activate)
1229 "Make the point visible with `org-show-context'."
1230 (org-mark-jump-unhide)))
1231
1232 (eval-after-load 'simple
1233 '(defadvice pop-global-mark (after org-make-visible activate)
1234 "Make the point visible with `org-show-context'."
1235 (org-mark-jump-unhide)))
1524 (org-fold-show-context 'mark-goto)))
1525
1526 (advice-add 'pop-to-mark-command :after #'org-mark-jump-unhide)
1527
1528 (advice-add 'exchange-point-and-mark :after #'org-mark-jump-unhide)
1529 (advice-add 'pop-global-mark :after #'org-mark-jump-unhide)
12361530
12371531 ;;;; Session
12381532
12411535 (eval-after-load 'session
12421536 '(add-to-list 'session-globals-exclude 'org-mark-ring))
12431537
1538 ;;;; outline-mode
1539
1540 ;; Folding in outline-mode is not compatible with org-mode folding
1541 ;; anymore. Working around to avoid breakage of external packages
1542 ;; assuming the compatibility.
1543 (define-advice outline-flag-region (:around (oldfun from to flag &rest extra) fix-for-org-fold)
1544 "Run `org-fold-region' when in org-mode."
1545 (if (derived-mode-p 'org-mode)
1546 (org-fold-region (max from (point-min)) (min to (point-max)) flag 'headline)
1547 ;; Apply EXTRA to avoid breakages if advised function definition
1548 ;; changes.
1549 (apply oldfun from to flag extra)))
1550
1551 (define-advice outline-next-visible-heading (:around (oldfun arg &rest extra) fix-for-org-fold)
1552 "Run `org-next-visible-heading' when in org-mode."
1553 (if (derived-mode-p 'org-mode)
1554 (org-next-visible-heading arg)
1555 ;; Apply EXTRA to avoid breakages if advised function definition
1556 ;; changes.
1557 (apply oldfun arg extra)))
1558
1559 (define-advice outline-back-to-heading (:around (oldfun &optional invisible-ok &rest extra) fix-for-org-fold)
1560 "Run `org-back-to-heading' when in org-mode."
1561 (if (derived-mode-p 'org-mode)
1562 (progn
1563 (beginning-of-line)
1564 (or (org-at-heading-p (not invisible-ok))
1565 (let (found)
1566 (save-excursion
1567 (while (not found)
1568 (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
1569 nil t)
1570 (signal 'outline-before-first-heading nil))
1571 (setq found (and (or invisible-ok (not (org-fold-folded-p)))
1572 (point)))))
1573 (goto-char found)
1574 found)))
1575 ;; Apply EXTRA to avoid breakages if advised function definition
1576 ;; changes.
1577 (apply oldfun invisible-ok extra)))
1578
1579 (define-advice outline-on-heading-p (:around (oldfun &optional invisible-ok &rest extra) fix-for-org-fold)
1580 "Run `org-at-heading-p' when in org-mode."
1581 (if (derived-mode-p 'org-mode)
1582 (org-at-heading-p (not invisible-ok))
1583 ;; Apply EXTRA to avoid breakages if advised function definition
1584 ;; changes.
1585 (apply oldfun invisible-ok extra)))
1586
1587 (define-advice outline-hide-sublevels (:around (oldfun levels &rest extra) fix-for-org-fold)
1588 "Run `org-fold-hide-sublevels' when in org-mode."
1589 (if (derived-mode-p 'org-mode)
1590 (org-fold-hide-sublevels levels)
1591 ;; Apply EXTRA to avoid breakages if advised function definition
1592 ;; changes.
1593 (apply oldfun levels extra)))
1594
1595 (define-advice outline-toggle-children (:around (oldfun &rest extra) fix-for-org-fold)
1596 "Run `org-fold-hide-sublevels' when in org-mode."
1597 (if (derived-mode-p 'org-mode)
1598 (save-excursion
1599 (org-back-to-heading)
1600 (if (not (org-fold-folded-p (line-end-position)))
1601 (org-fold-hide-subtree)
1602 (org-fold-show-children)
1603 (org-fold-show-entry 'hide-drawers)))
1604 ;; Apply EXTRA to avoid breakages if advised function definition
1605 ;; changes.
1606 (apply oldfun extra)))
1607
1608 ;; TODO: outline-headers-as-kill
1609
12441610 ;;;; Speed commands
12451611
12461612 (make-obsolete-variable 'org-speed-commands-user
12471613 "configure `org-speed-commands' instead." "9.5")
1248
12491614 (provide 'org-compat)
12501615
12511616 ;; Local variables:
00 ;;; org-crypt.el --- Public Key Encryption for Org Entries -*- lexical-binding: t; -*-
11 ;;
2 ;; Copyright (C) 2007-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2007-2023 Free Software Foundation, Inc.
33
44 ;; Author: John Wiegley <johnw@gnu.org>
55
5454 ;;; Code:
5555
5656 (require 'org-macs)
57 (org-assert-version)
58
59 (require 'org-macs)
5760 (require 'org-compat)
5861
5962 (declare-function epg-decrypt-string "epg" (context cipher))
7275 (declare-function org-end-of-meta-data "org" (&optional full))
7376 (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
7477 (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
75 (declare-function org-flag-subtree "org" (flag))
78 (declare-function org-fold-subtree "org-fold" (flag))
7679 (declare-function org-make-tags-matcher "org" (match))
7780 (declare-function org-previous-visible-heading "org" (arg))
7881 (declare-function org-scan-tags "org" (action matcher todo-only &optional start-level))
195198 Assume `epg-context' is set."
196199 (and org-crypt-key
197200 (or (epg-list-keys epg-context
198 (or (org-entry-get nil "CRYPTKEY" 'selective)
199 org-crypt-key))
201 (pcase (org-entry-get nil "CRYPTKEY" 'selective 'literal-nil)
202 ("nil" "")
203 (key (or key org-crypt-key ""))))
200204 (bound-and-true-p epa-file-encrypt-to)
201205 (progn
202206 (message "No crypt key set, using symmetric encryption.")
242246 (error (error-message-string err)))))
243247 (when folded-heading
244248 (goto-char folded-heading)
245 (org-flag-subtree t))
249 (org-fold-subtree t))
246250 nil)))))
247251
248252 ;;;###autoload
279283 'org-crypt-text encrypted-text))
280284 (when folded-heading
281285 (goto-char folded-heading)
282 (org-flag-subtree t))
286 (org-fold-subtree t))
283287 nil)))
284288 (_ nil)))
285289
312316 'org-mode-hook
313317 (lambda () (add-hook 'before-save-hook 'org-encrypt-entries nil t))))
314318
315 (add-hook 'org-reveal-start-hook 'org-decrypt-entry)
319 (add-hook 'org-fold-reveal-start-hook 'org-decrypt-entry)
316320
317321 (provide 'org-crypt)
318322
00 ;;; org-ctags.el --- Integrate Emacs "tags" Facility with Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2007-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2007-2023 Free Software Foundation, Inc.
33
44 ;; Author: Paul Sexton <eeeickythump@gmail.com>
55 ;; Keywords: org, wp
4444 ;; Installation
4545 ;; ============
4646 ;;
47 ;; Install org mode
48 ;; Ensure org-ctags.el is somewhere in your emacs load path.
49 ;; Download and install Exuberant ctags -- "http://ctags.sourceforge.net/"
47 ;; Download and install Exuberant ctags -- "https://ctags.sourceforge.net/"
5048 ;; Edit your .emacs file (see next section) and load emacs.
5149
5250 ;; To put in your init file (.emacs):
136134
137135 ;;; Code:
138136
137 (require 'org-macs)
138 (org-assert-version)
139
139140 (eval-when-compile (require 'cl-lib))
140141 (require 'org)
141142
156157 (defcustom org-ctags-path-to-ctags
157158 (if (executable-find "ctags-exuberant") "ctags-exuberant" "ctags")
158159 "Name of the ctags executable file."
159 :group 'org-ctags
160160 :version "24.1"
161161 :type 'file)
162162
165165 org-ctags-ask-rebuild-tags-file-then-find-tag
166166 org-ctags-ask-append-topic)
167167 "List of functions to be prepended to ORG-OPEN-LINK-FUNCTIONS by ORG-CTAGS."
168 :group 'org-ctags
169168 :version "24.1"
170169 :type 'hook
171170 :options '(org-ctags-find-tag
187186 "Text to insert when creating a new org file via opening a hyperlink.
188187 The following patterns are replaced in the string:
189188 `%t' - replaced with the capitalized title of the hyperlink"
190 :group 'org-ctags
191189 :version "24.1"
192190 :type 'string)
193191
206204 (visit-tags-table tags-filename))))))
207205
208206
209 (defadvice visit-tags-table (after org-ctags-load-tag-list activate compile)
207 (advice-add 'visit-tags-table :after #'org--ctags-load-tag-list)
208 (defun org--ctags-load-tag-list (&rest _)
210209 (when (and org-ctags-enabled-p tags-file-name)
211210 (setq-local org-ctags-tag-list
212211 (org-ctags-all-tags-in-current-tags-table))))
228227 buffer position where the tag is found."
229228 (interactive "sTag: ")
230229 (unless tags-file-name
231 (call-interactively (visit-tags-table)))
230 (call-interactively #'visit-tags-table))
232231 (save-excursion
233232 (visit-tags-table-buffer 'same)
234233 (when tags-file-name
255254 (interactive)
256255 (let ((taglist nil))
257256 (unless tags-file-name
258 (call-interactively (visit-tags-table)))
257 (call-interactively #'visit-tags-table))
259258 (save-excursion
260259 (visit-tags-table-buffer 'same)
261260 (with-current-buffer (get-file-buffer tags-file-name)
294293 ;;;; Misc interoperability with etags system =================================
295294
296295
297 (defadvice xref-find-definitions
298 (before org-ctags-set-org-mark-before-finding-tag activate compile)
296 (advice-add 'xref-find-definitions :before
297 #'org--ctags-set-org-mark-before-finding-tag)
298 (defun org--ctags-set-org-mark-before-finding-tag (&rest _)
299299 "Before trying to find a tag, save our current position on org mark ring."
300300 (save-excursion
301301 (when (and (derived-mode-p 'org-mode) org-ctags-enabled-p)
436436 Like ORG-CTAGS-FIND-TAG, but calls the external ctags program first,
437437 to rebuild (update) the TAGS file."
438438 (unless tags-file-name
439 (call-interactively (visit-tags-table)))
439 (call-interactively #'visit-tags-table))
440440 (when (buffer-file-name)
441441 (org-ctags-create-tags))
442442 (org-ctags-find-tag name))
509509 If the user enters a string that does not match an existing tag, create
510510 a new topic."
511511 (interactive)
512 (let* ((completing-read-fn (if (fboundp 'ido-completing-read)
513 'ido-completing-read
514 'completing-read))
515 (tag (funcall completing-read-fn "Topic: " org-ctags-tag-list
512 (let* ((tag (ido-completing-read "Topic: " org-ctags-tag-list
516513 nil 'confirm nil 'org-ctags-find-tag-history)))
517514 (when tag
518515 (cond
0 ;;; org-cycle.el --- Visibility cycling of Org entries -*- lexical-binding: t; -*-
1 ;;
2 ;; Copyright (C) 2020-2023 Free Software Foundation, Inc.
3 ;;
4 ;; Maintainer: Ihor Radchenko <yantar92 at gmail dot com>
5 ;; Keywords: folding, visibility cycling, invisible text
6 ;; URL: https://orgmode.org
7 ;;
8 ;; This file is part of GNU Emacs.
9 ;;
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
22 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
23 ;;
24 ;;; Commentary:
25
26 ;; This file contains code controlling global folding state in buffer
27 ;; and TAB-cycling.
28
29 ;;; Code:
30
31 (require 'org-macs)
32 (org-assert-version)
33
34 (require 'org-macs)
35 (require 'org-fold)
36
37 (declare-function org-element-type "org-element" (element))
38 (declare-function org-element-property "org-element" (property element))
39 (declare-function org-element-lineage "org-element" (datum &optional types with-self))
40 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
41 (declare-function org-display-inline-images "org" (&optional include-linked refresh beg end))
42 (declare-function org-get-tags "org" (&optional pos local fontify))
43 (declare-function org-subtree-end-visible-p "org" ())
44 (declare-function org-narrow-to-subtree "org" (&optional element))
45 (declare-function org-next-visible-heading "org" (arg))
46 (declare-function org-at-property-p "org" ())
47 (declare-function org-re-property "org" (property &optional literal allow-null value))
48 (declare-function org-remove-inline-images "org" (&optional beg end))
49 (declare-function org-item-beginning-re "org" ())
50 (declare-function org-at-heading-p "org" (&optional invisible-not-ok))
51 (declare-function org-at-item-p "org" ())
52 (declare-function org-before-first-heading-p "org" ())
53 (declare-function org-back-to-heading "org" (&optional invisible-ok))
54 (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
55 (declare-function org-entry-end-position "org" ())
56 (declare-function org-try-cdlatex-tab "org" ())
57 (declare-function org-cycle-level "org" ())
58 (declare-function org-table-next-field "org-table" ())
59 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
60 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
61 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
62 (declare-function org-list-get-all-items "org-list" (item struct prevs))
63 (declare-function org-list-get-bottom-point "org-list" (struct))
64 (declare-function org-list-prevs-alist "org-list" (struct))
65 (declare-function org-list-set-item-visibility "org-list" (item struct view))
66 (declare-function org-list-search-forward "org-list" (regexp &optional bound noerror))
67 (declare-function org-list-has-child-p "org-list" (item struct))
68 (declare-function org-list-get-item-end-before-blank "org-list" (item struct))
69 (declare-function org-list-struct "org-list" ())
70 (declare-function org-cycle-item-indentation "org-list" ())
71
72 (declare-function outline-previous-heading "outline" ())
73 (declare-function outline-next-heading "outline" ())
74 (declare-function outline-end-of-heading "outline" ())
75 (declare-function outline-up-heading "outline" (arg &optional invisible-ok))
76
77 (defvar org-drawer-regexp)
78 (defvar org-odd-levels-only)
79 (defvar org-startup-folded)
80 (defvar org-archive-tag)
81 (defvar org-cycle-include-plain-lists)
82 (defvar org-outline-regexp-bol)
83
84 (defvar-local org-cycle-global-status nil)
85 (put 'org-cycle-global-status 'org-state t)
86 (defvar-local org-cycle-subtree-status nil)
87 (put 'org-cycle-subtree-status 'org-state t)
88
89 ;;;; Customization:
90
91
92 (defgroup org-cycle nil
93 "Options concerning visibility cycling in Org mode."
94 :tag "Org Cycle"
95 :group 'org-structure)
96
97 (defcustom org-cycle-skip-children-state-if-no-children t
98 "Non-nil means skip CHILDREN state in entries that don't have any."
99 :group 'org-cycle
100 :type 'boolean)
101
102 (defcustom org-cycle-max-level nil
103 "Maximum level which should still be subject to visibility cycling.
104 Levels higher than this will, for cycling, be treated as text, not a headline.
105 When `org-odd-levels-only' is set, a value of N in this variable actually
106 means 2N-1 stars as the limiting headline.
107 When nil, cycle all levels.
108 Note that the limiting level of cycling is also influenced by
109 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
110 `org-inlinetask-min-level' is, cycling will be limited to levels one less
111 than its value."
112 :group 'org-cycle
113 :type '(choice
114 (const :tag "No limit" nil)
115 (integer :tag "Maximum level")))
116
117 (defcustom org-cycle-hide-block-startup nil
118 "Non-nil means entering Org mode will fold all blocks.
119 This can also be set in on a per-file basis with
120
121 #+STARTUP: hideblocks
122 #+STARTUP: nohideblocks"
123 :group 'org-startup
124 :group 'org-cycle
125 :type 'boolean)
126
127 (defcustom org-cycle-hide-drawer-startup t
128 "Non-nil means entering Org mode will fold all drawers.
129 This can also be set in on a per-file basis with
130
131 #+STARTUP: hidedrawers
132 #+STARTUP: nohidedrawers"
133 :group 'org-startup
134 :group 'org-cycle
135 :type 'boolean)
136
137 (defcustom org-cycle-global-at-bob nil
138 "Cycle globally if cursor is at beginning of buffer and not at a headline.
139
140 This makes it possible to do global cycling without having to use `S-TAB'
141 or `\\[universal-argument] TAB'. For this special case to work, the first \
142 line of the buffer
143 must not be a headline -- it may be empty or some other text.
144
145 When used in this way, `org-cycle-hook' is disabled temporarily to make
146 sure the cursor stays at the beginning of the buffer.
147
148 When this option is nil, don't do anything special at the beginning of
149 the buffer."
150 :group 'org-cycle
151 :type 'boolean)
152
153 (defcustom org-cycle-level-after-item/entry-creation t
154 "Non-nil means cycle entry level or item indentation in new empty entries.
155
156 When the cursor is at the end of an empty headline, i.e., with only stars
157 and maybe a TODO keyword, TAB will then switch the entry to become a child,
158 and then all possible ancestor states, before returning to the original state.
159 This makes data entry extremely fast: M-RET to create a new headline,
160 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
161
162 When the cursor is at the end of an empty plain list item, one TAB will
163 make it a subitem, two or more tabs will back up to make this an item
164 higher up in the item hierarchy."
165 :group 'org-cycle
166 :type 'boolean)
167
168 (defcustom org-cycle-emulate-tab t
169 "Where should `org-cycle' emulate TAB.
170 nil Never
171 white Only in completely white lines
172 whitestart Only at the beginning of lines, before the first non-white char
173 t Everywhere except in headlines
174 exc-hl-bol Everywhere except at the start of a headline
175 If TAB is used in a place where it does not emulate TAB, the current subtree
176 visibility is cycled."
177 :group 'org-cycle
178 :type '(choice (const :tag "Never" nil)
179 (const :tag "Only in completely white lines" white)
180 (const :tag "Before first char in a line" whitestart)
181 (const :tag "Everywhere except in headlines" t)
182 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
183
184 (defcustom org-cycle-separator-lines 2
185 "Number of empty lines needed to keep an empty line between collapsed trees.
186 If you leave an empty line between the end of a subtree and the following
187 headline, this empty line is hidden when the subtree is folded.
188 Org mode will leave (exactly) one empty line visible if the number of
189 empty lines is equal or larger to the number given in this variable.
190 So the default 2 means at least 2 empty lines after the end of a subtree
191 are needed to produce free space between a collapsed subtree and the
192 following headline.
193
194 If the number is negative, and the number of empty lines is at least -N,
195 all empty lines are shown.
196
197 Special case: when 0, never leave empty lines in collapsed view."
198 :group 'org-cycle
199 :type 'integer)
200 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
201
202 (defcustom org-cycle-pre-hook nil
203 "Hook that is run before visibility cycling is happening.
204 The function(s) in this hook must accept a single argument which indicates
205 the new state that will be set right after running this hook. The
206 argument is a symbol. Before a global state change, it can have the values
207 `overview', `content', or `all'. Before a local state change, it can have
208 the values `folded', `children', or `subtree'."
209 :group 'org-cycle
210 :type 'hook)
211
212 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
213 org-cycle-show-empty-lines
214 org-cycle-optimize-window-after-visibility-change
215 org-cycle-display-inline-images)
216 "Hook that is run after `org-cycle' has changed the buffer visibility.
217 The function(s) in this hook must accept a single argument which indicates
218 the new state that was set by the most recent `org-cycle' command. The
219 argument is a symbol. After a global state change, it can have the values
220 `overview', `contents', or `all'. After a local state change, it can have
221 the values `folded', `children', or `subtree'."
222 :group 'org-cycle
223 :package-version '(Org . "9.4")
224 :type 'hook)
225
226 (defcustom org-cycle-open-archived-trees nil
227 "Non-nil means `org-cycle' will open archived trees.
228 An archived tree is a tree marked with the tag ARCHIVE.
229 When nil, archived trees will stay folded. You can still open them with
230 normal outline commands like `show-all', but not with the cycling commands."
231 :group 'org-archive
232 :group 'org-cycle
233 :type 'boolean)
234
235 (defcustom org-cycle-inline-images-display nil
236 "Non-nil means auto display inline images under subtree when cycling."
237 :group 'org-startup
238 :group 'org-cycle
239 :package-version '(Org . "9.6")
240 :type 'boolean)
241
242 (defvar org-cycle-tab-first-hook nil
243 "Hook for functions to attach themselves to TAB.
244 See `org-ctrl-c-ctrl-c-hook' for more information.
245 This hook runs as the first action when TAB is pressed, even before
246 `org-cycle' messes around with the `outline-regexp' to cater for
247 inline tasks and plain list item folding.
248 If any function in this hook returns t, any other actions that
249 would have been caused by TAB (such as table field motion or visibility
250 cycling) will not occur.")
251
252 ;;;; Implementation:
253
254 (defun org-cycle-hide-drawers (state)
255 "Re-hide all drawers after a visibility state change.
256 STATE should be one of the symbols listed in the docstring of
257 `org-cycle-hook'."
258 (when (derived-mode-p 'org-mode)
259 (cond ((not (memq state '(overview folded contents)))
260 (let* ((global? (eq state 'all))
261 (beg (if global? (point-min) (line-beginning-position)))
262 (end (cond (global? (point-max))
263 ((eq state 'children) (org-entry-end-position))
264 (t (save-excursion (org-end-of-subtree t t))))))
265 (org-fold--hide-drawers beg end)))
266 ((memq state '(overview contents))
267 ;; Hide drawers before first heading.
268 (let ((beg (point-min))
269 (end (save-excursion
270 (goto-char (point-min))
271 (if (org-before-first-heading-p)
272 (org-entry-end-position)
273 (point-min)))))
274 (when (< beg end)
275 (org-fold--hide-drawers beg end)))))))
276
277 ;;;###autoload
278 (defun org-cycle (&optional arg)
279 "TAB-action and visibility cycling for Org mode.
280
281 This is the command invoked in Org mode by the `TAB' key. Its main
282 purpose is outline visibility cycling, but it also invokes other actions
283 in special contexts.
284
285 When this function is called with a `\\[universal-argument]' prefix, rotate \
286 the entire
287 buffer through 3 states (global cycling)
288 1. OVERVIEW: Show only top-level headlines.
289 2. CONTENTS: Show all headlines of all levels, but no body text.
290 3. SHOW ALL: Show everything.
291
292 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
293 switch to the startup visibility,
294 determined by the variable `org-startup-folded', and by any VISIBILITY
295 properties in the buffer.
296
297 With a `\\[universal-argument] \\[universal-argument] \
298 \\[universal-argument]' prefix argument, show the entire buffer, including
299 any drawers.
300
301 When inside a table, re-align the table and move to the next field.
302
303 When point is at the beginning of a headline, rotate the subtree started
304 by this line through 3 different states (local cycling)
305 1. FOLDED: Only the main headline is shown.
306 2. CHILDREN: The main headline and the direct children are shown.
307 From this state, you can move to one of the children
308 and zoom in further.
309 3. SUBTREE: Show the entire subtree, including body text.
310 If there is no subtree, switch directly from CHILDREN to FOLDED.
311
312 When point is at the beginning of an empty headline and the variable
313 `org-cycle-level-after-item/entry-creation' is set, cycle the level
314 of the headline by demoting and promoting it to likely levels. This
315 speeds up creation document structure by pressing `TAB' once or several
316 times right after creating a new headline.
317
318 When there is a numeric prefix, go up to a heading with level ARG, do
319 a `show-subtree' and return to the previous cursor position. If ARG
320 is negative, go up that many levels.
321
322 When point is not at the beginning of a headline, execute the global
323 binding for `TAB', which is re-indenting the line. See the option
324 `org-cycle-emulate-tab' for details.
325
326 As a special case, if point is at the very beginning of the buffer, if
327 there is no headline there, and if the variable `org-cycle-global-at-bob'
328 is non-nil, this function acts as if called with prefix argument \
329 \(`\\[universal-argument] TAB',
330 same as `S-TAB') also when called without prefix argument."
331 (interactive "P")
332 (org-load-modules-maybe)
333 (unless (or (run-hook-with-args-until-success 'org-cycle-tab-first-hook)
334 (and org-cycle-level-after-item/entry-creation
335 (or (org-cycle-level)
336 (org-cycle-item-indentation))))
337 (let* ((limit-level
338 (or org-cycle-max-level
339 (and (boundp 'org-inlinetask-min-level)
340 org-inlinetask-min-level
341 (1- org-inlinetask-min-level))))
342 (nstars
343 (and limit-level
344 (if org-odd-levels-only
345 (1- (* 2 limit-level))
346 limit-level)))
347 (org-outline-regexp
348 (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
349 (cond
350 ((equal arg '(16))
351 (setq last-command 'dummy)
352 (org-cycle-set-startup-visibility)
353 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
354 ((equal arg '(64))
355 (org-fold-show-all)
356 (org-unlogged-message "Entire buffer visible, including drawers"))
357 ((equal arg '(4)) (org-cycle-internal-global))
358 ;; Show-subtree, ARG levels up from here.
359 ((integerp arg)
360 (save-excursion
361 (org-back-to-heading)
362 (outline-up-heading (if (< arg 0) (- arg)
363 (- (funcall outline-level) arg)))
364 (org-fold-show-subtree)))
365 ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
366 ((and org-cycle-global-at-bob
367 (bobp)
368 (not (looking-at org-outline-regexp)))
369 (let ((org-cycle-hook
370 (remq 'org-cycle-optimize-window-after-visibility-change
371 org-cycle-hook)))
372 (org-cycle-internal-global)))
373 ;; Try CDLaTeX TAB completion.
374 ((org-try-cdlatex-tab))
375 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
376 ((and (featurep 'org-inlinetask)
377 (org-inlinetask-at-task-p)
378 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
379 (org-inlinetask-toggle-visibility))
380 (t
381 (let ((pos (point))
382 (element (org-element-at-point)))
383 (cond
384 ;; Try toggling visibility for block at point.
385 ((org-fold-hide-block-toggle nil t element))
386 ;; Try toggling visibility for drawer at point.
387 ((org-fold-hide-drawer-toggle nil t element))
388 ;; Table: enter it or move to the next field.
389 ((and (org-match-line "[ \t]*[|+]")
390 (org-element-lineage element '(table) t))
391 (if (and (eq 'table (org-element-type element))
392 (eq 'table.el (org-element-property :type element)))
393 (message (substitute-command-keys "\\<org-mode-map>\
394 Use `\\[org-edit-special]' to edit table.el tables"))
395 (org-table-justify-field-maybe)
396 (call-interactively #'org-table-next-field)))
397 ((run-hook-with-args-until-success
398 'org-tab-after-check-for-table-hook))
399 ;; At an item/headline: delegate to `org-cycle-internal-local'.
400 ((and (or (and org-cycle-include-plain-lists
401 (let ((item (org-element-lineage element
402 '(item plain-list)
403 t)))
404 (and item
405 (= (line-beginning-position)
406 (org-element-property :post-affiliated
407 item)))))
408 (org-match-line org-outline-regexp))
409 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
410 (org-cycle-internal-local))
411 ;; From there: TAB emulation and template completion.
412 (buffer-read-only (org-back-to-heading))
413 ((run-hook-with-args-until-success
414 'org-tab-after-check-for-cycling-hook))
415 ((run-hook-with-args-until-success
416 'org-tab-before-tab-emulation-hook))
417 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
418 (or (not (bolp))
419 (not (looking-at org-outline-regexp))))
420 (call-interactively (global-key-binding (kbd "TAB"))))
421 ((or (eq org-cycle-emulate-tab t)
422 (and (memq org-cycle-emulate-tab '(white whitestart))
423 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
424 (or (and (eq org-cycle-emulate-tab 'white)
425 (= (match-end 0) (line-end-position)))
426 (and (eq org-cycle-emulate-tab 'whitestart)
427 (>= (match-end 0) pos)))))
428 (call-interactively (global-key-binding (kbd "TAB"))))
429 (t
430 (save-excursion
431 (org-back-to-heading)
432 (org-cycle))))))))))
433
434 (defun org-cycle-force-archived ()
435 "Cycle subtree even if it is archived."
436 (interactive)
437 (setq this-command 'org-cycle)
438 (let ((org-cycle-open-archived-trees t))
439 (call-interactively 'org-cycle)))
440
441 (defun org-cycle-internal-global ()
442 "Do the global cycling action."
443 ;; Hack to avoid display of messages for .org attachments in Gnus
444 (let ((ga (string-match-p "\\*fontification" (buffer-name))))
445 (cond
446 ((and (eq last-command this-command)
447 (eq org-cycle-global-status 'overview))
448 ;; We just created the overview - now do table of contents
449 ;; This can be slow in very large buffers, so indicate action
450 (run-hook-with-args 'org-cycle-pre-hook 'contents)
451 (unless ga (org-unlogged-message "CONTENTS..."))
452 (org-cycle-content)
453 (unless ga (org-unlogged-message "CONTENTS...done"))
454 (setq org-cycle-global-status 'contents)
455 (run-hook-with-args 'org-cycle-hook 'contents))
456
457 ((and (eq last-command this-command)
458 (eq org-cycle-global-status 'contents))
459 ;; We just showed the table of contents - now show everything
460 (run-hook-with-args 'org-cycle-pre-hook 'all)
461 (org-fold-show-all '(headings blocks))
462 (unless ga (org-unlogged-message "SHOW ALL"))
463 (setq org-cycle-global-status 'all)
464 (run-hook-with-args 'org-cycle-hook 'all))
465
466 (t
467 ;; Default action: go to overview
468 (run-hook-with-args 'org-cycle-pre-hook 'overview)
469 (org-cycle-overview)
470 (unless ga (org-unlogged-message "OVERVIEW"))
471 (setq org-cycle-global-status 'overview)
472 (run-hook-with-args 'org-cycle-hook 'overview)))))
473
474 (defun org-cycle-internal-local ()
475 "Do the local cycling action."
476 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
477 ;; First, determine end of headline (EOH), end of subtree or item
478 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
479 (save-excursion
480 (if (org-at-item-p)
481 (progn
482 (beginning-of-line)
483 (setq struct (org-list-struct))
484 (setq eoh (line-end-position))
485 (setq eos (org-list-get-item-end-before-blank (point) struct))
486 (setq has-children (org-list-has-child-p (point) struct)))
487 (org-back-to-heading)
488 (setq eoh (save-excursion (outline-end-of-heading) (point)))
489 (setq eos (save-excursion
490 (org-end-of-subtree t t)
491 (unless (eobp) (forward-char -1))
492 (point)))
493 (setq has-children
494 (or
495 (save-excursion
496 (let ((level (funcall outline-level)))
497 (outline-next-heading)
498 (and (org-at-heading-p)
499 (> (funcall outline-level) level))))
500 (and (eq org-cycle-include-plain-lists 'integrate)
501 (save-excursion
502 (org-list-search-forward (org-item-beginning-re) eos t))))))
503 ;; Determine end invisible part of buffer (EOL)
504 (beginning-of-line 2)
505 (if (eq org-fold-core-style 'text-properties)
506 (while (and (not (eobp)) ;this is like `next-line'
507 (org-fold-folded-p (1- (point))))
508 (goto-char (org-fold-next-visibility-change nil nil t))
509 (and (eolp) (beginning-of-line 2)))
510 (while (and (not (eobp)) ;this is like `next-line'
511 (get-char-property (1- (point)) 'invisible))
512 (goto-char (next-single-char-property-change (point) 'invisible))
513 (and (eolp) (beginning-of-line 2))))
514 (setq eol (point)))
515 ;; Find out what to do next and set `this-command'
516 (cond
517 ((= eos eoh)
518 ;; Nothing is hidden behind this heading
519 (unless (org-before-first-heading-p)
520 (run-hook-with-args 'org-cycle-pre-hook 'empty))
521 (org-unlogged-message "EMPTY ENTRY")
522 (setq org-cycle-subtree-status nil)
523 (save-excursion
524 (goto-char eos)
525 (org-with-limited-levels
526 (outline-next-heading))
527 (when (org-invisible-p) (org-fold-heading nil))))
528 ((and (or (>= eol eos)
529 (save-excursion (goto-char eol) (skip-chars-forward "[:space:]" eos) (= (point) eos)))
530 (or has-children
531 (not (setq children-skipped
532 org-cycle-skip-children-state-if-no-children))))
533 ;; Entire subtree is hidden in one line: children view
534 (unless (org-before-first-heading-p)
535 (org-with-limited-levels
536 (run-hook-with-args 'org-cycle-pre-hook 'children)))
537 (if (org-at-item-p)
538 (org-list-set-item-visibility (line-beginning-position) struct 'children)
539 (org-fold-show-entry)
540 (org-with-limited-levels (org-fold-show-children))
541 (org-fold-show-set-visibility 'tree)
542 ;; Fold every list in subtree to top-level items.
543 (when (eq org-cycle-include-plain-lists 'integrate)
544 (save-excursion
545 (org-back-to-heading)
546 (while (org-list-search-forward (org-item-beginning-re) eos t)
547 (beginning-of-line 1)
548 (let* ((struct (org-list-struct))
549 (prevs (org-list-prevs-alist struct))
550 (end (org-list-get-bottom-point struct)))
551 (dolist (e (org-list-get-all-items (point) struct prevs))
552 (org-list-set-item-visibility e struct 'folded))
553 (goto-char (if (< end eos) end eos)))))))
554 (org-unlogged-message "CHILDREN")
555 (save-excursion
556 (goto-char eos)
557 (org-with-limited-levels
558 (outline-next-heading))
559 (when (and
560 ;; Subtree does not end at the end of visible section of the
561 ;; buffer.
562 (< (point) (point-max))
563 (org-invisible-p))
564 ;; Reveal the following heading line.
565 (org-fold-heading nil)))
566 (setq org-cycle-subtree-status 'children)
567 (unless (org-before-first-heading-p)
568 (run-hook-with-args 'org-cycle-hook 'children)))
569 ((or children-skipped
570 (and (eq last-command this-command)
571 (eq org-cycle-subtree-status 'children)))
572 ;; We just showed the children, or no children are there,
573 ;; now show everything.
574 (unless (org-before-first-heading-p)
575 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
576 (org-fold-region eoh eos nil 'outline)
577 (org-unlogged-message
578 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
579 (setq org-cycle-subtree-status 'subtree)
580 (unless (org-before-first-heading-p)
581 (run-hook-with-args 'org-cycle-hook 'subtree)))
582 (t
583 ;; Default action: hide the subtree.
584 (run-hook-with-args 'org-cycle-pre-hook 'folded)
585 (org-fold-region eoh eos t 'outline)
586 (org-unlogged-message "FOLDED")
587 (setq org-cycle-subtree-status 'folded)
588 (unless (org-before-first-heading-p)
589 (run-hook-with-args 'org-cycle-hook 'folded))))))
590
591 ;;;###autoload
592 (defun org-cycle-global (&optional arg)
593 "Cycle the global visibility. For details see `org-cycle'.
594 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
595 With a numeric prefix, show all headlines up to that level."
596 (interactive "P")
597 (cond
598 ((integerp arg)
599 (org-cycle-content arg)
600 (setq org-cycle-global-status 'contents))
601 ((equal arg '(4))
602 (org-cycle-set-startup-visibility)
603 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
604 (t
605 (org-cycle '(4)))))
606
607 (defun org-cycle-set-startup-visibility ()
608 "Set the visibility required by startup options and properties."
609 (cond
610 ((eq org-startup-folded t)
611 (org-cycle-overview))
612 ((eq org-startup-folded 'content)
613 (org-cycle-content))
614 ((eq org-startup-folded 'show2levels)
615 (org-cycle-content 2))
616 ((eq org-startup-folded 'show3levels)
617 (org-cycle-content 3))
618 ((eq org-startup-folded 'show4levels)
619 (org-cycle-content 4))
620 ((eq org-startup-folded 'show5levels)
621 (org-cycle-content 5))
622 ((or (eq org-startup-folded 'showeverything)
623 (eq org-startup-folded nil))
624 (org-fold-show-all)))
625 (unless (eq org-startup-folded 'showeverything)
626 (when org-cycle-hide-block-startup (org-fold-hide-block-all))
627 (org-cycle-set-visibility-according-to-property)
628 (org-cycle-hide-archived-subtrees 'all)
629 (when org-cycle-hide-drawer-startup (org-cycle-hide-drawers 'all))
630 (org-cycle-show-empty-lines t)))
631
632 (defun org-cycle-set-visibility-according-to-property ()
633 "Switch subtree visibility according to VISIBILITY property."
634 (interactive)
635 (let ((regexp (org-re-property "VISIBILITY")))
636 (org-with-point-at 1
637 (while (re-search-forward regexp nil t)
638 (let ((state (match-string 3)))
639 (if (not (org-at-property-p)) (outline-next-heading)
640 (save-excursion
641 (org-back-to-heading t)
642 (org-fold-subtree t)
643 (pcase state
644 ("folded"
645 (org-fold-subtree t))
646 ("children"
647 (org-fold-show-hidden-entry)
648 (org-fold-show-children))
649 ("content"
650 ;; Newline before heading will be outside the
651 ;; narrowing. Make sure that it is revealed.
652 (org-fold-heading nil)
653 (save-excursion
654 (save-restriction
655 (org-narrow-to-subtree)
656 (org-cycle-content))))
657 ((or "all" "showall")
658 (org-fold-show-subtree))
659 (_ nil)))
660 (org-end-of-subtree)))))))
661
662 (defun org-cycle-overview ()
663 "Switch to overview mode, showing only top-level headlines."
664 (interactive)
665 (save-excursion
666 (goto-char (point-min))
667 ;; Hide top-level drawer.
668 (save-restriction
669 (narrow-to-region (point-min) (or (re-search-forward org-outline-regexp-bol nil t) (point-max)))
670 (org-fold-hide-drawer-all))
671 (goto-char (point-min))
672 (when (re-search-forward org-outline-regexp-bol nil t)
673 (let* ((last (line-end-position))
674 (level (- (match-end 0) (match-beginning 0) 1))
675 (regexp (format "^\\*\\{1,%d\\} " level)))
676 (while (re-search-forward regexp nil :move)
677 (org-fold-region last (line-end-position 0) t 'outline)
678 (setq last (line-end-position))
679 (setq level (- (match-end 0) (match-beginning 0) 1))
680 (setq regexp (format "^\\*\\{1,%d\\} " level)))
681 (org-fold-region last (point) t 'outline)))))
682
683 (defun org-cycle-content (&optional arg)
684 "Show all headlines in the buffer, like a table of contents.
685 With numerical argument N, show content up to level N."
686 (interactive "p")
687 (org-fold-show-all '(headings))
688 (save-excursion
689 (goto-char (point-min))
690 ;; Hide top-level drawer.
691 (save-restriction
692 (narrow-to-region (point-min) (or (re-search-forward org-outline-regexp-bol nil t) (point-max)))
693 (org-fold-hide-drawer-all))
694 (goto-char (point-max))
695 (let ((regexp (if (and (wholenump arg) (> arg 0))
696 (format "^\\*\\{1,%d\\} " arg)
697 "^\\*+ "))
698 (last (point)))
699 (while (re-search-backward regexp nil t)
700 (org-fold-region (line-end-position) last t 'outline)
701 (setq last (line-end-position 0))))))
702
703 (defvar org-cycle-scroll-position-to-restore nil
704 "Temporarily store scroll position to restore.")
705 (defun org-cycle-optimize-window-after-visibility-change (state)
706 "Adjust the window after a change in outline visibility.
707 This function is the default value of the hook `org-cycle-hook'."
708 (when (get-buffer-window (current-buffer))
709 (let ((repeat (eq last-command this-command)))
710 (unless repeat
711 (setq org-cycle-scroll-position-to-restore nil))
712 (cond
713 ((eq state 'content) nil)
714 ((eq state 'all) nil)
715 ((and org-cycle-scroll-position-to-restore repeat
716 (eq state 'folded))
717 (set-window-start nil org-cycle-scroll-position-to-restore))
718 ((eq state 'folded) nil)
719 ((eq state 'children)
720 (setq org-cycle-scroll-position-to-restore (window-start))
721 (or (org-subtree-end-visible-p) (recenter 1)))
722 ((eq state 'subtree)
723 (unless repeat
724 (setq org-cycle-scroll-position-to-restore (window-start)))
725 (or (org-subtree-end-visible-p) (recenter 1)))))))
726
727 (defun org-cycle-show-empty-lines (state)
728 "Show empty lines above all visible headlines.
729 The region to be covered depends on STATE when called through
730 `org-cycle-hook'. Lisp program can use t for STATE to get the
731 entire buffer covered. Note that an empty line is only shown if there
732 are at least `org-cycle-separator-lines' empty lines before the headline."
733 (when (/= org-cycle-separator-lines 0)
734 (save-excursion
735 (let* ((n (abs org-cycle-separator-lines))
736 (re (cond
737 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
738 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
739 (t (let ((ns (number-to-string (- n 2))))
740 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
741 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
742 beg end)
743 (cond
744 ((memq state '(overview contents t))
745 (setq beg (point-min) end (point-max)))
746 ((memq state '(children folded))
747 (setq beg (point)
748 end (progn (org-end-of-subtree t t)
749 (line-beginning-position 2)))))
750 (when beg
751 (goto-char beg)
752 (while (re-search-forward re end t)
753 (unless (org-invisible-p (match-end 1))
754 (let ((e (match-end 1))
755 (b (if (>= org-cycle-separator-lines 0)
756 (match-beginning 1)
757 (save-excursion
758 (goto-char (match-beginning 0))
759 (skip-chars-backward " \t\n")
760 (line-end-position)))))
761 (org-fold-region b e nil 'outline))))))))
762 ;; Never hide empty lines at the end of the file.
763 (save-excursion
764 (goto-char (point-max))
765 (outline-previous-heading)
766 (outline-end-of-heading)
767 (when (and (looking-at "[ \t\n]+")
768 (= (match-end 0) (point-max)))
769 (org-fold-region (point) (match-end 0) nil 'outline))))
770
771 (defun org-cycle-hide-archived-subtrees (state)
772 "Re-hide all archived subtrees after a visibility state change.
773 STATE should be one of the symbols listed in the docstring of
774 `org-cycle-hook'."
775 (when (and (not org-cycle-open-archived-trees)
776 (not (memq state '(overview folded))))
777 (let ((globalp (memq state '(contents all))))
778 (if globalp
779 (org-fold-hide-archived-subtrees (point-min) (point-max))
780 (org-fold-hide-archived-subtrees
781 (point)
782 (save-excursion
783 (org-end-of-subtree t))))
784 (when (and (not globalp)
785 (member org-archive-tag
786 (org-get-tags nil 'local)))
787 (message "%s" (substitute-command-keys
788 "Subtree is archived and stays closed. Use \
789 `\\[org-cycle-force-archived]' to cycle it anyway."))))))
790
791 (defun org-cycle-display-inline-images (state)
792 "Auto display inline images under subtree when cycling.
793 It works when `org-cycle-inline-images-display' is non-nil."
794 (when org-cycle-inline-images-display
795 (pcase state
796 ('children
797 (org-with-wide-buffer
798 (org-narrow-to-subtree)
799 ;; If has nested headlines, beg,end only from parent headline
800 ;; to first child headline which reference to upper
801 ;; let-binding `org-next-visible-heading'.
802 (org-display-inline-images
803 nil nil
804 (point-min) (progn (org-next-visible-heading 1) (point)))))
805 ('subtree
806 (org-with-wide-buffer
807 (org-narrow-to-subtree)
808 ;; If has nested headlines, also inline display images under all sub-headlines.
809 (org-display-inline-images nil nil (point-min) (point-max))))
810 ('folded
811 (org-with-wide-buffer
812 (org-narrow-to-subtree)
813 (if (numberp (point-max))
814 (org-remove-inline-images (point-min) (point-max))
815 (ignore)))))))
816
817 (provide 'org-cycle)
818
819 ;;; org-cycle.el ends here
00 ;;; org-datetree.el --- Create date entries in a tree -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2828 ;; level 1 entries days.
2929
3030 ;;; Code:
31
32 (require 'org-macs)
33 (org-assert-version)
3134
3235 (require 'org)
3336
136139 (let* ((year (calendar-extract-year d))
137140 (month (calendar-extract-month d))
138141 (day (calendar-extract-day d))
139 (time (encode-time 0 0 0 day month year))
142 (time (org-encode-time 0 0 0 day month year))
140143 (iso-date (calendar-iso-from-absolute
141144 (calendar-absolute-from-gregorian d)))
142145 (weekyear (nth 2 iso-date))
184187
185188 (defun org-datetree-insert-line (year &optional month day text)
186189 (delete-region (save-excursion (skip-chars-backward " \t\n") (point)) (point))
187 (when (assq 'heading org-blank-before-new-entry)
188 (insert "\n"))
190 (when (org--blank-before-heading-p) (insert "\n"))
189191 (insert "\n" (make-string org-datetree-base-level ?*) " \n")
190192 (backward-char)
191193 (when month (org-do-demote))
196198 (when month
197199 (insert
198200 (if day
199 (format-time-string "-%m-%d %A" (encode-time 0 0 0 day month year))
200 (format-time-string "-%m %B" (encode-time 0 0 0 1 month year))))))
201 (format-time-string "-%m-%d %A" (org-encode-time 0 0 0 day month year))
202 (format-time-string "-%m %B" (org-encode-time 0 0 0 1 month year))))))
201203 (when (and day org-datetree-add-timestamp)
202204 (save-excursion
203205 (insert "\n")
204206 (org-indent-line)
205207 (org-insert-time-stamp
206 (encode-time 0 0 0 day month year)
208 (org-encode-time 0 0 0 day month year)
207209 nil
208210 (eq org-datetree-add-timestamp 'inactive))))
209211 (beginning-of-line))
00 ;;; org-duration.el --- Library handling durations -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2017-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2017-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55 ;; Keywords: outlines, hypermedia, calendar, wp
5050
5151 ;;; Code:
5252
53 (require 'org-macs)
54 (org-assert-version)
55
5356 (require 'cl-lib)
5457 (require 'org-macs)
5558
97100 :version "26.1"
98101 :package-version '(Org . "9.1")
99102 :set (lambda (var val)
100 (set-default var val)
103 (set-default-toplevel-value var val)
101104 ;; Avoid recursive load at startup.
102105 (when (featurep 'org-duration)
103106 (org-duration-set-regexps)))
283286
284287 Return value as a float. Raise an error if duration format is
285288 not recognized."
286 (cond
287 ((equal duration "") 0.0)
288 ((numberp duration) (float duration))
289 ((string-match-p org-duration--h:mm-re duration)
290 (pcase-let ((`(,hours ,minutes ,seconds)
291 (mapcar #'string-to-number (split-string duration ":"))))
292 (+ (/ (or seconds 0) 60.0) minutes (* 60 hours))))
293 ((string-match-p org-duration--full-re duration)
294 (let ((minutes 0)
295 (s 0))
296 (while (string-match org-duration--unit-re duration s)
297 (setq s (match-end 0))
298 (let ((value (string-to-number (match-string 1 duration)))
299 (unit (match-string 2 duration)))
300 (cl-incf minutes (* value (org-duration--modifier unit canonical)))))
301 (float minutes)))
302 ((string-match org-duration--mixed-re duration)
303 (let ((units-part (match-string 1 duration))
304 (hms-part (match-string 2 duration)))
305 (+ (org-duration-to-minutes units-part)
306 (org-duration-to-minutes hms-part))))
307 ((string-match-p "\\`[0-9]+\\(\\.[0-9]*\\)?\\'" duration)
308 (float (string-to-number duration)))
309 (t (error "Invalid duration format: %S" duration))))
289 (save-match-data
290 (cond
291 ((equal duration "") 0.0)
292 ((numberp duration) (float duration))
293 ((string-match-p org-duration--h:mm-re duration)
294 (pcase-let ((`(,hours ,minutes ,seconds)
295 (mapcar #'string-to-number (split-string duration ":"))))
296 (+ (/ (or seconds 0) 60.0) minutes (* 60 hours))))
297 ((string-match-p org-duration--full-re duration)
298 (let ((minutes 0)
299 (s 0))
300 (while (string-match org-duration--unit-re duration s)
301 (setq s (match-end 0))
302 (let ((value (string-to-number (match-string 1 duration)))
303 (unit (match-string 2 duration)))
304 (cl-incf minutes (* value (org-duration--modifier unit canonical)))))
305 (float minutes)))
306 ((string-match org-duration--mixed-re duration)
307 (let ((units-part (match-string 1 duration))
308 (hms-part (match-string 2 duration)))
309 (+ (org-duration-to-minutes units-part)
310 (org-duration-to-minutes hms-part))))
311 ((string-match-p "\\`[0-9]+\\(\\.[0-9]*\\)?\\'" duration)
312 (float (string-to-number duration)))
313 (t (error "Invalid duration format: %S" duration)))))
310314
311315 ;;;###autoload
312316 (defun org-duration-from-minutes (minutes &optional fmt canonical)
00 ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2012-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2012-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
5757
5858 ;;; Code:
5959
60 (require 'org-macs)
61 (org-assert-version)
62
6063 (require 'avl-tree)
64 (require 'ring)
6165 (require 'cl-lib)
6266 (require 'ol)
6367 (require 'org)
68 (require 'org-persist)
6469 (require 'org-compat)
6570 (require 'org-entities)
6671 (require 'org-footnote)
6772 (require 'org-list)
6873 (require 'org-macs)
6974 (require 'org-table)
75 (require 'org-fold-core)
7076
7177 (declare-function org-at-heading-p "org" (&optional _))
72 (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
7378 (declare-function org-escape-code-in-string "org-src" (s))
7479 (declare-function org-macro-escape-arguments "org-macro" (&rest args))
7580 (declare-function org-macro-extract-arguments "org-macro" (s))
7681 (declare-function org-reduced-level "org" (l))
7782 (declare-function org-unescape-code-in-string "org-src" (s))
83 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
7884 (declare-function outline-next-heading "outline" ())
7985 (declare-function outline-previous-heading "outline" ())
8086
81 (defvar org-archive-tag)
82 (defvar org-clock-line-re)
83 (defvar org-closed-string)
84 (defvar org-comment-string)
8587 (defvar org-complex-heading-regexp)
86 (defvar org-dblock-start-re)
87 (defvar org-deadline-string)
8888 (defvar org-done-keywords)
89 (defvar org-drawer-regexp)
9089 (defvar org-edit-src-content-indentation)
91 (defvar org-emph-re)
92 (defvar org-emphasis-regexp-components)
93 (defvar org-keyword-time-not-clock-regexp)
9490 (defvar org-match-substring-regexp)
9591 (defvar org-odd-levels-only)
96 (defvar org-outline-regexp-bol)
97 (defvar org-planning-line-re)
9892 (defvar org-property-drawer-re)
9993 (defvar org-property-format)
10094 (defvar org-property-re)
101 (defvar org-scheduled-string)
10295 (defvar org-src-preserve-indentation)
10396 (defvar org-tags-column)
104 (defvar org-time-stamp-formats)
10597 (defvar org-todo-regexp)
10698 (defvar org-ts-regexp-both)
107 (defvar org-verbatim-re)
10899
109100
110101 ;;; Definitions And Rules
116107 ;; `org-element-update-syntax' builds proper syntax regexps according
117108 ;; to current setup.
118109
110 (defconst org-element-archive-tag "ARCHIVE"
111 "Tag marking a substree as archived.")
112
119113 (defconst org-element-citation-key-re
120114 (rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
121115 "Regexp matching a citation key.
129123 "Regexp matching a citation prefix.
130124 Style, if any, is located in match group 1.")
131125
126 (defconst org-element-clock-line-re
127 (rx-to-string
128 `(seq
129 line-start (0+ (or ?\t ?\s))
130 "CLOCK: "
131 (regexp ,org-ts-regexp-inactive)
132 (opt "--"
133 (regexp ,org-ts-regexp-inactive)
134 (1+ (or ?\t ?\s)) "=>" (1+ (or ?\t ?\s))
135 (1+ digit) ":" digit digit)
136 (0+ (or ?\t ?\s))
137 line-end))
138 "Regexp matching a clock line.")
139
140 (defconst org-element-comment-string "COMMENT"
141 "String marker for commented headlines.")
142
143 (defconst org-element-closed-keyword "CLOSED:"
144 "Keyword used to close TODO entries.")
145
146 (defconst org-element-deadline-keyword "DEADLINE:"
147 "Keyword used to mark deadline entries.")
148
149 (defconst org-element-scheduled-keyword "SCHEDULED:"
150 "Keyword used to mark scheduled entries.")
151
152 (defconst org-element-planning-keywords-re
153 (regexp-opt (list org-element-closed-keyword
154 org-element-deadline-keyword
155 org-element-scheduled-keyword))
156 "Regexp matching any planning line keyword.")
157
158 (defconst org-element-planning-line-re
159 (rx-to-string
160 `(seq line-start (0+ (any ?\s ?\t))
161 (group (regexp ,org-element-planning-keywords-re))))
162 "Regexp matching a planning line.")
163
164 (defconst org-element-drawer-re
165 (rx line-start (0+ (any ?\s ?\t))
166 ":" (group (1+ (any ?- ?_ word))) ":"
167 (0+ (any ?\s ?\t)) line-end)
168 "Regexp matching opening or closing line of a drawer.
169 Drawer's name is located in match group 1.")
170
171 (defconst org-element-dynamic-block-open-re
172 (rx line-start (0+ (any ?\s ?\t))
173 "#+BEGIN:" (0+ (any ?\s ?\t))
174 (group (1+ word))
175 (opt
176 (1+ (any ?\s ?\t))
177 (group (1+ nonl))))
178 "Regexp matching the opening line of a dynamic block.
179 Dynamic block's name is located in match group 1.
180 Parameters are in match group 2.")
181
182 (defconst org-element-headline-re
183 (rx line-start (1+ "*") " ")
184 "Regexp matching a headline.")
185
132186 (defvar org-element-paragraph-separate nil
133187 "Regexp to separate paragraphs in an Org buffer.
134188 In the case of lines starting with \"#\" and \":\", this regexp
138192 (defvar org-element--object-regexp nil
139193 "Regexp possibly matching the beginning of an object.
140194 This regexp allows false positives. Dedicated parser (e.g.,
141 `org-export-bold-parser') will take care of further filtering.
195 `org-element-bold-parser') will take care of further filtering.
142196 Radio links are not matched by this regexp, as they are treated
143197 specially in `org-element--object-lex'.")
144198
173227 ;; LaTeX environments.
174228 "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
175229 ;; Clock lines.
176 "CLOCK:" "\\|"
230 org-element-clock-line-re "\\|"
177231 ;; Lists.
178232 (let ((term (pcase org-plain-list-ordered-item-terminator
179233 (?\) ")") (?. "\\.") (_ "[.)]")))
189243 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
190244 ;; Bold, code, italic, strike-through, underline
191245 ;; and verbatim.
192 (concat "[*~=+_/]"
193 (format "[^%s]"
194 (nth 2 org-emphasis-regexp-components)))
246 (rx (or "*" "~" "=" "+" "_" "/") (not space))
195247 ;; Plain links.
196248 (concat "\\<" link-types ":")
197249 ;; Objects starting with "[": citations,
244296 (defconst org-element-greater-elements
245297 '(center-block drawer dynamic-block footnote-definition headline inlinetask
246298 item plain-list property-drawer quote-block section
247 special-block table)
299 special-block table org-data)
248300 "List of recursive element types aka Greater Elements.")
249301
250302 (defconst org-element-all-objects
395447 "Alist between element types and locations of secondary values.")
396448
397449 (defconst org-element--pair-round-table
398 (let ((table (make-syntax-table)))
450 (let ((table (make-char-table 'syntax-table '(2))))
399451 (modify-syntax-entry ?\( "()" table)
400452 (modify-syntax-entry ?\) ")(" table)
401 (dolist (char '(?\{ ?\} ?\[ ?\] ?\< ?\>) table)
402 (modify-syntax-entry char " " table)))
403 "Table used internally to pair only round brackets.
404 Other brackets are treated as spaces.")
453 table)
454 "Table used internally to pair only round brackets.")
405455
406456 (defconst org-element--pair-square-table
407 (let ((table (make-syntax-table)))
457 (let ((table (make-char-table 'syntax-table '(2))))
408458 (modify-syntax-entry ?\[ "(]" table)
409459 (modify-syntax-entry ?\] ")[" table)
410 (dolist (char '(?\{ ?\} ?\( ?\) ?\< ?\>) table)
411 (modify-syntax-entry char " " table)))
412 "Table used internally to pair only square brackets.
413 Other brackets are treated as spaces.")
460 table)
461 "Table used internally to pair only square brackets.")
414462
415463 (defconst org-element--pair-curly-table
416 (let ((table (make-syntax-table)))
464 (let ((table (make-char-table 'syntax-table '(2))))
417465 (modify-syntax-entry ?\{ "(}" table)
418466 (modify-syntax-entry ?\} "){" table)
419 (dolist (char '(?\[ ?\] ?\( ?\) ?\< ?\>) table)
420 (modify-syntax-entry char " " table)))
421 "Table used internally to pair only curly brackets.
422 Other brackets are treated as spaces.")
467 table)
468 "Table used internally to pair only curly brackets.")
423469
424470 (defun org-element--parse-paired-brackets (char)
425471 "Parse paired brackets at point.
555601 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
556602 ;; string: parent is the list itself.
557603 (dolist (child children)
558 (org-element-put-property child :parent (or parent children)))
604 (when child
605 (org-element-put-property child :parent (or parent children))))
559606 ;; Add CHILDREN at the end of PARENT contents.
560607 (when parent
561608 (apply #'org-element-set-contents
611658 ;; Set appropriate :parent property.
612659 (org-element-put-property element :parent parent)))
613660
661 (defconst org-element--cache-element-properties
662 '(:cached
663 :org-element--cache-sync-key)
664 "List of element properties used internally by cache.")
665
614666 (defun org-element-set-element (old new)
615667 "Replace element or object OLD with element or object NEW.
616668 The function takes care of setting `:parent' property for NEW."
617669 ;; Ensure OLD and NEW have the same parent.
618670 (org-element-put-property new :parent (org-element-property :parent old))
671 (dolist (p org-element--cache-element-properties)
672 (when (org-element-property p old)
673 (org-element-put-property new p (org-element-property p old))))
619674 (if (or (memq (org-element-type old) '(plain-text nil))
620675 (memq (org-element-type new) '(plain-text nil)))
621676 ;; We cannot replace OLD with NEW since one of them is not an
652707 (`plain-text (substring-no-properties datum))
653708 (`nil (copy-sequence datum))
654709 (_
655 (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil)))))))
710 (let ((element-copy (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil))))
711 ;; We cannot simply return the copies property list. When
712 ;; DATUM is i.e. a headline, it's property list (`:title'
713 ;; in case of headline) can contain parsed objects. The
714 ;; objects will contain `:parent' property set to the DATUM
715 ;; itself. When copied, these inner `:parent' property
716 ;; values will contain incorrect object decoupled from
717 ;; DATUM. Changes to the DATUM copy will not longer be
718 ;; reflected in the `:parent' properties. So, we need to
719 ;; reassign inner `:parent' properties to the DATUM copy
720 ;; explicitly.
721 (org-element-map element-copy (cons 'plain-text org-element-all-objects)
722 (lambda (obj) (when (equal datum (org-element-property :parent obj))
723 (org-element-put-property obj :parent element-copy))))
724 element-copy))))))
656725
657726
658727
763832 (org-element-paragraph-parser limit affiliated)
764833 (save-excursion
765834 (let* ((drawer-end-line (match-beginning 0))
766 (name (progn (looking-at org-drawer-regexp)
767 (match-string-no-properties 1)))
835 (name
836 (progn
837 (looking-at org-element-drawer-re)
838 (match-string-no-properties 1)))
768839 (begin (car affiliated))
769840 (post-affiliated (point))
770841 ;; Empty drawers have no contents.
819890 (org-element-paragraph-parser limit affiliated)
820891 (let ((block-end-line (match-beginning 0)))
821892 (save-excursion
822 (let* ((name (progn (looking-at org-dblock-start-re)
823 (match-string-no-properties 1)))
824 (arguments (match-string-no-properties 3))
893 (let* ((name (progn
894 (looking-at org-element-dynamic-block-open-re)
895 (match-string-no-properties 1)))
896 (arguments (match-string-no-properties 2))
825897 (begin (car affiliated))
826898 (post-affiliated (point))
827899 ;; Empty blocks have no contents.
859931 ;;;; Footnote Definition
860932
861933 (defconst org-element--footnote-separator
862 (concat org-outline-regexp-bol "\\|"
934 (concat org-element-headline-re "\\|"
863935 org-footnote-definition-re "\\|"
864936 "^\\([ \t]*\n\\)\\{2,\\}")
865937 "Regexp used as a footnote definition separator.")
9431015 (if (= pre-blank 0) (concat " " (org-trim contents))
9441016 (concat (make-string pre-blank ?\n) contents)))))
9451017
946
9471018 ;;;; Headline
9481019
949 (defun org-element--get-node-properties ()
950 "Return node properties associated to headline at point.
1020 (defun org-element--get-node-properties (&optional at-point-p?)
1021 "Return node properties for headline or property drawer at point.
9511022 Upcase property names. It avoids confusion between properties
9521023 obtained through property drawer and default properties from the
953 parser (e.g. `:end' and :END:). Return value is a plist."
1024 parser (e.g. `:end' and :END:). Return value is a plist.
1025
1026 When AT-POINT-P? is nil, assume that point as at a headline. Otherwise
1027 parse properties for property drawer at point."
9541028 (save-excursion
955 (forward-line)
956 (when (looking-at-p org-planning-line-re) (forward-line))
1029 (unless at-point-p?
1030 (forward-line)
1031 (when (looking-at-p org-element-planning-line-re) (forward-line)))
9571032 (when (looking-at org-property-drawer-re)
9581033 (forward-line)
9591034 (let ((end (match-end 0)) properties)
9601035 (while (< (line-end-position) end)
9611036 (looking-at org-property-re)
962 (push (match-string-no-properties 3) properties)
963 (push (intern (concat ":" (upcase (match-string 2)))) properties)
1037 (let* ((property-name (concat ":" (upcase (match-string 2))))
1038 (property-name-symbol (intern property-name))
1039 (property-value (match-string-no-properties 3)))
1040 (cond
1041 ((and (plist-member properties property-name-symbol)
1042 (string-match-p "\\+$" property-name))
1043 (let ((val (plist-get properties property-name-symbol)))
1044 (if (listp val)
1045 (setq properties
1046 (plist-put properties
1047 property-name-symbol
1048 (append (plist-get properties property-name-symbol)
1049 (list property-value))))
1050 (plist-put properties property-name-symbol (list val property-value)))))
1051 (t (setq properties (plist-put properties property-name-symbol property-value)))))
9641052 (forward-line))
9651053 properties))))
9661054
9681056 "Return time properties associated to headline at point.
9691057 Return value is a plist."
9701058 (save-excursion
971 (when (progn (forward-line) (looking-at org-planning-line-re))
972 (let ((end (line-end-position)) plist)
973 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
974 (goto-char (match-end 1))
1059 (when (progn (forward-line) (looking-at org-element-planning-line-re))
1060 (let ((end (line-end-position))
1061 plist)
1062 (while (re-search-forward org-element-planning-keywords-re end t)
9751063 (skip-chars-forward " \t")
976 (let ((keyword (match-string 1))
1064 (let ((keyword (match-string 0))
9771065 (time (org-element-timestamp-parser)))
978 (cond ((equal keyword org-scheduled-string)
1066 (cond ((equal keyword org-element-scheduled-keyword)
9791067 (setq plist (plist-put plist :scheduled time)))
980 ((equal keyword org-deadline-string)
1068 ((equal keyword org-element-deadline-keyword)
9811069 (setq plist (plist-put plist :deadline time)))
9821070 (t (setq plist (plist-put plist :closed time))))))
9831071 plist))))
9841072
985 (defun org-element-headline-parser (limit &optional raw-secondary-p)
1073 (defun org-element-headline-parser (&optional _ raw-secondary-p)
9861074 "Parse a headline.
9871075
9881076 Return a list whose CAR is `headline' and CDR is a plist
9971085 with its name in upper cases and colons added at the
9981086 beginning (e.g., `:CUSTOM_ID').
9991087
1000 LIMIT is a buffer position bounding the search.
1001
10021088 When RAW-SECONDARY-P is non-nil, headline's title will not be
10031089 parsed as a secondary string, but as a plain string instead.
10041090
10051091 Assume point is at beginning of the headline."
10061092 (save-excursion
10071093 (let* ((begin (point))
1008 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
1009 (skip-chars-forward " \t")))
1094 (true-level (prog1 (skip-chars-forward "*")
1095 (skip-chars-forward " \t")))
1096 (level (org-reduced-level true-level))
10101097 (todo (and org-todo-regexp
10111098 (let (case-fold-search) (looking-at (concat org-todo-regexp " ")))
10121099 (progn (goto-char (match-end 0))
10181105 (progn (goto-char (match-end 0))
10191106 (aref (match-string 0) 2))))
10201107 (commentedp
1021 (and (let (case-fold-search) (looking-at org-comment-string))
1022 (goto-char (match-end 0))))
1108 (and (let ((case-fold-search nil))
1109 (looking-at org-element-comment-string))
1110 (goto-char (match-end 0))
1111 (when (looking-at-p "\\(?:[ \t]\\|$\\)")
1112 (point))))
10231113 (title-start (prog1 (point)
10241114 (unless (or todo priority commentedp)
10251115 ;; Headline like "* :tag:"
10331123 (title-end (point))
10341124 (raw-value (org-trim
10351125 (buffer-substring-no-properties title-start title-end)))
1036 (archivedp (member org-archive-tag tags))
1126 (archivedp (member org-element-archive-tag tags))
10371127 (footnote-section-p (and org-footnote-section
10381128 (string= org-footnote-section raw-value)))
10391129 (standard-props (org-element--get-node-properties))
10401130 (time-props (org-element--get-time-properties))
1041 (end (min (save-excursion (org-end-of-subtree t t)) limit))
1131 (end
1132 (save-excursion
1133 (let ((re (rx-to-string
1134 `(seq line-start (** 1 ,true-level "*") " "))))
1135 (if (re-search-forward re nil t)
1136 (line-beginning-position)
1137 (point-max)))))
10421138 (contents-begin (save-excursion
10431139 (forward-line)
10441140 (skip-chars-forward " \r\t\n" end)
10461142 (contents-end (and contents-begin
10471143 (progn (goto-char end)
10481144 (skip-chars-backward " \r\t\n")
1049 (line-beginning-position 2)))))
1145 (line-beginning-position 2))))
1146 (robust-begin (and contents-begin
1147 (progn (goto-char contents-begin)
1148 (when (looking-at-p org-element-planning-line-re)
1149 (forward-line))
1150 (when (looking-at org-property-drawer-re)
1151 (goto-char (match-end 0)))
1152 ;; If there is :pre-blank, we
1153 ;; need to be careful about
1154 ;; robust beginning.
1155 (max (if (< (+ 2 contents-begin) contents-end)
1156 (+ 2 contents-begin)
1157 0)
1158 (point)))))
1159 (robust-end (and robust-begin
1160 (when (> (- contents-end 2) robust-begin)
1161 (- contents-end 2)))))
1162 (unless robust-end (setq robust-begin nil))
10501163 (let ((headline
10511164 (list 'headline
10521165 (nconc
10581171 (1- (count-lines begin contents-begin)))
10591172 :contents-begin contents-begin
10601173 :contents-end contents-end
1174 :robust-begin robust-begin
1175 :robust-end robust-end
10611176 :level level
10621177 :priority priority
10631178 :tags tags
11041219 (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
11051220 ?*)
11061221 (and todo (concat " " todo))
1107 (and commentedp (concat " " org-comment-string))
1222 (and commentedp (concat " " org-element-comment-string))
11081223 (and priority (format " [#%c]" priority))
11091224 " "
11101225 (if (and org-footnote-section
11301245 (make-string (1+ pre-blank) ?\n)
11311246 contents)))
11321247
1248 ;;;; org-data
1249
1250 (defun org-element--get-global-node-properties ()
1251 "Return node properties associated with the whole Org buffer.
1252 Upcase property names. It avoids confusion between properties
1253 obtained through property drawer and default properties from the
1254 parser (e.g. `:end' and :END:). Return value is a plist."
1255 (org-with-wide-buffer
1256 (goto-char (point-min))
1257 (while (and (org-at-comment-p) (bolp)) (forward-line))
1258 (org-element--get-node-properties t)))
1259
1260
1261 (defvar org-element-org-data-parser--recurse nil)
1262 (defun org-element-org-data-parser (&optional _)
1263 "Parse org-data."
1264 (org-with-wide-buffer
1265 (let* ((begin 1)
1266 (contents-begin (progn
1267 (goto-char 1)
1268 (org-skip-whitespace)
1269 (beginning-of-line)
1270 (point)))
1271 (end (point-max))
1272 (pos-before-blank (progn (goto-char (point-max))
1273 (skip-chars-backward " \r\t\n")
1274 (line-beginning-position 2)))
1275 (robust-end (when (> (- pos-before-blank 2) contents-begin)
1276 (- pos-before-blank 2)))
1277 (robust-begin (when (and robust-end
1278 (< (+ 2 contents-begin) pos-before-blank))
1279 (or
1280 (org-with-wide-buffer
1281 (goto-char (point-min))
1282 (while (and (org-at-comment-p) (bolp)) (forward-line))
1283 (when (looking-at org-property-drawer-re)
1284 (goto-char (match-end 0))
1285 (skip-chars-backward " \t")
1286 (min robust-end (point))))
1287 (+ 2 contents-begin))))
1288 (category (cond ((null org-category)
1289 (when (org-with-base-buffer nil
1290 buffer-file-name)
1291 (file-name-sans-extension
1292 (file-name-nondirectory
1293 (org-with-base-buffer nil
1294 buffer-file-name)))))
1295 ((symbolp org-category) (symbol-name org-category))
1296 (t org-category)))
1297 (category (catch 'buffer-category
1298 (unless org-element-org-data-parser--recurse
1299 (org-with-point-at end
1300 ;; Avoid recursive calls from
1301 ;; `org-element-at-point-no-context'.
1302 (let ((org-element-org-data-parser--recurse t))
1303 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
1304 (org-element-with-disabled-cache
1305 (let ((element (org-element-at-point-no-context)))
1306 (when (eq (org-element-type element) 'keyword)
1307 (throw 'buffer-category
1308 (org-element-property :value element)))))))))
1309 category))
1310 (properties (org-element--get-global-node-properties)))
1311 (unless (plist-get properties :CATEGORY)
1312 (setq properties (plist-put properties :CATEGORY category)))
1313 (list 'org-data
1314 (nconc
1315 (list :begin begin
1316 :contents-begin contents-begin
1317 :contents-end pos-before-blank
1318 :end end
1319 :robust-begin robust-begin
1320 :robust-end robust-end
1321 :post-blank (count-lines pos-before-blank end)
1322 :post-affiliated begin
1323 :path (buffer-file-name)
1324 :mode 'org-data)
1325 properties)))))
1326
1327 (defun org-element-org-data-interpreter (_ contents)
1328 "Interpret ORG-DATA element as Org syntax.
1329 CONTENTS is the contents of the element."
1330 contents)
11331331
11341332 ;;;; Inlinetask
11351333
11661364 (priority (and (looking-at "\\[#.\\][ \t]*")
11671365 (progn (goto-char (match-end 0))
11681366 (aref (match-string 0) 2))))
1169 (title-start (point))
1367 (commentedp
1368 (and (let ((case-fold-search nil))
1369 (looking-at org-element-comment-string))
1370 (goto-char (match-end 0))
1371 (when (looking-at-p "\\(?:[ \t]\\|$\\)")
1372 (point))))
1373 (title-start (prog1 (point)
1374 (unless (or todo priority commentedp)
1375 ;; Headline like "* :tag:"
1376 (skip-chars-backward " \t"))))
11701377 (tags (when (re-search-forward
11711378 "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
11721379 (line-end-position)
11761383 (title-end (point))
11771384 (raw-value (org-trim
11781385 (buffer-substring-no-properties title-start title-end)))
1386 (archivedp (member org-element-archive-tag tags))
11791387 (task-end (save-excursion
11801388 (end-of-line)
1181 (and (re-search-forward org-outline-regexp-bol limit t)
1389 (and (re-search-forward org-element-headline-re limit t)
11821390 (looking-at-p "[ \t]*END[ \t]*$")
11831391 (line-beginning-position))))
11841392 (standard-props (and task-end (org-element--get-node-properties)))
12111419 :todo-keyword todo
12121420 :todo-type todo-type
12131421 :post-blank (1- (count-lines (or task-end begin) end))
1214 :post-affiliated begin)
1422 :post-affiliated begin
1423 :archivedp archivedp
1424 :commentedp commentedp)
12151425 time-props
12161426 standard-props))))
12171427 (org-element-put-property
13991609 (let ((case-fold-search t)
14001610 (top-ind limit)
14011611 (item-re (org-item-re))
1402 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1612 (inlinetask-re (and (featurep 'org-inlinetask)
1613 (boundp 'org-inlinetask-min-level)
1614 (boundp 'org-inlinetask-max-level)
1615 (format "^\\*\\{%d,%d\\}+ "
1616 org-inlinetask-min-level
1617 org-inlinetask-max-level)))
14031618 items struct)
14041619 (save-excursion
14051620 (catch :exit
14181633 ;; At a new item: end previous sibling.
14191634 ((looking-at item-re)
14201635 (let ((ind (save-excursion (skip-chars-forward " \t")
1421 (current-column))))
1636 (org-current-text-column))))
14221637 (setq top-ind (min top-ind ind))
14231638 (while (and items (<= ind (nth 1 (car items))))
14241639 (let ((item (pop items)))
14521667 (t
14531668 (let ((ind (save-excursion
14541669 (skip-chars-forward " \t")
1455 (current-column)))
1670 (org-current-text-column)))
14561671 (end (save-excursion
14571672 (skip-chars-backward " \r\t\n")
14581673 (line-beginning-position 2))))
14681683 (re-search-forward
14691684 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
14701685 limit t)))
1471 ((and (looking-at org-drawer-regexp)
1686 ((and (looking-at org-element-drawer-re)
14721687 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
14731688 (forward-line))))))))
14741689
16241839 (save-excursion
16251840 ;; Beginning of section is the beginning of the first non-blank
16261841 ;; line after previous headline.
1627 (let ((begin (point))
1628 (end (progn (org-with-limited-levels (outline-next-heading))
1629 (point)))
1630 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1631 (line-beginning-position 2))))
1842 (let* ((begin (point))
1843 (end (progn (org-with-limited-levels (outline-next-heading))
1844 (point)))
1845 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1846 (line-beginning-position 2)))
1847 (robust-end (when (> (- pos-before-blank 2) begin)
1848 (- pos-before-blank 2)))
1849 (robust-begin (when robust-end begin))
1850 )
16321851 (list 'section
16331852 (list :begin begin
16341853 :end end
16351854 :contents-begin begin
16361855 :contents-end pos-before-blank
1856 :robust-begin robust-begin
1857 :robust-end robust-end
16371858 :post-blank (count-lines pos-before-blank end)
16381859 :post-affiliated begin)))))
16391860
16541875 their value.
16551876
16561877 Return a list whose CAR is `special-block' and CDR is a plist
1657 containing `:type', `:begin', `:end', `:contents-begin',
1658 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1878 containing `:type', `:parameters', `:begin', `:end',
1879 `:contents-begin', `:contents-end', `:post-blank' and
1880 `:post-affiliated' keywords.
16591881
16601882 Assume point is at the beginning of the block."
16611883 (let* ((case-fold-search t)
1662 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1663 (match-string-no-properties 1))))
1884 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)[ \t]*\\(.*\\)[ \t]*$")
1885 (match-string-no-properties 1)))
1886 (parameters (match-string-no-properties 2)))
16641887 (if (not (save-excursion
16651888 (re-search-forward
16661889 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
16841907 (list 'special-block
16851908 (nconc
16861909 (list :type type
1910 :parameters (and (org-string-nw-p parameters)
1911 (org-trim parameters))
16871912 :begin begin
16881913 :end end
16891914 :contents-begin contents-begin
16951920 (defun org-element-special-block-interpreter (special-block contents)
16961921 "Interpret SPECIAL-BLOCK element as Org syntax.
16971922 CONTENTS is the contents of the element."
1698 (let ((block-type (org-element-property :type special-block)))
1699 (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
1923 (let ((block-type (org-element-property :type special-block))
1924 (parameters (org-element-property :parameters special-block)))
1925 (format "#+begin_%s%s\n%s#+end_%s" block-type
1926 (if parameters (concat " " parameters) "")
1927 (or contents "") block-type)))
17001928
17011929
17021930
21532381 (defun org-element-fixed-width-interpreter (fixed-width _)
21542382 "Interpret FIXED-WIDTH element as Org syntax."
21552383 (let ((value (org-element-property :value fixed-width)))
2156 (and value (replace-regexp-in-string "^" ": " value))))
2384 (and value
2385 (if (string-empty-p value) ":\n"
2386 (replace-regexp-in-string "^" ": " value)))))
21572387
21582388
21592389 ;;;; Horizontal Rule
22102440 (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
22112441 (upcase (match-string-no-properties 1))))
22122442 (value (org-trim (buffer-substring-no-properties
2213 (match-end 0) (point-at-eol))))
2443 (match-end 0) (line-end-position))))
22142444 (pos-before-blank (progn (forward-line) (point)))
22152445 (end (progn (skip-chars-forward " \r\t\n" limit)
22162446 (if (eobp) (point) (line-beginning-position)))))
22312461 (org-element-property :value keyword)))
22322462
22332463
2234 ;;;; Latex Environment
2464 ;;;; LaTeX Environment
22352465
22362466 (defconst org-element--latex-begin-environment
22372467 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
23522582 ((not (and (re-search-forward
23532583 org-element-paragraph-separate limit 'move)
23542584 (progn (beginning-of-line) t))))
2355 ((looking-at org-drawer-regexp)
2585 ((looking-at org-element-drawer-re)
23562586 (save-excursion
23572587 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
23582588 ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
24172647 (end (point))
24182648 closed deadline scheduled)
24192649 (goto-char begin)
2420 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2421 (goto-char (match-end 1))
2650 (while (re-search-forward org-element-planning-keywords-re end t)
24222651 (skip-chars-forward " \t" end)
2423 (let ((keyword (match-string 1))
2652 (let ((keyword (match-string 0))
24242653 (time (org-element-timestamp-parser)))
2425 (cond ((equal keyword org-closed-string) (setq closed time))
2426 ((equal keyword org-deadline-string) (setq deadline time))
2427 (t (setq scheduled time)))))
2654 (cond
2655 ((equal keyword org-element-closed-keyword) (setq closed time))
2656 ((equal keyword org-element-deadline-keyword) (setq deadline time))
2657 (t (setq scheduled time)))))
24282658 (list 'planning
24292659 (list :closed closed
24302660 :deadline deadline
24412671 (delq nil
24422672 (list (let ((deadline (org-element-property :deadline planning)))
24432673 (when deadline
2444 (concat org-deadline-string " "
2674 (concat org-element-deadline-keyword " "
24452675 (org-element-timestamp-interpreter deadline nil))))
24462676 (let ((scheduled (org-element-property :scheduled planning)))
24472677 (when scheduled
2448 (concat org-scheduled-string " "
2678 (concat org-element-scheduled-keyword " "
24492679 (org-element-timestamp-interpreter scheduled nil))))
24502680 (let ((closed (org-element-property :closed planning)))
24512681 (when closed
2452 (concat org-closed-string " "
2682 (concat org-element-closed-keyword " "
24532683 (org-element-timestamp-interpreter closed nil))))))
24542684 " "))
24552685
27442974
27452975 ;;;; Bold
27462976
2977 (defun org-element--parse-generic-emphasis (mark type)
2978 "Parse emphasis object at point, if any.
2979
2980 MARK is the delimiter string used. TYPE is a symbol among
2981 `bold', `code', `italic', `strike-through', `underline', and
2982 `verbatim'.
2983
2984 Assume point is at first MARK."
2985 (save-excursion
2986 (let ((origin (point)))
2987 (unless (bolp) (forward-char -1))
2988 (let ((opening-re
2989 (rx-to-string
2990 `(seq (or line-start (any space ?- ?\( ?' ?\" ?\{))
2991 ,mark
2992 (not space)))))
2993 (when (looking-at opening-re)
2994 (goto-char (1+ origin))
2995 (let ((closing-re
2996 (rx-to-string
2997 `(seq
2998 (not space)
2999 (group ,mark)
3000 (or (any space ?- ?. ?, ?\; ?: ?! ?? ?' ?\" ?\) ?\} ?\\ ?\[)
3001 line-end)))))
3002 (when (re-search-forward closing-re nil t)
3003 (let ((closing (match-end 1)))
3004 (goto-char closing)
3005 (let* ((post-blank (skip-chars-forward " \t"))
3006 (contents-begin (1+ origin))
3007 (contents-end (1- closing)))
3008 (list type
3009 (append
3010 (list :begin origin
3011 :end (point)
3012 :post-blank post-blank)
3013 (if (memq type '(code verbatim))
3014 (list :value
3015 (and (memq type '(code verbatim))
3016 (buffer-substring
3017 contents-begin contents-end)))
3018 (list :contents-begin contents-begin
3019 :contents-end contents-end)))))))))))))
3020
27473021 (defun org-element-bold-parser ()
27483022 "Parse bold object at point, if any.
27493023
27533027 nil.
27543028
27553029 Assume point is at the first star marker."
2756 (save-excursion
2757 (unless (bolp) (backward-char 1))
2758 (when (looking-at org-emph-re)
2759 (let ((begin (match-beginning 2))
2760 (contents-begin (match-beginning 4))
2761 (contents-end (match-end 4))
2762 (post-blank (progn (goto-char (match-end 2))
2763 (skip-chars-forward " \t")))
2764 (end (point)))
2765 (list 'bold
2766 (list :begin begin
2767 :end end
2768 :contents-begin contents-begin
2769 :contents-end contents-end
2770 :post-blank post-blank))))))
3030 (org-element--parse-generic-emphasis "*" 'bold))
27713031
27723032 (defun org-element-bold-interpreter (_ contents)
27733033 "Interpret bold object as Org syntax.
29083168 keywords. Otherwise, return nil.
29093169
29103170 Assume point is at the first tilde marker."
2911 (save-excursion
2912 (unless (bolp) (backward-char 1))
2913 (when (looking-at org-verbatim-re)
2914 (let ((begin (match-beginning 2))
2915 (value (match-string-no-properties 4))
2916 (post-blank (progn (goto-char (match-end 2))
2917 (skip-chars-forward " \t")))
2918 (end (point)))
2919 (list 'code
2920 (list :value value
2921 :begin begin
2922 :end end
2923 :post-blank post-blank))))))
3171 (org-element--parse-generic-emphasis "~" 'code))
29243172
29253173 (defun org-element-code-interpreter (code _)
29263174 "Interpret CODE object as Org syntax."
29853233 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
29863234 (setq contents-end
29873235 (save-match-data (goto-char (match-end 0))
2988 (re-search-forward "@@" nil t)
2989 (match-beginning 0))))
3236 (when
3237 (re-search-forward "@@" nil t)
3238 (match-beginning 0)))))
29903239 (let* ((begin (match-beginning 0))
29913240 (back-end (match-string-no-properties 1))
29923241 (value (buffer-substring-no-properties
31543403 nil.
31553404
31563405 Assume point is at the first slash marker."
3157 (save-excursion
3158 (unless (bolp) (backward-char 1))
3159 (when (looking-at org-emph-re)
3160 (let ((begin (match-beginning 2))
3161 (contents-begin (match-beginning 4))
3162 (contents-end (match-end 4))
3163 (post-blank (progn (goto-char (match-end 2))
3164 (skip-chars-forward " \t")))
3165 (end (point)))
3166 (list 'italic
3167 (list :begin begin
3168 :end end
3169 :contents-begin contents-begin
3170 :contents-end contents-end
3171 :post-blank post-blank))))))
3406 (org-element--parse-generic-emphasis "/" 'italic))
31723407
31733408 (defun org-element-italic-interpreter (_ contents)
31743409 "Interpret italic object as Org syntax.
31763411 (format "/%s/" contents))
31773412
31783413
3179 ;;;; Latex Fragment
3414 ;;;; LaTeX Fragment
31803415
31813416 (defun org-element-latex-fragment-parser ()
31823417 "Parse LaTeX fragment at point, if any.
32763511 (setq path (match-string-no-properties 1))
32773512 (setq contents-begin (match-beginning 1))
32783513 (setq contents-end (match-end 1)))
3279 ;; Type 2: Standard link, i.e. [[https://orgmode.org][homepage]]
3514 ;; Type 2: Standard link, i.e. [[https://orgmode.org][website]]
32803515 ((looking-at org-link-bracket-re)
32813516 (setq format 'bracket)
32823517 (setq contents-begin (match-beginning 2))
35343769 Otherwise, return nil.
35353770
35363771 Assume point is at the first plus sign marker."
3537 (save-excursion
3538 (unless (bolp) (backward-char 1))
3539 (when (looking-at org-emph-re)
3540 (let ((begin (match-beginning 2))
3541 (contents-begin (match-beginning 4))
3542 (contents-end (match-end 4))
3543 (post-blank (progn (goto-char (match-end 2))
3544 (skip-chars-forward " \t")))
3545 (end (point)))
3546 (list 'strike-through
3547 (list :begin begin
3548 :end end
3549 :contents-begin contents-begin
3550 :contents-end contents-end
3551 :post-blank post-blank))))))
3772 (org-element--parse-generic-emphasis "+" 'strike-through))
35523773
35533774 (defun org-element-strike-through-interpreter (_ contents)
35543775 "Interpret strike-through object as Org syntax.
37143935 (activep (eq (char-after) ?<))
37153936 (raw-value
37163937 (progn
3717 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3938 (looking-at (concat "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\("
3939 org-ts-regexp-both
3940 "\\)\\)?"))
37183941 (match-string-no-properties 0)))
37193942 (date-start (match-string-no-properties 1))
37203943 (date-end (match-string 3))
38224045 ;; the repeater string, if any.
38234046 (lambda (time activep &optional with-time-p hour-end minute-end)
38244047 (let ((ts (format-time-string
3825 (funcall (if with-time-p #'cdr #'car)
3826 org-time-stamp-formats)
4048 (org-time-stamp-format with-time-p)
38274049 time)))
38284050 (when (and hour-end minute-end)
38294051 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
38524074 (/= minute-start minute-end)))))
38534075 (funcall
38544076 build-ts-string
3855 (encode-time 0
3856 (or minute-start 0)
3857 (or hour-start 0)
3858 (org-element-property :day-start timestamp)
3859 (org-element-property :month-start timestamp)
3860 (org-element-property :year-start timestamp))
4077 (org-encode-time 0
4078 (or minute-start 0)
4079 (or hour-start 0)
4080 (org-element-property :day-start timestamp)
4081 (org-element-property :month-start timestamp)
4082 (org-element-property :year-start timestamp))
38614083 (eq type 'active)
38624084 (and hour-start minute-start)
38634085 (and time-range-p hour-end)
38694091 (hour-end (org-element-property :hour-end timestamp)))
38704092 (concat
38714093 (funcall
3872 build-ts-string (encode-time
4094 build-ts-string (org-encode-time
38734095 0
38744096 (or minute-start 0)
38754097 (or hour-start 0)
38804102 (and hour-start minute-start))
38814103 "--"
38824104 (funcall build-ts-string
3883 (encode-time 0
3884 (or minute-end 0)
3885 (or hour-end 0)
3886 (org-element-property :day-end timestamp)
3887 (org-element-property :month-end timestamp)
3888 (org-element-property :year-end timestamp))
4105 (org-encode-time
4106 0
4107 (or minute-end 0)
4108 (or hour-end 0)
4109 (org-element-property :day-end timestamp)
4110 (org-element-property :month-end timestamp)
4111 (org-element-property :year-end timestamp))
38894112 (eq type 'active-range)
38904113 (and hour-end minute-end)))))
38914114 (_ (org-element-property :raw-value timestamp)))))
39024125 Otherwise, return nil.
39034126
39044127 Assume point is at the first underscore marker."
3905 (save-excursion
3906 (unless (bolp) (backward-char 1))
3907 (when (looking-at org-emph-re)
3908 (let ((begin (match-beginning 2))
3909 (contents-begin (match-beginning 4))
3910 (contents-end (match-end 4))
3911 (post-blank (progn (goto-char (match-end 2))
3912 (skip-chars-forward " \t")))
3913 (end (point)))
3914 (list 'underline
3915 (list :begin begin
3916 :end end
3917 :contents-begin contents-begin
3918 :contents-end contents-end
3919 :post-blank post-blank))))))
4128 (org-element--parse-generic-emphasis "_" 'underline))
39204129
39214130 (defun org-element-underline-interpreter (_ contents)
39224131 "Interpret underline object as Org syntax.
39344143 `:post-blank' keywords. Otherwise, return nil.
39354144
39364145 Assume point is at the first equal sign marker."
3937 (save-excursion
3938 (unless (bolp) (backward-char 1))
3939 (when (looking-at org-verbatim-re)
3940 (let ((begin (match-beginning 2))
3941 (value (match-string-no-properties 4))
3942 (post-blank (progn (goto-char (match-end 2))
3943 (skip-chars-forward " \t")))
3944 (end (point)))
3945 (list 'verbatim
3946 (list :value value
3947 :begin begin
3948 :end end
3949 :post-blank post-blank))))))
4146 (org-element--parse-generic-emphasis "=" 'verbatim))
39504147
39514148 (defun org-element-verbatim-interpreter (verbatim _)
39524149 "Interpret VERBATIM object as Org syntax."
39604157 ;; It returns the Lisp representation of the element starting at
39614158 ;; point.
39624159
3963 (defun org-element--current-element (limit &optional granularity mode structure)
4160 (defvar org-element--cache-sync-requests); Declared later
4161 (defun org-element--current-element (limit &optional granularity mode structure add-to-cache)
39644162 "Parse the element starting at point.
39654163
39664164 Return value is a list like (TYPE PROPS) where TYPE is the type
39854183 If STRUCTURE isn't provided but MODE is set to `item', it will be
39864184 computed.
39874185
4186 Optional argument ADD-TO-CACHE, when non-nil, and when cache is active,
4187 will also add current element to cache if it is not yet there. Use
4188 this argument with care, as validity of the element in parse tree is
4189 not checked.
4190
39884191 This function assumes point is always at the beginning of the
39894192 element it has to parse."
3990 (save-excursion
3991 (let ((case-fold-search t)
3992 ;; Determine if parsing depth allows for secondary strings
3993 ;; parsing. It only applies to elements referenced in
3994 ;; `org-element-secondary-value-alist'.
3995 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3996 (cond
3997 ;; Item.
3998 ((eq mode 'item)
3999 (org-element-item-parser limit structure raw-secondary-p))
4000 ;; Table Row.
4001 ((eq mode 'table-row) (org-element-table-row-parser limit))
4002 ;; Node Property.
4003 ((eq mode 'node-property) (org-element-node-property-parser limit))
4004 ;; Headline.
4005 ((org-with-limited-levels (org-at-heading-p))
4006 (org-element-headline-parser limit raw-secondary-p))
4007 ;; Sections (must be checked after headline).
4008 ((eq mode 'section) (org-element-section-parser limit))
4009 ((eq mode 'first-section)
4010 (org-element-section-parser
4011 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
4012 limit)))
4013 ;; Comments.
4014 ((looking-at "^[ \t]*#\\(?: \\|$\\)")
4015 (org-element-comment-parser limit))
4016 ;; Planning.
4017 ((and (eq mode 'planning)
4018 (eq ?* (char-after (line-beginning-position 0)))
4019 (looking-at org-planning-line-re))
4020 (org-element-planning-parser limit))
4021 ;; Property drawer.
4022 ((and (pcase mode
4023 (`planning (eq ?* (char-after (line-beginning-position 0))))
4024 ((or `property-drawer `top-comment)
4025 (save-excursion
4026 (beginning-of-line 0)
4027 (not (looking-at "[[:blank:]]*$"))))
4028 (_ nil))
4029 (looking-at org-property-drawer-re))
4030 (org-element-property-drawer-parser limit))
4031 ;; When not at bol, point is at the beginning of an item or
4032 ;; a footnote definition: next item is always a paragraph.
4033 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
4034 ;; Clock.
4035 ((looking-at org-clock-line-re) (org-element-clock-parser limit))
4036 ;; Inlinetask.
4037 ((looking-at "^\\*+ ")
4038 (org-element-inlinetask-parser limit raw-secondary-p))
4039 ;; From there, elements can have affiliated keywords.
4040 (t (let ((affiliated (org-element--collect-affiliated-keywords
4041 limit (memq granularity '(nil object)))))
4042 (cond
4043 ;; Jumping over affiliated keywords put point off-limits.
4044 ;; Parse them as regular keywords.
4045 ((and (cdr affiliated) (>= (point) limit))
4046 (goto-char (car affiliated))
4047 (org-element-keyword-parser limit nil))
4048 ;; LaTeX Environment.
4049 ((looking-at org-element--latex-begin-environment)
4050 (org-element-latex-environment-parser limit affiliated))
4051 ;; Drawer.
4052 ((looking-at org-drawer-regexp)
4053 (org-element-drawer-parser limit affiliated))
4054 ;; Fixed Width
4055 ((looking-at "[ \t]*:\\( \\|$\\)")
4056 (org-element-fixed-width-parser limit affiliated))
4057 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
4058 ;; Keywords.
4059 ((looking-at "[ \t]*#\\+")
4060 (goto-char (match-end 0))
4061 (cond
4062 ((looking-at "BEGIN_\\(\\S-+\\)")
4063 (beginning-of-line)
4064 (funcall (pcase (upcase (match-string 1))
4065 ("CENTER" #'org-element-center-block-parser)
4066 ("COMMENT" #'org-element-comment-block-parser)
4067 ("EXAMPLE" #'org-element-example-block-parser)
4068 ("EXPORT" #'org-element-export-block-parser)
4069 ("QUOTE" #'org-element-quote-block-parser)
4070 ("SRC" #'org-element-src-block-parser)
4071 ("VERSE" #'org-element-verse-block-parser)
4072 (_ #'org-element-special-block-parser))
4073 limit
4074 affiliated))
4075 ((looking-at "CALL:")
4076 (beginning-of-line)
4077 (org-element-babel-call-parser limit affiliated))
4078 ((looking-at "BEGIN:? ")
4079 (beginning-of-line)
4080 (org-element-dynamic-block-parser limit affiliated))
4081 ((looking-at "\\S-+:")
4082 (beginning-of-line)
4083 (org-element-keyword-parser limit affiliated))
4084 (t
4085 (beginning-of-line)
4086 (org-element-paragraph-parser limit affiliated))))
4087 ;; Footnote Definition.
4088 ((looking-at org-footnote-definition-re)
4089 (org-element-footnote-definition-parser limit affiliated))
4090 ;; Horizontal Rule.
4091 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
4092 (org-element-horizontal-rule-parser limit affiliated))
4093 ;; Diary Sexp.
4094 ((looking-at "%%(")
4095 (org-element-diary-sexp-parser limit affiliated))
4096 ;; Table.
4097 ((or (looking-at "[ \t]*|")
4098 ;; There is no strict definition of a table.el
4099 ;; table. Try to prevent false positive while being
4100 ;; quick.
4101 (let ((rule-regexp
4102 (rx (zero-or-more (any " \t"))
4103 "+"
4104 (one-or-more (one-or-more "-") "+")
4105 (zero-or-more (any " \t"))
4106 eol))
4107 (non-table.el-line
4108 (rx bol
4109 (zero-or-more (any " \t"))
4110 (or eol (not (any "+| \t")))))
4111 (next (line-beginning-position 2)))
4112 ;; Start with a full rule.
4113 (and
4114 (looking-at rule-regexp)
4115 (< next limit) ;no room for a table.el table
4193 (let* ((element (and (not (buffer-narrowed-p))
4194 (org-element--cache-active-p)
4195 (not org-element--cache-sync-requests)
4196 (org-element--cache-find (point) t)))
4197 (element (progn (while (and element
4198 (not (and (eq (point) (org-element-property :begin element))
4199 (eq mode (org-element-property :mode element)))))
4200 (setq element (org-element-property :parent element)))
4201 element))
4202 (old-element element)
4203 (element (when
4204 (pcase (org-element-property :granularity element)
4205 (`nil t)
4206 (`object t)
4207 (`element (not (memq granularity '(nil object))))
4208 (`greater-element (not (memq granularity '(nil object element))))
4209 (`headline (eq granularity 'headline)))
4210 element)))
4211 (if element
4212 element
4213 (save-excursion
4214 (let ((case-fold-search t)
4215 ;; Determine if parsing depth allows for secondary strings
4216 ;; parsing. It only applies to elements referenced in
4217 ;; `org-element-secondary-value-alist'.
4218 (raw-secondary-p (and granularity (not (eq granularity 'object))))
4219 result)
4220 (setq
4221 result
4222 (cond
4223 ;; Item.
4224 ((eq mode 'item)
4225 (org-element-item-parser limit structure raw-secondary-p))
4226 ;; Table Row.
4227 ((eq mode 'table-row) (org-element-table-row-parser limit))
4228 ;; Node Property.
4229 ((eq mode 'node-property) (org-element-node-property-parser limit))
4230 ;; Headline.
4231 ((org-with-limited-levels (looking-at-p org-outline-regexp-bol))
4232 (org-element-headline-parser limit raw-secondary-p))
4233 ;; Sections (must be checked after headline).
4234 ((eq mode 'section) (org-element-section-parser limit))
4235 ((eq mode 'first-section)
4236 (org-element-section-parser
4237 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
4238 limit)))
4239 ;; Comments.
4240 ((looking-at "^[ \t]*#\\(?: \\|$\\)")
4241 (org-element-comment-parser limit))
4242 ;; Planning.
4243 ((and (eq mode 'planning)
4244 (eq ?* (char-after (line-beginning-position 0)))
4245 (looking-at org-element-planning-line-re))
4246 (org-element-planning-parser limit))
4247 ;; Property drawer.
4248 ((and (pcase mode
4249 (`planning (eq ?* (char-after (line-beginning-position 0))))
4250 ((or `property-drawer `top-comment)
41164251 (save-excursion
4117 (end-of-line)
4118 (cond
4119 ;; Must end with a full rule.
4120 ((not (re-search-forward non-table.el-line limit 'move))
4121 (if (bolp) (forward-line -1) (beginning-of-line))
4122 (looking-at rule-regexp))
4123 ;; Ignore pseudo-tables with a single
4124 ;; rule.
4125 ((= next (line-beginning-position))
4126 nil)
4127 ;; Must end with a full rule.
4128 (t
4129 (forward-line -1)
4130 (looking-at rule-regexp)))))))
4131 (org-element-table-parser limit affiliated))
4132 ;; List.
4133 ((looking-at (org-item-re))
4134 (org-element-plain-list-parser
4135 limit affiliated
4136 (or structure (org-element--list-struct limit))))
4137 ;; Default element: Paragraph.
4138 (t (org-element-paragraph-parser limit affiliated)))))))))
4252 (beginning-of-line 0)
4253 (not (looking-at "[[:blank:]]*$"))))
4254 (_ nil))
4255 (looking-at org-property-drawer-re))
4256 (org-element-property-drawer-parser limit))
4257 ;; When not at bol, point is at the beginning of an item or
4258 ;; a footnote definition: next item is always a paragraph.
4259 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
4260 ;; Clock.
4261 ((looking-at org-element-clock-line-re)
4262 (org-element-clock-parser limit))
4263 ;; Inlinetask.
4264 ((looking-at "^\\*+ ")
4265 (org-element-inlinetask-parser limit raw-secondary-p))
4266 ;; From there, elements can have affiliated keywords.
4267 (t (let ((affiliated (org-element--collect-affiliated-keywords
4268 limit (memq granularity '(nil object)))))
4269 (cond
4270 ;; Jumping over affiliated keywords put point off-limits.
4271 ;; Parse them as regular keywords.
4272 ((and (cdr affiliated) (>= (point) limit))
4273 (goto-char (car affiliated))
4274 (org-element-keyword-parser limit nil))
4275 ;; LaTeX Environment.
4276 ((looking-at org-element--latex-begin-environment)
4277 (org-element-latex-environment-parser limit affiliated))
4278 ;; Drawer.
4279 ((looking-at org-element-drawer-re)
4280 (org-element-drawer-parser limit affiliated))
4281 ;; Fixed Width
4282 ((looking-at "[ \t]*:\\( \\|$\\)")
4283 (org-element-fixed-width-parser limit affiliated))
4284 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
4285 ;; Keywords.
4286 ((looking-at "[ \t]*#\\+")
4287 (goto-char (match-end 0))
4288 (cond
4289 ((looking-at "BEGIN_\\(\\S-+\\)")
4290 (beginning-of-line)
4291 (funcall (pcase (upcase (match-string 1))
4292 ("CENTER" #'org-element-center-block-parser)
4293 ("COMMENT" #'org-element-comment-block-parser)
4294 ("EXAMPLE" #'org-element-example-block-parser)
4295 ("EXPORT" #'org-element-export-block-parser)
4296 ("QUOTE" #'org-element-quote-block-parser)
4297 ("SRC" #'org-element-src-block-parser)
4298 ("VERSE" #'org-element-verse-block-parser)
4299 (_ #'org-element-special-block-parser))
4300 limit
4301 affiliated))
4302 ((looking-at "CALL:")
4303 (beginning-of-line)
4304 (org-element-babel-call-parser limit affiliated))
4305 ((save-excursion
4306 (beginning-of-line)
4307 (looking-at org-element-dynamic-block-open-re))
4308 (beginning-of-line)
4309 (org-element-dynamic-block-parser limit affiliated))
4310 ((looking-at "\\S-+:")
4311 (beginning-of-line)
4312 (org-element-keyword-parser limit affiliated))
4313 (t
4314 (beginning-of-line)
4315 (org-element-paragraph-parser limit affiliated))))
4316 ;; Footnote Definition.
4317 ((looking-at org-footnote-definition-re)
4318 (org-element-footnote-definition-parser limit affiliated))
4319 ;; Horizontal Rule.
4320 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
4321 (org-element-horizontal-rule-parser limit affiliated))
4322 ;; Diary Sexp.
4323 ((looking-at "%%(")
4324 (org-element-diary-sexp-parser limit affiliated))
4325 ;; Table.
4326 ((or (looking-at "[ \t]*|")
4327 ;; There is no strict definition of a table.el
4328 ;; table. Try to prevent false positive while being
4329 ;; quick.
4330 (let ((rule-regexp
4331 (rx (zero-or-more (any " \t"))
4332 "+"
4333 (one-or-more (one-or-more "-") "+")
4334 (zero-or-more (any " \t"))
4335 eol))
4336 (non-table.el-line
4337 (rx bol
4338 (zero-or-more (any " \t"))
4339 (or eol (not (any "+| \t")))))
4340 (next (line-beginning-position 2)))
4341 ;; Start with a full rule.
4342 (and
4343 (looking-at rule-regexp)
4344 (< next limit) ;no room for a table.el table
4345 (save-excursion
4346 (end-of-line)
4347 (cond
4348 ;; Must end with a full rule.
4349 ((not (re-search-forward non-table.el-line limit 'move))
4350 (if (bolp) (forward-line -1) (beginning-of-line))
4351 (looking-at rule-regexp))
4352 ;; Ignore pseudo-tables with a single
4353 ;; rule.
4354 ((= next (line-beginning-position))
4355 nil)
4356 ;; Must end with a full rule.
4357 (t
4358 (forward-line -1)
4359 (looking-at rule-regexp)))))))
4360 (org-element-table-parser limit affiliated))
4361 ;; List.
4362 ((looking-at (org-item-re))
4363 (org-element-plain-list-parser
4364 limit affiliated
4365 (or structure (org-element--list-struct limit))))
4366 ;; Default element: Paragraph.
4367 (t (org-element-paragraph-parser limit affiliated)))))))
4368 (when result
4369 (org-element-put-property result :mode mode)
4370 (org-element-put-property result :granularity granularity))
4371 (when (and (not (buffer-narrowed-p))
4372 (org-element--cache-active-p)
4373 (not org-element--cache-sync-requests)
4374 add-to-cache)
4375 (if (not old-element)
4376 (setq result (org-element--cache-put result))
4377 (org-element-set-element old-element result)
4378 (setq result old-element)))
4379 result)))))
41394380
41404381
41414382 ;; Most elements can have affiliated keywords. When looking for an
42764517 This function assumes that current major mode is `org-mode'."
42774518 (save-excursion
42784519 (goto-char (point-min))
4279 (org-skip-whitespace)
4280 (org-element--parse-elements
4281 (point-at-bol) (point-max)
4282 ;; Start in `first-section' mode so text before the first
4283 ;; headline belongs to a section.
4284 'first-section nil granularity visible-only (list 'org-data nil))))
4520 (let ((org-data (org-element-org-data-parser))
4521 (gc-cons-threshold #x40000000))
4522 (org-skip-whitespace)
4523 (org-element--parse-elements
4524 (line-beginning-position) (point-max)
4525 ;; Start in `first-section' mode so text before the first
4526 ;; headline belongs to a section.
4527 'first-section nil granularity visible-only org-data))))
42854528
42864529 (defun org-element-parse-secondary-string (string restriction &optional parent)
42874530 "Recursively parse objects in STRING and return structure.
43174560 (data types fun &optional info first-match no-recursion with-affiliated)
43184561 "Map a function on selected elements or objects.
43194562
4320 DATA is a parse tree, an element, an object, a string, or a list
4321 of such constructs. TYPES is a symbol or list of symbols of
4322 elements or objects types (see `org-element-all-elements' and
4323 `org-element-all-objects' for a complete list of types). FUN is
4324 the function called on the matching element or object. It has to
4325 accept one argument: the element or object itself.
4563 DATA is a parse tree (for example, returned by
4564 `org-element-parse-buffer'), an element, an object, a string, or a
4565 list of such constructs. TYPES is a symbol or list of symbols of
4566 elements or object types (see `org-element-all-elements' and
4567 `org-element-all-objects' for a complete list of types). FUN is the
4568 function called on the matching element or object. It has to accept
4569 one argument: the element or object itself.
43264570
43274571 When optional argument INFO is non-nil, it should be a plist
43284572 holding export options. In that case, parts of the parse tree
43504594 the following example will return a flat list of all `src-block'
43514595 and `example-block' elements in it:
43524596
4597 (setq tree (org-element-parse-buffer))
43534598 (org-element-map tree \\='(example-block src-block) #\\='identity)
43544599
43554600 The following snippet will find the first headline with a level
43964641 ;; every element it encounters.
43974642 (and (not (eq category 'elements))
43984643 (setq category 'elements))))))))
4644 (--ignore-list (plist-get info :ignore-list))
43994645 --acc)
44004646 (letrec ((--walk-tree
44014647 (lambda (--data)
44054651 (cond
44064652 ((not --data))
44074653 ;; Ignored element in an export context.
4408 ((and info (memq --data (plist-get info :ignore-list))))
4654 ((and info (memq --data --ignore-list)))
44094655 ;; List of elements or objects.
44104656 ((not --type) (mapc --walk-tree --data))
44114657 ;; Unconditionally enter parse trees.
44964742 (pcase type
44974743 (`headline 'section)
44984744 ((and (guard (eq mode 'first-section)) `section) 'top-comment)
4745 ((and (guard (eq mode 'org-data)) `org-data) 'first-section)
4746 ((and (guard (not mode)) `org-data) 'first-section)
44994747 (`inlinetask 'planning)
45004748 (`plain-list 'item)
45014749 (`property-drawer 'node-property)
45404788 (when (and (eolp) (not (eobp))) (forward-char)))
45414789 ;; Find current element's type and parse it accordingly to
45424790 ;; its category.
4543 (let* ((element (org-element--current-element
4544 end granularity mode structure))
4791 (let* ((element (org-element-copy
4792 ;; `org-element--current-element' may return cached
4793 ;; elements. Below code reassigns
4794 ;; `:parent' property of the element and
4795 ;; may interfere with cache
4796 ;; synchronization if parent element is not
4797 ;; yet in cache. Moreover, the returned
4798 ;; structure may be altered by caller code
4799 ;; arbitrarily. Hence, we return a copy of
4800 ;; the potentially cached element to make
4801 ;; potential modifications safe for element
4802 ;; cache.
4803 (org-element--current-element
4804 end granularity mode structure)))
45454805 (type (org-element-type element))
45464806 (cbeg (org-element-property :contents-begin element)))
45474807 (goto-char (org-element-property :end element))
45754835 ;; Update mode.
45764836 (setq mode (org-element--next-mode mode type nil)))))
45774837 ;; Return result.
4838 (org-element-put-property acc :granularity granularity)
45784839 (apply #'org-element-set-contents acc (nreverse elements)))))
45794840
45804841 (defun org-element--object-lex (restriction)
49935254
49945255 ;;; Cache
49955256 ;;
4996 ;; Implement a caching mechanism for `org-element-at-point' and
4997 ;; `org-element-context', which see.
5257 ;; Implement a caching mechanism for `org-element-at-point', `org-element-context', and for
5258 ;; fast mapping across Org elements in `org-element-cache-map', which see.
49985259 ;;
4999 ;; A single public function is provided: `org-element-cache-reset'.
5260 ;; When cache is enabled, the elements returned by `org-element-at-point' and
5261 ;; `org-element-context' are returned by reference. Altering these elements will
5262 ;; also alter their cache representation. The same is true for
5263 ;; elements passed to mapping function in `org-element-cache-map'.
50005264 ;;
5001 ;; Cache is disabled by default for now because it sometimes triggers
5002 ;; freezes, but it can be enabled globally with
5003 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
5004 ;; `org-element-cache-sync-duration' and
5005 ;; `org-element-cache-sync-break' can be tweaked to control caching
5006 ;; behavior.
5265 ;; Public functions are: `org-element-cache-reset', `org-element-cache-refresh', and
5266 ;; `org-element-cache-map'.
5267 ;;
5268 ;; Cache can be controlled using `org-element-use-cache' and `org-element-cache-persistent'.
5269 ;; `org-element-cache-sync-idle-time', `org-element-cache-sync-duration' and
5270 ;; `org-element-cache-sync-break' can be tweaked to control caching behavior.
50075271 ;;
50085272 ;; Internally, parsed elements are stored in an AVL tree,
50095273 ;; `org-element--cache'. This tree is updated lazily: whenever
50355299 ;; associated to a key, obtained with `org-element--cache-key'. This
50365300 ;; mechanism is robust enough to preserve total order among elements
50375301 ;; even when the tree is only partially synchronized.
5038
5039
5040 (defvar org-element-use-cache nil
5041 "Non-nil when Org parser should cache its results.
5042
5043 WARNING: for the time being, using cache sometimes triggers
5044 freezes. Therefore, it is disabled by default. Activate it if
5045 you want to help debugging the issue.")
5302 ;;
5303 ;; The cache code debugging is fairly complex because cache request
5304 ;; state is often hard to reproduce. An extensive diagnostics
5305 ;; functionality is built into the cache code to assist hunting bugs.
5306 ;; See `org-element--cache-self-verify', `org-element--cache-self-verify-frequency',
5307 ;; `org-element--cache-diagnostics', `org-element--cache-diagnostics-level',
5308 ;; `org-element--cache-diagnostics-ring-size', `org-element--cache-map-statistics',
5309 ;; `org-element--cache-map-statistics-threshold'.
5310
5311 ;;;###autoload
5312 (defvar org-element-use-cache t
5313 "Non-nil when Org parser should cache its results.")
5314
5315 (defvar org-element-cache-persistent t
5316 "Non-nil when cache should persist between Emacs sessions.")
50465317
50475318 (defvar org-element-cache-sync-idle-time 0.6
50485319 "Length, in seconds, of idle time before syncing cache.")
50575328 "Duration, as a time value, of the pause between synchronizations.
50585329 See `org-element-cache-sync-duration' for more information.")
50595330
5331 (defvar org-element--cache-self-verify nil
5332 "Activate extra consistency checks for the cache.
5333
5334 This may cause serious performance degradation depending on the value
5335 of `org-element--cache-self-verify-frequency'.
5336
5337 When set to symbol `backtrace', record and display backtrace log if
5338 any inconsistency is detected.")
5339
5340 (defvar org-element--cache-self-verify-frequency 0.03
5341 "Frequency of cache element verification.
5342
5343 This number is a probability to check an element requested from cache
5344 to be correct. Setting this to a value less than 0.0001 is useless.")
5345
5346 (defvar org-element--cache-diagnostics nil
5347 "Print detailed diagnostics of cache processing.")
5348
5349 (defvar org-element--cache-map-statistics nil
5350 "Print statistics for `org-element-cache-map'.")
5351
5352 (defvar org-element--cache-map-statistics-threshold 0.1
5353 "Time threshold in seconds to log statistics for `org-element-cache-map'.")
5354
5355 (defvar org-element--cache-diagnostics-level 2
5356 "Detail level of the diagnostics.")
5357
5358 (defvar-local org-element--cache-diagnostics-ring nil
5359 "Ring containing last `org-element--cache-diagnostics-ring-size'
5360 cache process log entries.")
5361
5362 (defvar org-element--cache-diagnostics-ring-size 5000
5363 "Size of `org-element--cache-diagnostics-ring'.")
50605364
50615365 ;;;; Data Structure
50625366
5063 (defvar org-element--cache nil
5367 (defvar-local org-element--cache nil
50645368 "AVL tree used to cache elements.
50655369 Each node of the tree contains an element. Comparison is done
50665370 with `org-element--cache-compare'. This cache is used in
50675371 `org-element-at-point'.")
50685372
5069 (defvar org-element--cache-sync-requests nil
5373 (defvar-local org-element--headline-cache nil
5374 "AVL tree used to cache headline and inlinetask elements.
5375 Each node of the tree contains an element. Comparison is done
5376 with `org-element--cache-compare'. This cache is used in
5377 `org-element-cache-map'.")
5378
5379 (defconst org-element--cache-hash-size 16
5380 "Cache size for recent cached calls to `org-element--cache-find'.
5381
5382 This extra caching is based on the following paper:
5383 Pugh [Information Processing Letters] (1990) Slow optimally balanced
5384 search strategies vs. cached fast uniformly balanced search
5385 strategies. http://dx.doi.org/10.1016/0020-0190(90)90130-P
5386
5387 Also, see `org-element--cache-hash-left' and `org-element--cache-hash-right'.")
5388 (defvar-local org-element--cache-hash-left nil
5389 "Cached elements from `org-element--cache' for fast O(1) lookup.
5390 When non-nil, it should be a vector representing POS arguments of
5391 `org-element--cache-find' called with nil SIDE argument.
5392 Also, see `org-element--cache-hash-size'.")
5393 (defvar-local org-element--cache-hash-right nil
5394 "Cached elements from `org-element--cache' for fast O(1) lookup.
5395 When non-nil, it should be a vector representing POS arguments of
5396 `org-element--cache-find' called with non-nil, non-`both' SIDE argument.
5397 Also, see `org-element--cache-hash-size'.")
5398
5399 (defvar org-element--cache-hash-statistics '(0 . 0)
5400 "Cons cell storing how Org makes use of `org-element--cache-find' caching.
5401 The car is the number of successful uses and cdr is the total calls to
5402 `org-element--cache-find'.")
5403 (defvar org-element--cache-hash-nocache 0
5404 "Number of calls to `org-element--cache-has' with `both' SIDE argument.
5405 These calls are not cached by hash. See `org-element--cache-hash-size'.")
5406
5407 (defvar-local org-element--cache-size 0
5408 "Size of the `org-element--cache'.
5409
5410 Storing value is variable is faster because `avl-tree-size' is O(N).")
5411
5412 (defvar-local org-element--headline-cache-size 0
5413 "Size of the `org-element--headline-cache'.
5414
5415 Storing value is variable is faster because `avl-tree-size' is O(N).")
5416
5417 (defvar-local org-element--cache-sync-requests nil
50705418 "List of pending synchronization requests.
50715419
50725420 A request is a vector with the following pattern:
50835431 removed, BEG and END is buffer position delimiting the
50845432 modifications. Elements starting between them (inclusive) are
50855433 removed. So are elements whose parent is removed. PARENT, when
5086 non-nil, is the parent of the first element to be removed.
5434 non-nil, is the common parent of all the elements between BEG and END.
5435
5436 It is guaranteed that only a single phase 0 request exists at any
5437 moment of time. If it does, it must be the first request in the list.
50875438
50885439 During phase 1, NEXT is the key of the next known element in
50895440 cache and BEG its beginning position. Parse buffer between that
50925443
50935444 During phase 2, NEXT is the key of the next element to shift in
50945445 the parse tree. All elements starting from this one have their
5095 properties relatives to buffer positions shifted by integer
5446 properties relative to buffer positions shifted by integer
50965447 OFFSET and, if they belong to element PARENT, are adopted by it.
50975448
5098 PHASE specifies the phase number, as an integer.")
5099
5100 (defvar org-element--cache-sync-timer nil
5449 PHASE specifies the phase number, as an integer.
5450
5451 For any synchronization request, all the later requests in the cache
5452 must not start at or before END. See `org-element--cache-submit-request'.")
5453
5454 (defvar-local org-element--cache-sync-timer nil
51015455 "Timer used for cache synchronization.")
51025456
5103 (defvar org-element--cache-sync-keys nil
5104 "Hash table used to store keys during synchronization.
5457 (defvar-local org-element--cache-sync-keys-value nil
5458 "Id value used to identify keys during synchronization.
51055459 See `org-element--cache-key' for more information.")
5460
5461 (defvar-local org-element--cache-change-tic nil
5462 "Last `buffer-chars-modified-tick' for registered changes.")
5463
5464 (defvar-local org-element--cache-last-buffer-size nil
5465 "Last value of `buffer-size' for registered changes.")
5466
5467 (defvar org-element--cache-non-modifying-commands
5468 '(org-agenda
5469 org-agenda-redo
5470 org-sparse-tree
5471 org-occur
5472 org-columns
5473 org-columns-redo
5474 org-columns-new
5475 org-columns-delete
5476 org-columns-compute
5477 org-columns-insert-dblock
5478 org-agenda-columns
5479 org-ctrl-c-ctrl-c)
5480 "List of commands that are not expected to change the cache state.
5481
5482 This variable is used to determine when re-parsing buffer is not going
5483 to slow down the command.
5484
5485 If the commands end up modifying the cache, the worst case scenario is
5486 performance drop. So, advicing these commands is safe. Yet, it is
5487 better to remove the commands advised in such a way from this list.")
5488
5489 (defmacro org-element--request-key (request)
5490 "Get NEXT part of a `org-element--cache-sync-requests' REQUEST."
5491 `(aref ,request 0))
5492
5493 (defmacro org-element--request-beg (request)
5494 "Get BEG part of a `org-element--cache-sync-requests' REQUEST."
5495 `(aref ,request 1))
5496
5497 (defmacro org-element--request-end (request)
5498 "Get END part of a `org-element--cache-sync-requests' REQUEST."
5499 `(aref ,request 2))
5500
5501 (defmacro org-element--request-offset (request)
5502 "Get OFFSET part of a `org-element--cache-sync-requests' REQUEST."
5503 `(aref ,request 3))
5504
5505 (defmacro org-element--request-parent (request)
5506 "Get PARENT part of a `org-element--cache-sync-requests' REQUEST."
5507 `(aref ,request 4))
5508
5509 (defmacro org-element--request-phase (request)
5510 "Get PHASE part of a `org-element--cache-sync-requests' REQUEST."
5511 `(aref ,request 5))
5512
5513 (defmacro org-element--format-element (element)
5514 "Format ELEMENT for printing in diagnostics."
5515 `(let ((print-length 50)
5516 (print-level 5))
5517 (prin1-to-string ,element)))
5518
5519 (defmacro org-element--cache-log-message (format-string &rest args)
5520 "Add a new log message for org-element-cache."
5521 `(when (or org-element--cache-diagnostics
5522 (eq org-element--cache-self-verify 'backtrace))
5523 (let* ((format-string (concat (format "org-element-cache diagnostics(%s): "
5524 (buffer-name (current-buffer)))
5525 ,format-string))
5526 (format-string (funcall #'format format-string ,@args)))
5527 (if org-element--cache-diagnostics
5528 (display-warning 'org-element-cache format-string)
5529 (unless org-element--cache-diagnostics-ring
5530 (setq org-element--cache-diagnostics-ring
5531 (make-ring org-element--cache-diagnostics-ring-size)))
5532 (ring-insert org-element--cache-diagnostics-ring format-string)))))
5533
5534 (defmacro org-element--cache-warn (format-string &rest args)
5535 "Raise warning for org-element-cache."
5536 `(let* ((format-string (funcall #'format ,format-string ,@args))
5537 (format-string
5538 (if (or (not org-element--cache-diagnostics-ring)
5539 (not (eq 'backtrace org-element--cache-self-verify)))
5540 format-string
5541 (prog1
5542 (concat (format "Warning(%s): "
5543 (buffer-name (current-buffer)))
5544 format-string
5545 "\nBacktrace:\n "
5546 (mapconcat #'identity
5547 (ring-elements org-element--cache-diagnostics-ring)
5548 "\n "))
5549 (setq org-element--cache-diagnostics-ring nil)))))
5550 (if (and (boundp 'org-batch-test) org-batch-test)
5551 (error "%s" (concat "org-element--cache: " format-string))
5552 (display-warning 'org-element-cache
5553 (concat "org-element--cache: " format-string)))))
51065554
51075555 (defsubst org-element--cache-key (element)
51085556 "Return a unique key for ELEMENT in cache tree.
51135561 When no synchronization is taking place, a key is simply the
51145562 beginning position of the element, or that position plus one in
51155563 the case of an first item (respectively row) in
5116 a list (respectively a table).
5564 a list (respectively a table). They key of a section is its beginning
5565 position minus one.
51175566
51185567 During a synchronization, the key is the one the element had when
51195568 the cache was synchronized for the last time. Elements added to
51205569 cache during the synchronization get a new key generated with
51215570 `org-element--cache-generate-key'.
51225571
5123 Such keys are stored in `org-element--cache-sync-keys'. The hash
5124 table is cleared once the synchronization is complete."
5125 (or (gethash element org-element--cache-sync-keys)
5572 Such keys are stored inside the element property
5573 `:org-element--cache-sync-key'. The property is a cons containing
5574 current `org-element--cache-sync-keys-value' and the element key."
5575 (or (when (eq org-element--cache-sync-keys-value (car (org-element-property :org-element--cache-sync-key element)))
5576 (cdr (org-element-property :org-element--cache-sync-key element)))
51265577 (let* ((begin (org-element-property :begin element))
51275578 ;; Increase beginning position of items (respectively
51285579 ;; table rows) by one, so the first item can get
51305581 ;; table).
51315582 (key (if (memq (org-element-type element) '(item table-row))
51325583 (1+ begin)
5133 begin)))
5134 (if org-element--cache-sync-requests
5135 (puthash element key org-element--cache-sync-keys)
5136 key))))
5584 ;; Decrease beginning position of sections by one,
5585 ;; so that the first element of the section get
5586 ;; different key from the parent section.
5587 (if (eq (org-element-type element) 'section)
5588 (1- begin)
5589 (if (eq (org-element-type element) 'org-data)
5590 (- begin 2)
5591 begin)))))
5592 (when org-element--cache-sync-requests
5593 (org-element-put-property
5594 element
5595 :org-element--cache-sync-key
5596 (cons org-element--cache-sync-keys-value key)))
5597 key)))
51375598
51385599 (defun org-element--cache-generate-key (lower upper)
51395600 "Generate a key between LOWER and UPPER.
52085669 (defsubst org-element--cache-key-less-p (a b)
52095670 "Non-nil if key A is less than key B.
52105671 A and B are either integers or lists of integers, as returned by
5211 `org-element--cache-key'."
5672 `org-element--cache-key'.
5673
5674 Note that it is not reliable to compare buffer position with the cache
5675 keys. They keys may be larger compared to actual element :begin
5676 position."
52125677 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
52135678 (if (integerp b) (< (car a) b)
52145679 (catch 'exit
52265691
52275692 (defun org-element--cache-compare (a b)
52285693 "Non-nil when element A is located before element B."
5229 (org-element--cache-key-less-p (org-element--cache-key a)
5230 (org-element--cache-key b)))
5694 (org-element--cache-key-less-p (org-element--cache-key a) (org-element--cache-key b)))
52315695
52325696 (defsubst org-element--cache-root ()
5233 "Return root value in cache.
5697 "Return root value in `org-element--cache' .
52345698 This function assumes `org-element--cache' is a valid AVL tree."
52355699 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
52365700
5701 (defsubst org-element--headline-cache-root ()
5702 "Return root value in `org-element--headline-cache' .
5703 This function assumes `org-element--headline-cache' is a valid AVL tree."
5704 (avl-tree--node-left (avl-tree--dummyroot org-element--headline-cache)))
52375705
52385706 ;;;; Tools
52395707
5240 (defsubst org-element--cache-active-p ()
5708 ;; FIXME: Ideally, this should be inlined to avoid overheads, but
5709 ;; inlined functions should be declared before the code that uses them
5710 ;; and some code above does use `org-element--cache-active-p'. Moving this
5711 ;; declaration on top would require restructuring the whole cache
5712 ;; section.
5713 (defun org-element--cache-active-p (&optional called-from-cache-change-func-p)
52415714 "Non-nil when cache is active in current buffer."
5242 (and org-element-use-cache
5243 org-element--cache
5244 (derived-mode-p 'org-mode)))
5715 (org-with-base-buffer nil
5716 (and org-element-use-cache
5717 org-element--cache
5718 (or called-from-cache-change-func-p
5719 (eq org-element--cache-change-tic (buffer-chars-modified-tick))
5720 (and
5721 ;; org-num-mode calls some Org structure analysis functions
5722 ;; that can trigger cache update in the middle of changes. See
5723 ;; `org-num--verify' calling `org-num--skip-value' calling
5724 ;; `org-entry-get' that uses cache.
5725 ;; Forcefully disable cache when called from inside a
5726 ;; modification hook, where `inhibit-modification-hooks' is set
5727 ;; to t.
5728 (not inhibit-modification-hooks)
5729 ;; `combine-change-calls' sets `after-change-functions' to
5730 ;; nil. We need not to use cache inside
5731 ;; `combine-change-calls' because the buffer is potentially
5732 ;; changed without notice (the change will be registered
5733 ;; after exiting the `combine-change-calls' body though).
5734 (catch :inhibited
5735 (org-fold-core-cycle-over-indirect-buffers
5736 (unless (memq #'org-element--cache-after-change after-change-functions)
5737 (throw :inhibited nil)))
5738 t))))))
5739
5740 ;; FIXME: Remove after we establish that hashing is effective.
5741 (defun org-element-cache-hash-show-statistics ()
5742 "Display efficiency of O(1) query cache for `org-element--cache-find'.
5743
5744 This extra caching is based on the following paper:
5745 Pugh [Information Processing Letters] (1990) Slow optimally balanced
5746 search strategies vs. cached fast uniformly balanced search
5747 strategies. http://dx.doi.org/10.1016/0020-0190(90)90130-P
5748
5749 Also, see `org-element--cache-size'."
5750 (interactive)
5751 (message "%.2f%% of cache searches hashed, %.2f%% non-hashable."
5752 (* 100
5753 (/ (float (car org-element--cache-hash-statistics))
5754 (cdr org-element--cache-hash-statistics)))
5755 (* 100
5756 (/ (float org-element--cache-hash-nocache)
5757 (cdr org-element--cache-hash-statistics)))))
52455758
52465759 (defun org-element--cache-find (pos &optional side)
52475760 "Find element in cache starting at POS or before.
52565769
52575770 The function can only find elements in the synchronized part of
52585771 the cache."
5259 (let ((limit (and org-element--cache-sync-requests
5260 (aref (car org-element--cache-sync-requests) 0)))
5261 (node (org-element--cache-root))
5262 lower upper)
5263 (while node
5264 (let* ((element (avl-tree--node-data node))
5265 (begin (org-element-property :begin element)))
5266 (cond
5267 ((and limit
5268 (not (org-element--cache-key-less-p
5269 (org-element--cache-key element) limit)))
5270 (setq node (avl-tree--node-left node)))
5271 ((> begin pos)
5272 (setq upper element
5273 node (avl-tree--node-left node)))
5274 ((< begin pos)
5275 (setq lower element
5276 node (avl-tree--node-right node)))
5277 ;; We found an element in cache starting at POS. If `side'
5278 ;; is `both' we also want the next one in order to generate
5279 ;; a key in-between.
5280 ;;
5281 ;; If the element is the first row or item in a table or
5282 ;; a plain list, we always return the table or the plain
5283 ;; list.
5284 ;;
5285 ;; In any other case, we return the element found.
5286 ((eq side 'both)
5287 (setq lower element)
5288 (setq node (avl-tree--node-right node)))
5289 ((and (memq (org-element-type element) '(item table-row))
5290 (let ((parent (org-element-property :parent element)))
5291 (and (= (org-element-property :begin element)
5292 (org-element-property :contents-begin parent))
5293 (setq node nil
5294 lower parent
5295 upper parent)))))
5296 (t
5297 (setq node nil
5298 lower element
5299 upper element)))))
5300 (pcase side
5301 (`both (cons lower upper))
5302 (`nil lower)
5303 (_ upper))))
5772 (org-with-base-buffer nil
5773 (let* ((limit (and org-element--cache-sync-requests
5774 (org-element--request-key (car org-element--cache-sync-requests))))
5775 (node (org-element--cache-root))
5776 (hash-pos (unless (eq side 'both)
5777 (mod (org-knuth-hash pos)
5778 org-element--cache-hash-size)))
5779 (hashed (if (not side)
5780 (aref org-element--cache-hash-left hash-pos)
5781 (unless (eq side 'both)
5782 (aref org-element--cache-hash-right hash-pos))))
5783 lower upper)
5784 ;; `org-element--cache-key-less-p' does not accept markers.
5785 (when (markerp pos) (setq pos (marker-position pos)))
5786 (cl-incf (cdr org-element--cache-hash-statistics))
5787 (when (eq side 'both) (cl-incf org-element--cache-hash-nocache))
5788 (if (and hashed (not (eq side 'both))
5789 (or (not limit)
5790 ;; Limit can be a list key.
5791 (org-element--cache-key-less-p
5792 (org-element--cache-key hashed)
5793 limit))
5794 (= pos (org-element-property :begin hashed))
5795 ;; We cannot rely on element :begin for elements with
5796 ;; children starting at the same pos.
5797 (not (memq (org-element-type hashed)
5798 '(section org-data table)))
5799 (org-element-property :cached hashed))
5800 (progn
5801 (cl-incf (car org-element--cache-hash-statistics))
5802 hashed)
5803 (while node
5804 (let* ((element (avl-tree--node-data node))
5805 (begin (org-element-property :begin element)))
5806 (cond
5807 ((and limit
5808 (not (org-element--cache-key-less-p
5809 (org-element--cache-key element) limit)))
5810 (setq node (avl-tree--node-left node)))
5811 ((> begin pos)
5812 (setq upper element
5813 node (avl-tree--node-left node)))
5814 ((or (< begin pos)
5815 ;; If the element is section or org-data, we also need
5816 ;; to check the following element.
5817 (memq (org-element-type element) '(section org-data)))
5818 (setq lower element
5819 node (avl-tree--node-right node)))
5820 ;; We found an element in cache starting at POS. If `side'
5821 ;; is `both' we also want the next one in order to generate
5822 ;; a key in-between.
5823 ;;
5824 ;; If the element is the first row or item in a table or
5825 ;; a plain list, we always return the table or the plain
5826 ;; list.
5827 ;;
5828 ;; In any other case, we return the element found.
5829 ((eq side 'both)
5830 (setq lower element)
5831 (setq node (avl-tree--node-right node)))
5832 ((and (memq (org-element-type element) '(item table-row))
5833 (let ((parent (org-element-property :parent element)))
5834 (and (= (org-element-property :begin element)
5835 (org-element-property :contents-begin parent))
5836 (setq node nil
5837 lower parent
5838 upper parent)))))
5839 (t
5840 (setq node nil
5841 lower element
5842 upper element)))))
5843 (if (not side)
5844 (aset org-element--cache-hash-left hash-pos lower)
5845 (unless (eq side 'both)
5846 (aset org-element--cache-hash-right hash-pos lower)))
5847 (pcase side
5848 (`both (cons lower upper))
5849 (`nil lower)
5850 (_ upper))))))
53045851
53055852 (defun org-element--cache-put (element)
53065853 "Store ELEMENT in current buffer's cache, if allowed."
5307 (when (org-element--cache-active-p)
5308 (when org-element--cache-sync-requests
5309 ;; During synchronization, first build an appropriate key for
5310 ;; the new element so `avl-tree-enter' can insert it at the
5311 ;; right spot in the cache.
5312 (let ((keys (org-element--cache-find
5313 (org-element-property :begin element) 'both)))
5314 (puthash element
5315 (org-element--cache-generate-key
5316 (and (car keys) (org-element--cache-key (car keys)))
5317 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
5318 (org-element--cache-sync-requests
5319 (aref (car org-element--cache-sync-requests) 0))))
5320 org-element--cache-sync-keys)))
5321 (avl-tree-enter org-element--cache element)))
5854 (org-with-base-buffer nil
5855 (when (org-element--cache-active-p)
5856 (when org-element--cache-sync-requests
5857 ;; During synchronization, first build an appropriate key for
5858 ;; the new element so `avl-tree-enter' can insert it at the
5859 ;; right spot in the cache.
5860 (let* ((keys (org-element--cache-find
5861 (org-element-property :begin element) 'both))
5862 (new-key (org-element--cache-generate-key
5863 (and (car keys) (org-element--cache-key (car keys)))
5864 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
5865 (org-element--cache-sync-requests
5866 (org-element--request-key (car org-element--cache-sync-requests)))))))
5867 (org-element-put-property
5868 element
5869 :org-element--cache-sync-key
5870 (cons org-element--cache-sync-keys-value new-key))))
5871 (when (>= org-element--cache-diagnostics-level 2)
5872 (org-element--cache-log-message
5873 "Added new element with %S key: %S"
5874 (org-element-property :org-element--cache-sync-key element)
5875 (org-element--format-element element)))
5876 (org-element-put-property element :cached t)
5877 (when (memq (org-element-type element) '(headline inlinetask))
5878 (cl-incf org-element--headline-cache-size)
5879 (avl-tree-enter org-element--headline-cache element))
5880 (cl-incf org-element--cache-size)
5881 (avl-tree-enter org-element--cache element))))
53225882
53235883 (defsubst org-element--cache-remove (element)
53245884 "Remove ELEMENT from cache.
53255885 Assume ELEMENT belongs to cache and that a cache is active."
5326 (avl-tree-delete org-element--cache element))
5327
5886 (org-with-base-buffer nil
5887 (org-element-put-property element :cached nil)
5888 (cl-decf org-element--cache-size)
5889 ;; Invalidate contents of parent.
5890 (when (and (org-element-property :parent element)
5891 (org-element-contents (org-element-property :parent element)))
5892 (org-element-set-contents (org-element-property :parent element) nil))
5893 (when (memq (org-element-type element) '(headline inlinetask))
5894 (cl-decf org-element--headline-cache-size)
5895 (avl-tree-delete org-element--headline-cache element))
5896 (org-element--cache-log-message
5897 "Decreasing cache size to %S"
5898 org-element--cache-size)
5899 (when (< org-element--cache-size 0)
5900 (org-element--cache-warn
5901 "Cache grew to negative size in %S when deleting %S at %S. Cache key: %S.
5902 If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
5903 (org-element-type element)
5904 (current-buffer)
5905 (org-element-property :begin element)
5906 (org-element-property :org-element--cache-sync-key element))
5907 (org-element-cache-reset)
5908 (throw 'quit nil))
5909 (or (avl-tree-delete org-element--cache element)
5910 (progn
5911 ;; This should not happen, but if it is, would be better to know
5912 ;; where it happens.
5913 (org-element--cache-warn
5914 "Failed to delete %S element in %S at %S. The element cache key was %S.
5915 If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
5916 (org-element-type element)
5917 (current-buffer)
5918 (org-element-property :begin element)
5919 (org-element-property :org-element--cache-sync-key element))
5920 (org-element-cache-reset)
5921 (throw 'quit nil)))))
53285922
53295923 ;;;; Synchronization
53305924
53355929 (setq org-element--cache-sync-timer
53365930 (run-with-idle-timer
53375931 (let ((idle (current-idle-time)))
5338 (if idle (org-time-add idle org-element-cache-sync-break)
5932 (if idle (time-add idle org-element-cache-sync-break)
53395933 org-element-cache-sync-idle-time))
53405934 nil
53415935 #'org-element--cache-sync
53465940 TIME-LIMIT is a time value or nil."
53475941 (and time-limit
53485942 (or (input-pending-p)
5349 (org-time-less-p time-limit nil))))
5943 (time-less-p time-limit nil))))
53505944
53515945 (defsubst org-element--cache-shift-positions (element offset &optional props)
53525946 "Shift ELEMENT properties relative to buffer positions by OFFSET.
53635957 ;; shifting it more than once.
53645958 (when (and (or (not props) (memq :structure props))
53655959 (eq (org-element-type element) 'plain-list)
5366 (not (eq (org-element-type (plist-get properties :parent))
5367 'item)))
5960 (not (eq (org-element-type (plist-get properties :parent)) 'item)))
53685961 (dolist (item (plist-get properties :structure))
53695962 (cl-incf (car item) offset)
53705963 (cl-incf (nth 6 item) offset)))
5371 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
5964 (dolist (key '( :begin :contents-begin :contents-end :end
5965 :post-affiliated :robust-begin :robust-end))
53725966 (let ((value (and (or (not props) (memq key props))
53735967 (plist-get properties key))))
53745968 (and value (plist-put properties key (+ offset value)))))))
53755969
5376 (defun org-element--cache-sync (buffer &optional threshold future-change)
5970 (defvar org-element--cache-interrupt-C-g t
5971 "When non-nil, allow the user to abort `org-element--cache-sync'.
5972 The execution is aborted upon pressing `\\[keyboard-quit]'
5973 `org-element--cache-interrupt-C-g-max-count' times.")
5974 (defvar org-element--cache-interrupt-C-g-max-count 5
5975 "`\\[keyboard-quit]' count to interrupt `org-element--cache-sync'.
5976 See `org-element--cache-interrupt-C-g'.")
5977 (defvar org-element--cache-interrupt-C-g-count 0
5978 "Current number of `org-element--cache-sync' calls.
5979 See `org-element--cache-interrupt-C-g'.")
5980
5981 (defvar org-element--cache-change-warning nil
5982 "Non-nil when a sensitive line is about to be changed.
5983 It is a symbol among nil, t, or a number representing smallest level of
5984 modified headline. The level considers headline levels both before
5985 and after the modification.")
5986
5987 (defun org-element--cache-sync (buffer &optional threshold future-change offset)
53775988 "Synchronize cache with recent modification in BUFFER.
53785989
53795990 When optional argument THRESHOLD is non-nil, do the
53835994 state.
53845995
53855996 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5386 not registered yet in the cache are going to happen. It is used
5387 in `org-element--cache-submit-request', where cache is partially
5388 updated before current modification are actually submitted."
5997 not registered yet in the cache are going to happen. OFFSET is the
5998 change offset. It is used in `org-element--cache-submit-request',
5999 where cache is partially updated before current modification are
6000 actually submitted."
53896001 (when (buffer-live-p buffer)
5390 (with-current-buffer buffer
5391 (let ((inhibit-quit t) request next)
5392 (when org-element--cache-sync-timer
5393 (cancel-timer org-element--cache-sync-timer))
5394 (catch 'interrupt
5395 (while org-element--cache-sync-requests
5396 (setq request (car org-element--cache-sync-requests)
5397 next (nth 1 org-element--cache-sync-requests))
5398 (org-element--cache-process-request
5399 request
5400 (and next (aref next 0))
5401 threshold
5402 (and (not threshold)
5403 (org-time-add nil
5404 org-element-cache-sync-duration))
5405 future-change)
5406 ;; Request processed. Merge current and next offsets and
5407 ;; transfer ending position.
5408 (when next
5409 (cl-incf (aref next 3) (aref request 3))
5410 (aset next 2 (aref request 2)))
5411 (setq org-element--cache-sync-requests
5412 (cdr org-element--cache-sync-requests))))
5413 ;; If more requests are awaiting, set idle timer accordingly.
5414 ;; Otherwise, reset keys.
5415 (if org-element--cache-sync-requests
5416 (org-element--cache-set-timer buffer)
5417 (clrhash org-element--cache-sync-keys))))))
6002 (org-with-base-buffer buffer
6003 ;; Do not sync when, for example, in the middle of
6004 ;; `combine-change-calls'. See the commentary inside
6005 ;; `org-element--cache-active-p'.
6006 (when (and org-element--cache-sync-requests (org-element--cache-active-p))
6007 ;; Check if the buffer have been changed outside visibility of
6008 ;; `org-element--cache-before-change' and `org-element--cache-after-change'.
6009 (if (/= org-element--cache-last-buffer-size (buffer-size))
6010 (progn
6011 (org-element--cache-warn
6012 "Unregistered buffer modifications detected (%S != %S). Resetting.
6013 If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
6014 The buffer is: %s\n Current command: %S\n Backtrace:\n%S"
6015 org-element--cache-last-buffer-size
6016 (buffer-size)
6017 (buffer-name (current-buffer))
6018 this-command
6019 (when (and (fboundp 'backtrace-get-frames)
6020 (fboundp 'backtrace-to-string))
6021 (backtrace-to-string (backtrace-get-frames 'backtrace))))
6022 (org-element-cache-reset))
6023 (let ((inhibit-quit t) request next)
6024 (setq org-element--cache-interrupt-C-g-count 0)
6025 (when org-element--cache-sync-timer
6026 (cancel-timer org-element--cache-sync-timer))
6027 (let ((time-limit (time-add nil org-element-cache-sync-duration)))
6028 (catch 'org-element--cache-interrupt
6029 (when org-element--cache-sync-requests
6030 (org-element--cache-log-message "Syncing down to %S-%S" (or future-change threshold) threshold))
6031 (while org-element--cache-sync-requests
6032 (setq request (car org-element--cache-sync-requests)
6033 next (nth 1 org-element--cache-sync-requests))
6034 (org-element--cache-process-request
6035 request
6036 (when next (org-element--request-key next))
6037 threshold
6038 (unless threshold time-limit)
6039 future-change
6040 offset)
6041 ;; Re-assign current and next requests. It could have
6042 ;; been altered during phase 1.
6043 (setq request (car org-element--cache-sync-requests)
6044 next (nth 1 org-element--cache-sync-requests))
6045 ;; Request processed. Merge current and next offsets and
6046 ;; transfer ending position.
6047 (when next
6048 ;; The following requests can only be either phase 1
6049 ;; or phase 2 requests. We need to let them know
6050 ;; that additional shifting happened ahead of them.
6051 (cl-incf (org-element--request-offset next) (org-element--request-offset request))
6052 (org-element--cache-log-message
6053 "Updating next request offset to %S: %s"
6054 (org-element--request-offset next)
6055 (let ((print-length 10) (print-level 3)) (prin1-to-string next)))
6056 ;; FIXME: END part of the request only matters for
6057 ;; phase 0 requests. However, the only possible
6058 ;; phase 0 request must be the first request in the
6059 ;; list all the time. END position should be
6060 ;; unused.
6061 (setf (org-element--request-end next) (org-element--request-end request)))
6062 (setq org-element--cache-sync-requests
6063 (cdr org-element--cache-sync-requests)))))
6064 ;; If more requests are awaiting, set idle timer accordingly.
6065 ;; Otherwise, reset keys.
6066 (if org-element--cache-sync-requests
6067 (org-element--cache-set-timer buffer)
6068 (setq org-element--cache-change-warning nil)
6069 (setq org-element--cache-sync-keys-value (1+ org-element--cache-sync-keys-value)))))))))
54186070
54196071 (defun org-element--cache-process-request
5420 (request next threshold time-limit future-change)
6072 (request next-request-key threshold time-limit future-change offset)
54216073 "Process synchronization REQUEST for all entries before NEXT.
54226074
54236075 REQUEST is a vector, built by `org-element--cache-submit-request'.
54246076
5425 NEXT is a cache key, as returned by `org-element--cache-key'.
6077 NEXT-REQUEST-KEY is a cache key of the next request, as returned by
6078 `org-element--cache-key'.
54266079
54276080 When non-nil, THRESHOLD is a buffer position. Synchronization
54286081 stops as soon as a shifted element begins after it.
54306083 When non-nil, TIME-LIMIT is a time value. Synchronization stops
54316084 after this time or when Emacs exits idle state.
54326085
5433 When non-nil, FUTURE-CHANGE is a buffer position where changes
5434 not registered yet in the cache are going to happen. See
5435 `org-element--cache-submit-request' for more information.
5436
5437 Throw `interrupt' if the process stops before completing the
5438 request."
5439 (catch 'quit
5440 (when (= (aref request 5) 0)
5441 ;; Phase 0.
6086 When non-nil, FUTURE-CHANGE is a buffer position where changes not
6087 registered yet in the cache are going to happen. OFFSET is the
6088 changed text length. See `org-element--cache-submit-request' for more
6089 information.
6090
6091 Throw `org-element--cache-interrupt' if the process stops before
6092 completing the request."
6093 (org-with-base-buffer nil
6094 (org-element--cache-log-message
6095 "org-element-cache: Processing request %s up to %S-%S, next: %S"
6096 (let ((print-length 10) (print-level 3)) (prin1-to-string request))
6097 future-change
6098 threshold
6099 next-request-key)
6100 (catch 'org-element--cache-quit
6101 (when (= (org-element--request-phase request) 0)
6102 ;; Phase 0.
6103 ;;
6104 ;; Delete all elements starting after beginning of the element
6105 ;; with request key NEXT, but not after buffer position END.
6106 ;;
6107 ;; At each iteration, we start again at tree root since
6108 ;; a deletion modifies structure of the balanced tree.
6109 (org-element--cache-log-message "Phase 0")
6110 (catch 'org-element--cache-end-phase
6111 (let ((deletion-count 0))
6112 (while t
6113 (when (org-element--cache-interrupt-p time-limit)
6114 (org-element--cache-log-message "Interrupt: time limit")
6115 (throw 'org-element--cache-interrupt nil))
6116 (let ((request-key (org-element--request-key request))
6117 (end (org-element--request-end request))
6118 (node (org-element--cache-root))
6119 data data-key)
6120 ;; Find first element in cache with key REQUEST-KEY or
6121 ;; after it.
6122 (while node
6123 (let* ((element (avl-tree--node-data node))
6124 (key (org-element--cache-key element)))
6125 (cond
6126 ((org-element--cache-key-less-p key request-key)
6127 (setq node (avl-tree--node-right node)))
6128 ((org-element--cache-key-less-p request-key key)
6129 (setq data element
6130 data-key key
6131 node (avl-tree--node-left node)))
6132 (t (setq data element
6133 data-key key
6134 node nil)))))
6135 (if data
6136 ;; We found first element in cache starting at or
6137 ;; after REQUEST-KEY.
6138 (let ((pos (org-element-property :begin data)))
6139 ;; FIXME: Maybe simply (< pos end)?
6140 (if (<= pos end)
6141 (progn
6142 (org-element--cache-log-message "removing %S::%S"
6143 (org-element-property :org-element--cache-sync-key data)
6144 (org-element--format-element data))
6145 (cl-incf deletion-count)
6146 (org-element--cache-remove data)
6147 (when (and (> (log org-element--cache-size 2) 10)
6148 (> deletion-count
6149 (/ org-element--cache-size (log org-element--cache-size 2))))
6150 (org-element--cache-log-message "Removed %S>N/LogN(=%S/%S) elements. Resetting cache to prevent performance degradation"
6151 deletion-count
6152 org-element--cache-size
6153 (log org-element--cache-size 2))
6154 (org-element-cache-reset)
6155 (throw 'org-element--cache-quit t)))
6156 ;; Done deleting everything starting before END.
6157 ;; DATA-KEY is the first known element after END.
6158 ;; Move on to phase 1.
6159 (org-element--cache-log-message
6160 "found element after %S: %S::%S"
6161 end
6162 (org-element-property :org-element--cache-sync-key data)
6163 (org-element--format-element data))
6164 (setf (org-element--request-key request) data-key)
6165 (setf (org-element--request-beg request) pos)
6166 (setf (org-element--request-phase request) 1)
6167 (throw 'org-element--cache-end-phase nil)))
6168 ;; No element starting after modifications left in
6169 ;; cache: further processing is futile.
6170 (org-element--cache-log-message
6171 "Phase 0 deleted all elements in cache after %S!"
6172 request-key)
6173 (throw 'org-element--cache-quit t)))))))
6174 (when (= (org-element--request-phase request) 1)
6175 ;; Phase 1.
6176 ;;
6177 ;; Phase 0 left a hole in the cache. Some elements after it
6178 ;; could have parents within. For example, in the following
6179 ;; buffer:
6180 ;;
6181 ;; - item
6182 ;;
6183 ;;
6184 ;; Paragraph1
6185 ;;
6186 ;; Paragraph2
6187 ;;
6188 ;; if we remove a blank line between "item" and "Paragraph1",
6189 ;; everything down to "Paragraph2" is removed from cache. But
6190 ;; the paragraph now belongs to the list, and its `:parent'
6191 ;; property no longer is accurate.
6192 ;;
6193 ;; Therefore we need to parse again elements in the hole, or at
6194 ;; least in its last section, so that we can re-parent
6195 ;; subsequent elements, during phase 2.
6196 ;;
6197 ;; Note that we only need to get the parent from the first
6198 ;; element in cache after the hole.
6199 ;;
6200 ;; When next key is lesser or equal to the current one, current
6201 ;; request is inside a to-be-shifted part of the cache. It is
6202 ;; fine because the order of elements will not be altered by
6203 ;; shifting. However, we cannot know the real position of the
6204 ;; unshifted NEXT element in the current request. So, we need
6205 ;; to sort the request list according to keys and re-start
6206 ;; processing from the new leftmost request.
6207 (org-element--cache-log-message "Phase 1")
6208 (let ((key (org-element--request-key request)))
6209 (when (and next-request-key (not (org-element--cache-key-less-p key next-request-key)))
6210 ;; In theory, the only case when requests are not
6211 ;; ordered is when key of the next request is either the
6212 ;; same with current key or it is a key for a removed
6213 ;; element. Either way, we can simply merge the two
6214 ;; requests.
6215 (let ((next-request (nth 1 org-element--cache-sync-requests)))
6216 (org-element--cache-log-message "Phase 1: Unorderered requests. Merging: %S\n%S\n"
6217 (let ((print-length 10) (print-level 3)) (prin1-to-string request))
6218 (let ((print-length 10) (print-level 3)) (prin1-to-string next-request)))
6219 (setf (org-element--request-key next-request) key)
6220 (setf (org-element--request-beg next-request) (org-element--request-beg request))
6221 (setf (org-element--request-phase next-request) 1)
6222 (throw 'org-element--cache-quit t))))
6223 ;; Next element will start at its beginning position plus
6224 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
6225 ;; contains the real beginning position of the first element to
6226 ;; shift and re-parent.
6227 (let ((limit (+ (org-element--request-beg request) (org-element--request-offset request)))
6228 cached-before)
6229 (cond ((and threshold (> limit threshold))
6230 (org-element--cache-log-message "Interrupt: position %S after threshold %S" limit threshold)
6231 (throw 'org-element--cache-interrupt nil))
6232 ((and future-change (>= limit future-change))
6233 ;; Changes happened around this element and they will
6234 ;; trigger another phase 1 request. Skip re-parenting
6235 ;; and simply proceed with shifting (phase 2) to make
6236 ;; sure that followup phase 0 request for the recent
6237 ;; changes can operate on the correctly shifted cache.
6238 (org-element--cache-log-message "position %S after future change %S" limit future-change)
6239 (setf (org-element--request-parent request) nil)
6240 (setf (org-element--request-phase request) 2))
6241 (t
6242 (when future-change
6243 ;; Changes happened, but not yet registered after
6244 ;; this element. However, we a not yet safe to look
6245 ;; at the buffer and parse elements in the cache gap.
6246 ;; Some of the parents to be added to cache may end
6247 ;; after the changes. Parsing this parents will
6248 ;; assign the :end correct value for cache state
6249 ;; after future-change. Then, when the future change
6250 ;; is going to be processed, such parent boundary
6251 ;; will be altered unnecessarily. To avoid this,
6252 ;; we alter the new parents by -OFFSET.
6253 ;; For now, just save last known cached element and
6254 ;; then check all the parents below.
6255 (setq cached-before (org-element--cache-find (1- limit) nil)))
6256 ;; No relevant changes happened after submitting this
6257 ;; request. We are safe to look at the actual Org
6258 ;; buffer and calculate the new parent.
6259 (let ((parent (org-element--parse-to (1- limit) nil time-limit)))
6260 (when future-change
6261 ;; Check all the newly added parents to not
6262 ;; intersect with future change.
6263 (let ((up parent))
6264 (while (and up
6265 (or (not cached-before)
6266 (> (org-element-property :begin up)
6267 (org-element-property :begin cached-before))))
6268 (when (> (org-element-property :end up) future-change)
6269 ;; Offset future cache request.
6270 (org-element--cache-shift-positions
6271 up (- offset)
6272 (if (and (org-element-property :robust-begin up)
6273 (org-element-property :robust-end up))
6274 '(:contents-end :end :robust-end)
6275 '(:contents-end :end))))
6276 (setq up (org-element-property :parent up)))))
6277 (org-element--cache-log-message
6278 "New parent at %S: %S::%S"
6279 limit
6280 (org-element-property :org-element--cache-sync-key parent)
6281 (org-element--format-element parent))
6282 (setf (org-element--request-parent request) parent)
6283 (setf (org-element--request-phase request) 2))))))
6284 ;; Phase 2.
54426285 ;;
5443 ;; Delete all elements starting after BEG, but not after buffer
5444 ;; position END or past element with key NEXT. Also delete
5445 ;; elements contained within a previously removed element
5446 ;; (stored in `last-container').
6286 ;; Shift all elements starting from key START, but before NEXT, by
6287 ;; OFFSET, and re-parent them when appropriate.
54476288 ;;
5448 ;; At each iteration, we start again at tree root since
5449 ;; a deletion modifies structure of the balanced tree.
5450 (catch 'end-phase
5451 (while t
5452 (when (org-element--cache-interrupt-p time-limit)
5453 (throw 'interrupt nil))
5454 ;; Find first element in cache with key BEG or after it.
5455 (let ((beg (aref request 0))
5456 (end (aref request 2))
5457 (node (org-element--cache-root))
5458 data data-key last-container)
5459 (while node
5460 (let* ((element (avl-tree--node-data node))
5461 (key (org-element--cache-key element)))
5462 (cond
5463 ((org-element--cache-key-less-p key beg)
5464 (setq node (avl-tree--node-right node)))
5465 ((org-element--cache-key-less-p beg key)
5466 (setq data element
5467 data-key key
5468 node (avl-tree--node-left node)))
5469 (t (setq data element
5470 data-key key
5471 node nil)))))
5472 (if data
5473 (let ((pos (org-element-property :begin data)))
5474 (if (if (or (not next)
5475 (org-element--cache-key-less-p data-key next))
5476 (<= pos end)
5477 (and last-container
5478 (let ((up data))
5479 (while (and up (not (eq up last-container)))
5480 (setq up (org-element-property :parent up)))
5481 up)))
5482 (progn (when (and (not last-container)
5483 (> (org-element-property :end data)
5484 end))
5485 (setq last-container data))
5486 (org-element--cache-remove data))
5487 (aset request 0 data-key)
5488 (aset request 1 pos)
5489 (aset request 5 1)
5490 (throw 'end-phase nil)))
5491 ;; No element starting after modifications left in
5492 ;; cache: further processing is futile.
5493 (throw 'quit t))))))
5494 (when (= (aref request 5) 1)
5495 ;; Phase 1.
6289 ;; Elements are modified by side-effect so the tree structure
6290 ;; remains intact.
54966291 ;;
5497 ;; Phase 0 left a hole in the cache. Some elements after it
5498 ;; could have parents within. For example, in the following
5499 ;; buffer:
5500 ;;
5501 ;; - item
5502 ;;
5503 ;;
5504 ;; Paragraph1
5505 ;;
5506 ;; Paragraph2
5507 ;;
5508 ;; if we remove a blank line between "item" and "Paragraph1",
5509 ;; everything down to "Paragraph2" is removed from cache. But
5510 ;; the paragraph now belongs to the list, and its `:parent'
5511 ;; property no longer is accurate.
5512 ;;
5513 ;; Therefore we need to parse again elements in the hole, or at
5514 ;; least in its last section, so that we can re-parent
5515 ;; subsequent elements, during phase 2.
5516 ;;
5517 ;; Note that we only need to get the parent from the first
5518 ;; element in cache after the hole.
5519 ;;
5520 ;; When next key is lesser or equal to the current one, delegate
5521 ;; phase 1 processing to next request in order to preserve key
5522 ;; order among requests.
5523 (let ((key (aref request 0)))
5524 (when (and next (not (org-element--cache-key-less-p key next)))
5525 (let ((next-request (nth 1 org-element--cache-sync-requests)))
5526 (aset next-request 0 key)
5527 (aset next-request 1 (aref request 1))
5528 (aset next-request 5 1))
5529 (throw 'quit t)))
5530 ;; Next element will start at its beginning position plus
5531 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5532 ;; contains the real beginning position of the first element to
5533 ;; shift and re-parent.
5534 (let ((limit (+ (aref request 1) (aref request 3))))
5535 (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
5536 ((and future-change (>= limit future-change))
5537 ;; Changes are going to happen around this element and
5538 ;; they will trigger another phase 1 request. Skip the
5539 ;; current one.
5540 (aset request 5 2))
5541 (t
5542 (let ((parent (org-element--parse-to limit t time-limit)))
5543 (aset request 4 parent)
5544 (aset request 5 2))))))
5545 ;; Phase 2.
5546 ;;
5547 ;; Shift all elements starting from key START, but before NEXT, by
5548 ;; OFFSET, and re-parent them when appropriate.
5549 ;;
5550 ;; Elements are modified by side-effect so the tree structure
5551 ;; remains intact.
5552 ;;
5553 ;; Once THRESHOLD, if any, is reached, or once there is an input
5554 ;; pending, exit. Before leaving, the current synchronization
5555 ;; request is updated.
5556 (let ((start (aref request 0))
5557 (offset (aref request 3))
5558 (parent (aref request 4))
5559 (node (org-element--cache-root))
5560 (stack (list nil))
5561 (leftp t)
5562 exit-flag)
5563 ;; No re-parenting nor shifting planned: request is over.
5564 (when (and (not parent) (zerop offset)) (throw 'quit t))
5565 (while node
5566 (let* ((data (avl-tree--node-data node))
5567 (key (org-element--cache-key data)))
5568 (if (and leftp (avl-tree--node-left node)
5569 (not (org-element--cache-key-less-p key start)))
5570 (progn (push node stack)
5571 (setq node (avl-tree--node-left node)))
5572 (unless (org-element--cache-key-less-p key start)
5573 ;; We reached NEXT. Request is complete.
5574 (when (equal key next) (throw 'quit t))
5575 ;; Handle interruption request. Update current request.
5576 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5577 (aset request 0 key)
5578 (aset request 4 parent)
5579 (throw 'interrupt nil))
5580 ;; Shift element.
5581 (unless (zerop offset)
5582 (org-element--cache-shift-positions data offset))
5583 (let ((begin (org-element-property :begin data)))
5584 ;; Update PARENT and re-parent DATA, only when
5585 ;; necessary. Propagate new structures for lists.
5586 (while (and parent
5587 (<= (org-element-property :end parent) begin))
5588 (setq parent (org-element-property :parent parent)))
5589 (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
5590 ((and parent
5591 (let ((p (org-element-property :parent data)))
5592 (or (not p)
5593 (< (org-element-property :begin p)
5594 (org-element-property :begin parent)))))
5595 (org-element-put-property data :parent parent)
5596 (let ((s (org-element-property :structure parent)))
5597 (when (and s (org-element-property :structure data))
5598 (org-element-put-property data :structure s)))))
5599 ;; Cache is up-to-date past THRESHOLD. Request
5600 ;; interruption.
5601 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5602 (setq node (if (setq leftp (avl-tree--node-right node))
5603 (avl-tree--node-right node)
5604 (pop stack))))))
5605 ;; We reached end of tree: synchronization complete.
5606 t)))
6292 ;; Once THRESHOLD, if any, is reached, or once there is an input
6293 ;; pending, exit. Before leaving, the current synchronization
6294 ;; request is updated.
6295 (org-element--cache-log-message "Phase 2")
6296 (let ((start (org-element--request-key request))
6297 (offset (org-element--request-offset request))
6298 (parent (org-element--request-parent request))
6299 (node (org-element--cache-root))
6300 (stack (list nil))
6301 (leftp t)
6302 exit-flag continue-flag)
6303 ;; No re-parenting nor shifting planned: request is over.
6304 (when (and (not parent) (zerop offset))
6305 (org-element--cache-log-message "Empty offset. Request completed.")
6306 (throw 'org-element--cache-quit t))
6307 (while node
6308 (let* ((data (avl-tree--node-data node))
6309 (key (org-element--cache-key data)))
6310 ;; Traverse the cache tree. Ignore all the elements before
6311 ;; START. Note that `avl-tree-stack' would not bypass the
6312 ;; elements before START and thus would have been less
6313 ;; efficient.
6314 (if (and leftp (avl-tree--node-left node)
6315 (not (org-element--cache-key-less-p key start)))
6316 (progn (push node stack)
6317 (setq node (avl-tree--node-left node)))
6318 ;; Shift and re-parent when current node starts at or
6319 ;; after START, but before NEXT.
6320 (unless (org-element--cache-key-less-p key start)
6321 ;; We reached NEXT. Request is complete.
6322 (when (and next-request-key
6323 (not (org-element--cache-key-less-p key next-request-key)))
6324 (org-element--cache-log-message "Reached next request.")
6325 (let ((next-request (nth 1 org-element--cache-sync-requests)))
6326 (unless (and (org-element-property :cached (org-element--request-parent next-request))
6327 (org-element-property :begin (org-element--request-parent next-request))
6328 parent
6329 (> (org-element-property :begin (org-element--request-parent next-request))
6330 (org-element-property :begin parent)))
6331 (setf (org-element--request-parent next-request) parent)))
6332 (throw 'org-element--cache-quit t))
6333 ;; Handle interruption request. Update current request.
6334 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
6335 (org-element--cache-log-message "Interrupt: %s" (if exit-flag "threshold" "time limit"))
6336 (setf (org-element--request-key request) key)
6337 (setf (org-element--request-parent request) parent)
6338 (throw 'org-element--cache-interrupt nil))
6339 ;; Shift element.
6340 (unless (zerop offset)
6341 (when (>= org-element--cache-diagnostics-level 3)
6342 (org-element--cache-log-message "Shifting positions (𝝙%S) in %S::%S"
6343 offset
6344 (org-element-property :org-element--cache-sync-key data)
6345 (org-element--format-element data)))
6346 (org-element--cache-shift-positions data offset))
6347 (let ((begin (org-element-property :begin data)))
6348 ;; Update PARENT and re-parent DATA, only when
6349 ;; necessary. Propagate new structures for lists.
6350 (while (and parent
6351 (<= (org-element-property :end parent) begin))
6352 (setq parent (org-element-property :parent parent)))
6353 (cond ((and (not parent) (zerop offset)) (throw 'org-element--cache-quit nil))
6354 ;; Consider scenario when DATA lays within
6355 ;; sensitive lines of PARENT that was found
6356 ;; during phase 2. For example:
6357 ;;
6358 ;; #+ begin_quote
6359 ;; Paragraph
6360 ;; #+end_quote
6361 ;;
6362 ;; In the above source block, remove space in
6363 ;; the first line will trigger re-parenting of
6364 ;; the paragraph and "#+end_quote" that is also
6365 ;; considered paragraph before the modification.
6366 ;; However, the paragraph element stored in
6367 ;; cache must be deleted instead.
6368 ((and parent
6369 (or (not (memq (org-element-type parent) org-element-greater-elements))
6370 (and (org-element-property :contents-begin parent)
6371 (< (org-element-property :begin data) (org-element-property :contents-begin parent)))
6372 (and (org-element-property :contents-end parent)
6373 (>= (org-element-property :begin data) (org-element-property :contents-end parent)))
6374 (> (org-element-property :end data) (org-element-property :end parent))
6375 (and (org-element-property :contents-end data)
6376 (> (org-element-property :contents-end data) (org-element-property :contents-end parent)))))
6377 (org-element--cache-log-message "org-element-cache: Removing obsolete element with key %S::%S"
6378 (org-element-property :org-element--cache-sync-key data)
6379 (org-element--format-element data))
6380 (org-element--cache-remove data)
6381 ;; We altered the tree structure. The tree
6382 ;; traversal needs to be restarted.
6383 (setf (org-element--request-key request) key)
6384 (setf (org-element--request-parent request) parent)
6385 ;; Restart tree traversal.
6386 (setq node (org-element--cache-root)
6387 stack (list nil)
6388 leftp t
6389 begin -1
6390 continue-flag t))
6391 ((and parent
6392 (not (eq parent data))
6393 (let ((p (org-element-property :parent data)))
6394 (or (not p)
6395 (< (org-element-property :begin p)
6396 (org-element-property :begin parent))
6397 (unless (eq p parent)
6398 (not (org-element-property :cached p))
6399 ;; (not (avl-tree-member-p org-element--cache p))
6400 ))))
6401 (org-element--cache-log-message
6402 "Updating parent in %S\n Old parent: %S\n New parent: %S"
6403 (org-element--format-element data)
6404 (org-element--format-element (org-element-property :parent data))
6405 (org-element--format-element parent))
6406 (when (and (eq 'org-data (org-element-type parent))
6407 (not (eq 'headline (org-element-type data))))
6408 ;; FIXME: This check is here to see whether
6409 ;; such error happens within
6410 ;; `org-element--cache-process-request' or somewhere
6411 ;; else.
6412 (org-element--cache-warn
6413 "Added org-data parent to non-headline element: %S
6414 If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
6415 data)
6416 (org-element-cache-reset)
6417 (throw 'org-element--cache-quit t))
6418 (org-element-put-property data :parent parent)
6419 (let ((s (org-element-property :structure parent)))
6420 (when (and s (org-element-property :structure data))
6421 (org-element-put-property data :structure s)))))
6422 ;; Cache is up-to-date past THRESHOLD. Request
6423 ;; interruption.
6424 (when (and threshold (> begin threshold))
6425 (org-element--cache-log-message "Reached threshold %S: %S"
6426 threshold
6427 (org-element--format-element data))
6428 (setq exit-flag t))))
6429 (if continue-flag
6430 (setq continue-flag nil)
6431 (setq node (if (setq leftp (avl-tree--node-right node))
6432 (avl-tree--node-right node)
6433 (pop stack)))))))
6434 ;; We reached end of tree: synchronization complete.
6435 t))
6436 (org-element--cache-log-message
6437 "org-element-cache: Finished process. The cache size is %S. The remaining sync requests: %S"
6438 org-element--cache-size
6439 (let ((print-level 2)) (prin1-to-string org-element--cache-sync-requests)))))
6440
6441 (defsubst org-element--open-end-p (element)
6442 "Check if ELEMENT in current buffer contains extra blank lines after
6443 it and does not have closing term.
6444
6445 Examples of such elements are: section, headline, org-data,
6446 and footnote-definition."
6447 (and (org-element-property :contents-end element)
6448 (= (org-element-property :contents-end element)
6449 (save-excursion
6450 (goto-char (org-element-property :end element))
6451 (skip-chars-backward " \r\n\t")
6452 (line-beginning-position 2)))))
56076453
56086454 (defun org-element--parse-to (pos &optional syncp time-limit)
56096455 "Parse elements in current section, down to POS.
56156461 When optional argument SYNCP is non-nil, return the parent of the
56166462 element containing POS instead. In that case, it is also
56176463 possible to provide TIME-LIMIT, which is a time value specifying
5618 when the parsing should stop. The function throws `interrupt' if
5619 the process stopped before finding the expected result."
6464 when the parsing should stop. The function throws
6465 `org-element--cache-interrupt' if the process stopped before finding
6466 the expected result."
56206467 (catch 'exit
5621 (org-with-wide-buffer
5622 (goto-char pos)
5623 (let* ((cached (and (org-element--cache-active-p)
5624 (org-element--cache-find pos nil)))
5625 (begin (org-element-property :begin cached))
5626 element next mode)
5627 (cond
5628 ;; Nothing in cache before point: start parsing from first
5629 ;; element following headline above, or first element in
5630 ;; buffer.
5631 ((not cached)
5632 (if (org-with-limited-levels (outline-previous-heading))
5633 (progn
5634 (setq mode 'planning)
5635 (forward-line))
5636 (setq mode 'top-comment))
5637 (skip-chars-forward " \r\t\n")
5638 (beginning-of-line))
5639 ;; Cache returned exact match: return it.
5640 ((= pos begin)
5641 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5642 ;; There's a headline between cached value and POS: cached
5643 ;; value is invalid. Start parsing from first element
5644 ;; following the headline.
5645 ((re-search-backward
5646 (org-with-limited-levels org-outline-regexp-bol) begin t)
5647 (forward-line)
5648 (skip-chars-forward " \r\t\n")
5649 (beginning-of-line)
5650 (setq mode 'planning))
5651 ;; Check if CACHED or any of its ancestors contain point.
5652 ;;
5653 ;; If there is such an element, we inspect it in order to know
5654 ;; if we return it or if we need to parse its contents.
5655 ;; Otherwise, we just start parsing from current location,
5656 ;; which is right after the top-most element containing
5657 ;; CACHED.
5658 ;;
5659 ;; As a special case, if POS is at the end of the buffer, we
5660 ;; want to return the innermost element ending there.
5661 ;;
5662 ;; Also, if we find an ancestor and discover that we need to
5663 ;; parse its contents, make sure we don't start from
5664 ;; `:contents-begin', as we would otherwise go past CACHED
5665 ;; again. Instead, in that situation, we will resume parsing
5666 ;; from NEXT, which is located after CACHED or its higher
5667 ;; ancestor not containing point.
5668 (t
5669 (let ((up cached)
5670 (pos (if (= (point-max) pos) (1- pos) pos)))
5671 (goto-char (or (org-element-property :contents-begin cached) begin))
5672 (while (let ((end (org-element-property :end up)))
5673 (and (<= end pos)
5674 (goto-char end)
5675 (setq up (org-element-property :parent up)))))
5676 (cond ((not up))
5677 ((eobp) (setq element up))
5678 (t (setq element up next (point)))))))
5679 ;; Parse successively each element until we reach POS.
5680 (let ((end (or (org-element-property :end element)
5681 (save-excursion
5682 (org-with-limited-levels (outline-next-heading))
5683 (point))))
5684 (parent element))
5685 (while t
5686 (when syncp
5687 (cond ((= (point) pos) (throw 'exit parent))
5688 ((org-element--cache-interrupt-p time-limit)
5689 (throw 'interrupt nil))))
5690 (unless element
5691 (setq element (org-element--current-element
5692 end 'element mode
5693 (org-element-property :structure parent)))
5694 (org-element-put-property element :parent parent)
5695 (org-element--cache-put element))
5696 (let ((elem-end (org-element-property :end element))
5697 (type (org-element-type element)))
5698 (cond
5699 ;; Skip any element ending before point. Also skip
5700 ;; element ending at point (unless it is also the end of
5701 ;; buffer) since we're sure that another element begins
5702 ;; after it.
5703 ((and (<= elem-end pos) (/= (point-max) elem-end))
5704 (goto-char elem-end)
5705 (setq mode (org-element--next-mode mode type nil)))
5706 ;; A non-greater element contains point: return it.
5707 ((not (memq type org-element-greater-elements))
5708 (throw 'exit element))
5709 ;; Otherwise, we have to decide if ELEMENT really
5710 ;; contains POS. In that case we start parsing from
5711 ;; contents' beginning.
5712 ;;
5713 ;; If POS is at contents' beginning but it is also at
5714 ;; the beginning of the first item in a list or a table.
5715 ;; In that case, we need to create an anchor for that
5716 ;; list or table, so return it.
5717 ;;
5718 ;; Also, if POS is at the end of the buffer, no element
5719 ;; can start after it, but more than one may end there.
5720 ;; Arbitrarily, we choose to return the innermost of
5721 ;; such elements.
5722 ((let ((cbeg (org-element-property :contents-begin element))
5723 (cend (org-element-property :contents-end element)))
5724 (when (or syncp
5725 (and cbeg cend
5726 (or (< cbeg pos)
5727 (and (= cbeg pos)
5728 (not (memq type '(plain-list table)))))
5729 (or (> cend pos)
5730 (and (= cend pos) (= (point-max) pos)))))
5731 (goto-char (or next cbeg))
5732 (setq next nil
5733 mode (org-element--next-mode mode type t)
5734 parent element
5735 end cend))))
5736 ;; Otherwise, return ELEMENT as it is the smallest
5737 ;; element containing POS.
5738 (t (throw 'exit element))))
5739 (setq element nil)))))))
5740
6468 (save-match-data
6469 (org-with-base-buffer nil
6470 (org-with-wide-buffer
6471 (goto-char pos)
6472 (save-excursion
6473 (end-of-line)
6474 (skip-chars-backward " \r\t\n")
6475 ;; Within blank lines at the beginning of buffer, return nil.
6476 (when (bobp) (throw 'exit nil)))
6477 (let* ((cached (and (org-element--cache-active-p)
6478 (org-element--cache-find pos nil)))
6479 (mode (org-element-property :mode cached))
6480 element next)
6481 (cond
6482 ;; Nothing in cache before point: start parsing from first
6483 ;; element in buffer down to POS or from the beginning of the
6484 ;; file.
6485 ((and (not cached) (org-element--cache-active-p))
6486 (setq element (org-element-org-data-parser))
6487 (unless (org-element-property :begin element)
6488 (org-element--cache-warn "Error parsing org-data. Got %S\nPlease report to Org mode mailing list (M-x org-submit-bug-report)." element))
6489 (org-element--cache-log-message
6490 "Nothing in cache. Adding org-data: %S"
6491 (org-element--format-element element))
6492 (org-element--cache-put element)
6493 (goto-char (org-element-property :contents-begin element))
6494 (setq mode 'org-data))
6495 ;; Nothing in cache before point because cache is not active.
6496 ;; Parse from previous heading to avoid re-parsing the whole
6497 ;; buffer above. This comes at the cost of not calculating
6498 ;; `:parent' property for headings.
6499 ((not cached)
6500 (if (org-with-limited-levels (outline-previous-heading))
6501 (progn
6502 (setq element (org-element-headline-parser nil 'fast))
6503 (setq mode 'planning)
6504 (forward-line))
6505 (setq element (org-element-org-data-parser))
6506 (setq mode 'org-data))
6507 (org-skip-whitespace)
6508 (beginning-of-line))
6509 ;; Check if CACHED or any of its ancestors contain point.
6510 ;;
6511 ;; If there is such an element, we inspect it in order to know
6512 ;; if we return it or if we need to parse its contents.
6513 ;; Otherwise, we just start parsing from location, which is
6514 ;; right after the top-most element containing CACHED but
6515 ;; still before POS.
6516 ;;
6517 ;; As a special case, if POS is at the end of the buffer, we
6518 ;; want to return the innermost element ending there.
6519 ;;
6520 ;; Also, if we find an ancestor and discover that we need to
6521 ;; parse its contents, make sure we don't start from
6522 ;; `:contents-begin', as we would otherwise go past CACHED
6523 ;; again. Instead, in that situation, we will resume parsing
6524 ;; from NEXT, which is located after CACHED or its higher
6525 ;; ancestor not containing point.
6526 (t
6527 (let ((up cached)
6528 (pos (if (= (point-max) pos) (1- pos) pos)))
6529 (while (and up (<= (org-element-property :end up) pos))
6530 (goto-char (org-element-property :end up))
6531 (setq element up
6532 mode (org-element--next-mode (org-element-property :mode element) (org-element-type element) nil)
6533 up (org-element-property :parent up)
6534 next (point)))
6535 (when up (setq element up)))))
6536 ;; Parse successively each element until we reach POS.
6537 (let ((end (or (org-element-property :end element) (point-max)))
6538 (parent (org-element-property :parent element)))
6539 (while t
6540 (when (org-element--cache-interrupt-p time-limit)
6541 (throw 'org-element--cache-interrupt nil))
6542 (when (and inhibit-quit org-element--cache-interrupt-C-g quit-flag)
6543 (when quit-flag
6544 (cl-incf org-element--cache-interrupt-C-g-count)
6545 (setq quit-flag nil))
6546 (when (>= org-element--cache-interrupt-C-g-count
6547 org-element--cache-interrupt-C-g-max-count)
6548 (setq quit-flag t)
6549 (setq org-element--cache-interrupt-C-g-count 0)
6550 (org-element-cache-reset)
6551 (error "org-element: Parsing aborted by user. Cache has been cleared.
6552 If you observe Emacs hangs frequently, please report this to Org mode mailing list (M-x org-submit-bug-report)."))
6553 (message (substitute-command-keys
6554 "`org-element--parse-buffer': Suppressed `\\[keyboard-quit]'. Press `\\[keyboard-quit]' %d more times to force interruption.")
6555 (- org-element--cache-interrupt-C-g-max-count
6556 org-element--cache-interrupt-C-g-count)))
6557 (unless element
6558 ;; Do not try to parse within blank at EOB.
6559 (unless (save-excursion
6560 (org-skip-whitespace)
6561 (eobp))
6562 (org-element-with-disabled-cache
6563 (setq element (org-element--current-element
6564 end 'element mode
6565 (org-element-property :structure parent)))))
6566 ;; Make sure that we return referenced element in cache
6567 ;; that can be altered directly.
6568 (if element
6569 (progn
6570 (org-element-put-property element :granularity 'element)
6571 (setq element (or (org-element--cache-put element) element)))
6572 ;; Nothing to parse (i.e. empty file).
6573 (throw 'exit parent))
6574 (unless (or (not (org-element--cache-active-p)) parent)
6575 (org-element--cache-warn
6576 "Got empty parent while parsing. Please report it to Org mode mailing list (M-x org-submit-bug-report).\n Backtrace:\n%S"
6577 (when (and (fboundp 'backtrace-get-frames)
6578 (fboundp 'backtrace-to-string))
6579 (backtrace-to-string (backtrace-get-frames 'backtrace))
6580 (org-element-cache-reset)
6581 (error "org-element--cache: Emergency exit"))))
6582 (org-element-put-property element :parent parent))
6583 (let ((elem-end (org-element-property :end element))
6584 (type (org-element-type element)))
6585 (cond
6586 ;; Skip any element ending before point. Also skip
6587 ;; element ending at point (unless it is also the end of
6588 ;; buffer) since we're sure that another element begins
6589 ;; after it.
6590 ((and (<= elem-end pos) (/= (point-max) elem-end))
6591 ;; Avoid parsing headline siblings above.
6592 (goto-char elem-end)
6593 (when (eq type 'headline)
6594 (save-match-data
6595 (unless (when (and (/= 1 (org-element-property :level element))
6596 (re-search-forward
6597 (rx-to-string
6598 `(and bol (repeat 1 ,(1- (let ((level (org-element-property :level element)))
6599 (if org-odd-levels-only (1- (* level 2)) level)))
6600 "*")
6601 " "))
6602 pos t))
6603 (beginning-of-line)
6604 t)
6605 ;; There are headings with lower level than
6606 ;; ELEMENT between ELEM-END and POS. Siblings
6607 ;; may exist though. Parse starting from the
6608 ;; last sibling or from ELEM-END if there are
6609 ;; no other siblings.
6610 (goto-char pos)
6611 (unless
6612 (re-search-backward
6613 (rx-to-string
6614 `(and bol (repeat ,(let ((level (org-element-property :level element)))
6615 (if org-odd-levels-only (1- (* level 2)) level))
6616 "*")
6617 " "))
6618 elem-end t)
6619 ;; Roll-back to normal parsing.
6620 (goto-char elem-end)))))
6621 (setq mode (org-element--next-mode mode type nil)))
6622 ;; A non-greater element contains point: return it.
6623 ((not (memq type org-element-greater-elements))
6624 (throw 'exit (if syncp parent element)))
6625 ;; Otherwise, we have to decide if ELEMENT really
6626 ;; contains POS. In that case we start parsing from
6627 ;; contents' beginning.
6628 ;;
6629 ;; If POS is at contents' beginning but it is also at
6630 ;; the beginning of the first item in a list or a table.
6631 ;; In that case, we need to create an anchor for that
6632 ;; list or table, so return it.
6633 ;;
6634 ;; Also, if POS is at the end of the buffer, no element
6635 ;; can start after it, but more than one may end there.
6636 ;; Arbitrarily, we choose to return the innermost of
6637 ;; such elements.
6638 ((let ((cbeg (org-element-property :contents-begin element))
6639 (cend (org-element-property :contents-end element)))
6640 (when (and cbeg cend
6641 (or (< cbeg pos)
6642 (and (= cbeg pos)
6643 (not (memq type '(plain-list table)))))
6644 (or (> cend pos)
6645 ;; When we are at cend or within blank
6646 ;; lines after, it is a special case:
6647 ;; 1. At the end of buffer we return
6648 ;; the innermost element.
6649 ;; 2. At cend of element with return
6650 ;; that element.
6651 ;; 3. At the end of element, we would
6652 ;; return in the earlier cond form.
6653 ;; 4. Within blank lines after cend,
6654 ;; when element does not have a
6655 ;; closing keyword, we return that
6656 ;; outermost element, unless the
6657 ;; outermost element is a non-empty
6658 ;; headline. In the latter case, we
6659 ;; return the outermost element inside
6660 ;; the headline section.
6661 (and (org-element--open-end-p element)
6662 (or (= (org-element-property :end element) (point-max))
6663 (and (>= pos (org-element-property :contents-end element))
6664 (memq (org-element-type element) '(org-data section headline)))))))
6665 (goto-char (or next cbeg))
6666 (setq mode (if next mode (org-element--next-mode mode type t))
6667 next nil
6668 parent element
6669 end (if (org-element--open-end-p element)
6670 (org-element-property :end element)
6671 (org-element-property :contents-end element))))))
6672 ;; Otherwise, return ELEMENT as it is the smallest
6673 ;; element containing POS.
6674 (t (throw 'exit (if syncp parent element)))))
6675 (setq element nil)))))))))
57416676
57426677 ;;;; Staging Buffer Changes
57436678
57466681 "^\\*+ " "\\|"
57476682 "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
57486683 "^[ \t]*\\(?:"
5749 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5750 "\\\\begin{[A-Za-z0-9*]+}" "\\|"
6684 "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
6685 org-list-full-item-re "\\|"
6686 ":\\(?: \\|$\\)" "\\|"
57516687 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
57526688 "\\)")
57536689 "Regexp matching a sensitive line, structure wise.
57566692 structure changes in the document may propagate in the whole
57576693 section, possibly making cache invalid.")
57586694
5759 (defvar org-element--cache-change-warning nil
5760 "Non-nil when a sensitive line is about to be changed.
5761 It is a symbol among nil, t and `headline'.")
5762
57636695 (defun org-element--cache-before-change (beg end)
5764 "Request extension of area going to be modified if needed.
6696 "Detect modifications in sensitive parts of Org buffer.
57656697 BEG and END are the beginning and end of the range of changed
5766 text. See `before-change-functions' for more information."
5767 (when (org-element--cache-active-p)
5768 (org-with-wide-buffer
5769 (goto-char beg)
5770 (beginning-of-line)
5771 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
5772 (setq org-element--cache-change-warning
5773 (save-match-data
5774 (if (and (org-with-limited-levels (org-at-heading-p))
5775 (= (line-end-position) bottom))
5776 'headline
5777 (let ((case-fold-search t))
5778 (re-search-forward
5779 org-element--cache-sensitive-re bottom t)))))))))
6698 text. See `before-change-functions' for more information.
6699
6700 The function returns the new value of `org-element--cache-change-warning'."
6701 (org-with-base-buffer nil
6702 (when (org-element--cache-active-p t)
6703 (org-with-wide-buffer
6704 (setq org-element--cache-change-tic (buffer-chars-modified-tick))
6705 (setq org-element--cache-last-buffer-size (buffer-size))
6706 (goto-char beg)
6707 (forward-line 0)
6708 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
6709 (prog1
6710 ;; Use the worst change warning to not miss important edits.
6711 ;; This function is called before edit and after edit by
6712 ;; `org-element--cache-after-change'. Before the edit, we still
6713 ;; want to use the old value if it comes from previous
6714 ;; not yet processed edit (they may be merged by
6715 ;; `org-element--cache-submit-request'). After the edit, we want to
6716 ;; look if there was a sensitive removed during edit.
6717 ;; FIXME: This is not the most efficient way and we now
6718 ;; have to delete more elements than needed in some
6719 ;; cases. A better approach may be storing the warning
6720 ;; in the modification request itself.
6721 (let ((org-element--cache-change-warning-before org-element--cache-change-warning)
6722 (org-element--cache-change-warning-after))
6723 (setq org-element--cache-change-warning-after
6724 (save-match-data
6725 (let ((case-fold-search t))
6726 (when (re-search-forward
6727 org-element--cache-sensitive-re bottom t)
6728 (goto-char beg)
6729 (beginning-of-line)
6730 (let (min-level)
6731 (cl-loop while (re-search-forward
6732 (rx-to-string
6733 (if (and min-level
6734 (> min-level 1))
6735 `(and bol (repeat 1 ,(1- min-level) "*") " ")
6736 `(and bol (+ "*") " ")))
6737 bottom t)
6738 do (setq min-level (1- (length (match-string 0))))
6739 until (= min-level 1))
6740 (goto-char beg)
6741 (beginning-of-line)
6742 (or (and min-level (org-reduced-level min-level))
6743 (when (looking-at-p "^[ \t]*#\\+CATEGORY:")
6744 'org-data)
6745 t))))))
6746 (setq org-element--cache-change-warning
6747 (cond
6748 ((and (numberp org-element--cache-change-warning-before)
6749 (numberp org-element--cache-change-warning-after))
6750 (min org-element--cache-change-warning-after
6751 org-element--cache-change-warning-before))
6752 ((numberp org-element--cache-change-warning-before)
6753 org-element--cache-change-warning-before)
6754 ((numberp org-element--cache-change-warning-after)
6755 org-element--cache-change-warning-after)
6756 (t (or org-element--cache-change-warning-after
6757 org-element--cache-change-warning-before)))))
6758 (org-element--cache-log-message
6759 "%S is about to modify text: warning %S"
6760 this-command
6761 org-element--cache-change-warning)))))))
57806762
57816763 (defun org-element--cache-after-change (beg end pre)
57826764 "Update buffer modifications for current buffer.
57836765 BEG and END are the beginning and end of the range of changed
57846766 text, and the length in bytes of the pre-change text replaced by
57856767 that range. See `after-change-functions' for more information."
5786 (when (org-element--cache-active-p)
5787 (org-with-wide-buffer
5788 (goto-char beg)
5789 (beginning-of-line)
5790 (save-match-data
5791 (let ((top (point))
5792 (bottom (save-excursion (goto-char end) (line-end-position))))
5793 ;; Determine if modified area needs to be extended, according
5794 ;; to both previous and current state. We make a special
5795 ;; case for headline editing: if a headline is modified but
5796 ;; not removed, do not extend.
5797 (when (pcase org-element--cache-change-warning
5798 (`t t)
5799 (`headline
5800 (not (and (org-with-limited-levels (org-at-heading-p))
5801 (= (line-end-position) bottom))))
5802 (_
5803 (let ((case-fold-search t))
5804 (re-search-forward
5805 org-element--cache-sensitive-re bottom t))))
5806 ;; Effectively extend modified area.
5807 (org-with-limited-levels
5808 (setq top (progn (goto-char top)
5809 (when (outline-previous-heading) (forward-line))
5810 (point)))
5811 (setq bottom (progn (goto-char bottom)
5812 (if (outline-next-heading) (1- (point))
5813 (point))))))
5814 ;; Store synchronization request.
5815 (let ((offset (- end beg pre)))
5816 (org-element--cache-submit-request top (- bottom offset) offset)))))
5817 ;; Activate a timer to process the request during idle time.
5818 (org-element--cache-set-timer (current-buffer))))
5819
6768 (org-with-base-buffer nil
6769 (when (org-element--cache-active-p t)
6770 (when (not (eq org-element--cache-change-tic (buffer-chars-modified-tick)))
6771 (org-element--cache-log-message "After change")
6772 (setq org-element--cache-change-warning (org-element--cache-before-change beg end))
6773 ;; If beg is right after spaces in front of an element, we
6774 ;; risk affecting previous element, so move beg to bol, making
6775 ;; sure that we capture preceding element.
6776 (setq beg (save-excursion
6777 (goto-char beg)
6778 (cl-incf pre (- beg (line-beginning-position)))
6779 (line-beginning-position)))
6780 ;; Store synchronization request.
6781 (let ((offset (- end beg pre)))
6782 (save-match-data
6783 (org-element--cache-submit-request beg (- end offset) offset)))
6784 ;; Activate a timer to process the request during idle time.
6785 (org-element--cache-set-timer (current-buffer))))))
6786
6787 (defun org-element--cache-setup-change-functions ()
6788 "Setup `before-change-functions' and `after-change-functions'."
6789 (when (and (derived-mode-p 'org-mode) org-element-use-cache)
6790 (add-hook 'before-change-functions
6791 #'org-element--cache-before-change nil t)
6792 ;; Run `org-element--cache-after-change' early to handle cases
6793 ;; when other `after-change-functions' require element cache.
6794 (add-hook 'after-change-functions
6795 #'org-element--cache-after-change -1 t)))
6796
6797 (defvar org-element--cache-avoid-synchronous-headline-re-parsing nil
6798 "This variable controls how buffer changes are handled by the cache.
6799
6800 By default (when this variable is nil), cache re-parses modified
6801 headlines immediately after modification preserving all the unaffected
6802 elements inside the headline.
6803
6804 The default behavior works best when users types inside Org buffer of
6805 when buffer modifications are mixed with cache requests. However,
6806 large automated edits inserting/deleting many headlines are somewhat
6807 slower by default (as in `org-archive-subtree'). Let-binding this
6808 variable to non-nil will reduce cache latency after every singular edit
6809 (`after-change-functions') at the cost of slower cache queries.")
58206810 (defun org-element--cache-for-removal (beg end offset)
58216811 "Return first element to remove from cache.
58226812
58276817 any position between BEG and END. As an exception, greater
58286818 elements around the changes that are robust to contents
58296819 modifications are preserved and updated according to the
5830 changes."
6820 changes. In the latter case, the returned element is the outermost
6821 non-robust element affected by the changes. Note that the returned
6822 element may end before END position in which case some cached element
6823 starting after the returned may still be affected by the changes.
6824
6825 Also, when there are no elements in cache before BEG, return first
6826 known element in cache (it may start after END)."
58316827 (let* ((elements (org-element--cache-find (1- beg) 'both))
58326828 (before (car elements))
58336829 (after (cdr elements)))
58346830 (if (not before) after
6831 ;; If BEFORE is a keyword, it may need to be removed to become
6832 ;; an affiliated keyword.
6833 (when (eq 'keyword (org-element-type before))
6834 (let ((prev before))
6835 (while (eq 'keyword (org-element-type prev))
6836 (setq before prev
6837 beg (org-element-property :begin prev))
6838 (setq prev (org-element--cache-find (1- (org-element-property :begin before)))))))
58356839 (let ((up before)
58366840 (robust-flag t))
58376841 (while up
58386842 (if (let ((type (org-element-type up)))
5839 (and (or (memq type '(center-block dynamic-block quote-block
5840 special-block))
5841 ;; Drawers named "PROPERTIES" are probably
5842 ;; a properties drawer being edited. Force
5843 ;; parsing to check if editing is over.
5844 (and (eq type 'drawer)
5845 (not (string=
5846 (org-element-property :drawer-name up)
5847 "PROPERTIES"))))
5848 (let ((cbeg (org-element-property :contents-begin up)))
5849 (and cbeg
5850 (<= cbeg beg)
5851 (> (org-element-property :contents-end up) end)))))
6843 (or (and (memq type '( center-block dynamic-block
6844 quote-block special-block
6845 drawer))
6846 (or (not (eq type 'drawer))
6847 (not (string= "PROPERTIES" (org-element-property :drawer-name up))))
6848 ;; Sensitive change. This is
6849 ;; unconditionally non-robust change.
6850 (not org-element--cache-change-warning)
6851 (let ((cbeg (org-element-property :contents-begin up))
6852 (cend (org-element-property :contents-end up)))
6853 (and cbeg
6854 (<= cbeg beg)
6855 (or (> cend end)
6856 (and (= cend end)
6857 (= (+ end offset) (point-max)))))))
6858 (and (memq type '(headline section org-data))
6859 (let ((rbeg (org-element-property :robust-begin up))
6860 (rend (org-element-property :robust-end up)))
6861 (and rbeg rend
6862 (<= rbeg beg)
6863 (or (> rend end)
6864 (and (= rend end)
6865 (= (+ end offset) (point-max))))))
6866 (pcase type
6867 ;; Sensitive change in section. Need to
6868 ;; re-parse.
6869 (`section (not org-element--cache-change-warning))
6870 ;; Headline might be inserted. This is non-robust
6871 ;; change when `up' is a `headline' or `section'
6872 ;; with `>' level compared to the inserted headline.
6873 ;;
6874 ;; Also, planning info/property drawer
6875 ;; could have been inserted. It is not
6876 ;; robust change then.
6877 (`headline
6878 (and
6879 (or (not (numberp org-element--cache-change-warning))
6880 (> org-element--cache-change-warning
6881 (org-element-property :level up)))
6882 (org-with-point-at (org-element-property :contents-begin up)
6883 (unless
6884 (save-match-data
6885 (when (looking-at-p org-element-planning-line-re)
6886 (forward-line))
6887 (when (looking-at org-property-drawer-re)
6888 (< beg (match-end 0))))
6889 'robust))))
6890 (`org-data (and (not (eq org-element--cache-change-warning 'org-data))
6891 ;; Property drawer could
6892 ;; have been inserted. It
6893 ;; is not robust change
6894 ;; then.
6895 (org-with-wide-buffer
6896 (goto-char (point-min))
6897 (while (and (org-at-comment-p) (bolp)) (forward-line))
6898 ;; Should not see property
6899 ;; drawer within changed
6900 ;; region.
6901 (save-match-data
6902 (or (not (looking-at org-property-drawer-re))
6903 (> beg (match-end 0)))))))
6904 (_ 'robust)))))
58526905 ;; UP is a robust greater element containing changes.
58536906 ;; We only need to extend its ending boundaries.
5854 (org-element--cache-shift-positions
5855 up offset '(:contents-end :end))
5856 (setq before up)
5857 (when robust-flag (setq robust-flag nil)))
6907 (progn
6908 (org-element--cache-shift-positions
6909 up offset
6910 (if (and (org-element-property :robust-begin up)
6911 (org-element-property :robust-end up))
6912 '(:contents-end :end :robust-end)
6913 '(:contents-end :end)))
6914 (org-element--cache-log-message
6915 "Shifting end positions of robust parent: %S"
6916 (org-element--format-element up)))
6917 (unless (or
6918 ;; UP is non-robust. Yet, if UP is headline, flagging
6919 ;; everything inside for removal may be to
6920 ;; costly. Instead, we should better re-parse only the
6921 ;; headline itself when possible. If a headline is still
6922 ;; starting from old :begin position, we do not care that
6923 ;; its boundaries could have extended to shrunk - we
6924 ;; will re-parent and shift them anyway.
6925 (and (eq 'headline (org-element-type up))
6926 (not org-element--cache-avoid-synchronous-headline-re-parsing)
6927 ;; The change is not inside headline. Not
6928 ;; updating here.
6929 (not (<= beg (org-element-property :begin up)))
6930 (not (> end (org-element-property :end up)))
6931 (let ((current (org-with-point-at (org-element-property :begin up)
6932 (org-element-with-disabled-cache
6933 (and (looking-at-p org-element-headline-re)
6934 (org-element-headline-parser nil 'fast))))))
6935 (when (eq 'headline (org-element-type current))
6936 (org-element--cache-log-message
6937 "Found non-robust headline that can be updated individually: %S"
6938 (org-element--format-element current))
6939 (org-element-set-element up current)
6940 (org-element-put-property up :granularity 'element)
6941 t)))
6942 ;; If UP is org-data, the situation is similar to
6943 ;; headline case. We just need to re-parse the
6944 ;; org-data itself, unless the change is made
6945 ;; within blank lines at BOB (that could
6946 ;; potentially alter first-section).
6947 (when (and (eq 'org-data (org-element-type up))
6948 (>= beg (org-element-property :contents-begin up)))
6949 (org-element-set-element up (org-with-point-at 1 (org-element-org-data-parser)))
6950 (org-element--cache-log-message
6951 "Found non-robust change invalidating org-data. Re-parsing: %S"
6952 (org-element--format-element up))
6953 t))
6954 (org-element--cache-log-message
6955 "Found non-robust element: %S"
6956 (org-element--format-element up))
6957 (setq before up)
6958 (when robust-flag (setq robust-flag nil))))
6959 (unless (or (org-element-property :parent up)
6960 (eq 'org-data (org-element-type up)))
6961 (org-element--cache-warn "Got element without parent. Please report it to Org mode mailing list (M-x org-submit-bug-report).\n%S" up)
6962 (org-element-cache-reset)
6963 (error "org-element--cache: Emergency exit"))
58586964 (setq up (org-element-property :parent up)))
5859 ;; We're at top level element containing ELEMENT: if it's
5860 ;; altered by buffer modifications, it is first element in
5861 ;; cache to be removed. Otherwise, that first element is the
5862 ;; following one.
5863 ;;
5864 ;; As a special case, do not remove BEFORE if it is a robust
5865 ;; container for current changes.
5866 (if (or (< (org-element-property :end before) beg) robust-flag) after
6965 ;; We're at top level element containing ELEMENT: if it's
6966 ;; altered by buffer modifications, it is first element in
6967 ;; cache to be removed. Otherwise, that first element is the
6968 ;; following one.
6969 ;;
6970 ;; As a special case, do not remove BEFORE if it is a robust
6971 ;; container for current changes.
6972 (if (or (< (org-element-property :end before) beg) robust-flag) after
58676973 before)))))
58686974
58696975 (defun org-element--cache-submit-request (beg end offset)
58716977 BEG and END are buffer positions delimiting the minimal area
58726978 where cache data should be removed. OFFSET is the size of the
58736979 change, as an integer."
5874 (let ((next (car org-element--cache-sync-requests))
5875 delete-to delete-from)
5876 (if (and next
5877 (zerop (aref next 5))
5878 (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
5879 (<= (setq delete-from (aref next 1)) end))
5880 ;; Current changes can be merged with first sync request: we
5881 ;; can save a partial cache synchronization.
5882 (progn
5883 (cl-incf (aref next 3) offset)
5884 ;; If last change happened within area to be removed, extend
5885 ;; boundaries of robust parents, if any. Otherwise, find
5886 ;; first element to remove and update request accordingly.
5887 (if (> beg delete-from)
5888 (let ((up (aref next 4)))
5889 (while up
5890 (org-element--cache-shift-positions
5891 up offset '(:contents-end :end))
5892 (setq up (org-element-property :parent up))))
5893 (let ((first (org-element--cache-for-removal beg delete-to offset)))
5894 (when first
5895 (aset next 0 (org-element--cache-key first))
5896 (aset next 1 (org-element-property :begin first))
5897 (aset next 4 (org-element-property :parent first))))))
5898 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5899 ;; if any, is no longer a 0-phase request, thus ensuring that
5900 ;; phases are properly ordered. We need to provide OFFSET as
5901 ;; optional parameter since current modifications are not known
5902 ;; yet to the otherwise correct part of the cache (i.e, before
5903 ;; the first request).
5904 (when next (org-element--cache-sync (current-buffer) end beg))
5905 (let ((first (org-element--cache-for-removal beg end offset)))
5906 (if first
5907 (push (let ((beg (org-element-property :begin first))
5908 (key (org-element--cache-key first)))
5909 (cond
5910 ;; When changes happen before the first known
5911 ;; element, re-parent and shift the rest of the
5912 ;; cache.
5913 ((> beg end) (vector key beg nil offset nil 1))
5914 ;; Otherwise, we find the first non robust
5915 ;; element containing END. All elements between
5916 ;; FIRST and this one are to be removed.
5917 ((let ((first-end (org-element-property :end first)))
5918 (and (> first-end end)
5919 (vector key beg first-end offset first 0))))
5920 (t
5921 (let* ((element (org-element--cache-find end))
5922 (end (org-element-property :end element))
5923 (up element))
5924 (while (and (setq up (org-element-property :parent up))
5925 (>= (org-element-property :begin up) beg))
5926 (setq end (org-element-property :end up)
5927 element up))
5928 (vector key beg end offset element 0)))))
5929 org-element--cache-sync-requests)
5930 ;; No element to remove. No need to re-parent either.
5931 ;; Simply shift additional elements, if any, by OFFSET.
5932 (when org-element--cache-sync-requests
5933 (cl-incf (aref (car org-element--cache-sync-requests) 3)
5934 offset)))))))
5935
6980 (org-element--cache-log-message
6981 "Submitting new synchronization request for [%S..%S]𝝙%S"
6982 beg end offset)
6983 (org-with-base-buffer nil
6984 (let ((next (car org-element--cache-sync-requests))
6985 delete-to delete-from)
6986 (if (and next
6987 ;; First existing sync request is in phase 0.
6988 (= 0 (org-element--request-phase next))
6989 ;; Current changes intersect with the first sync request.
6990 (> (setq delete-to (+ (org-element--request-end next)
6991 (org-element--request-offset next)))
6992 end)
6993 (<= (setq delete-from (org-element--request-beg next))
6994 end))
6995 ;; Current changes can be merged with first sync request: we
6996 ;; can save a partial cache synchronization.
6997 (progn
6998 (org-element--cache-log-message "Found another phase 0 request intersecting with current")
6999 ;; Update OFFSET of the existing request.
7000 (cl-incf (org-element--request-offset next) offset)
7001 ;; If last change happened within area to be removed, extend
7002 ;; boundaries of robust parents, if any. Otherwise, find
7003 ;; first element to remove and update request accordingly.
7004 (if (> beg delete-from)
7005 ;; The current modification is completely inside NEXT.
7006 ;; We already added the current OFFSET to the NEXT
7007 ;; request. However, the robust elements around
7008 ;; modifications also need to be shifted. Moreover, the
7009 ;; new modification may also have non-nil
7010 ;; `org-element--cache-change-warning'. In the latter case, we
7011 ;; also need to update the request.
7012 (let ((first (org-element--cache-for-removal delete-from end offset) ; Shift as needed.
7013 ))
7014 (org-element--cache-log-message
7015 "Current request is inside next. Candidate parent: %S"
7016 (org-element--format-element first))
7017 (when
7018 ;; Non-robust element is now before NEXT. Need to
7019 ;; update.
7020 (and first
7021 (org-element--cache-key-less-p
7022 (org-element--cache-key first)
7023 (org-element--request-key next)))
7024 (org-element--cache-log-message
7025 "Current request is inside next. New parent: %S"
7026 (org-element--format-element first))
7027 (setf (org-element--request-key next)
7028 (org-element--cache-key first))
7029 (setf (org-element--request-beg next)
7030 (org-element-property :begin first))
7031 (setf (org-element--request-end next)
7032 (max (org-element-property :end first)
7033 (org-element--request-end next)))
7034 (setf (org-element--request-parent next)
7035 (org-element-property :parent first))))
7036 ;; The current and NEXT modifications are intersecting
7037 ;; with current modification starting before NEXT and NEXT
7038 ;; ending after current. We need to update the common
7039 ;; non-robust parent for the new extended modification
7040 ;; region.
7041 (let ((first (org-element--cache-for-removal beg delete-to offset)))
7042 (org-element--cache-log-message
7043 "Current request intersects with next. Candidate parent: %S"
7044 (org-element--format-element first))
7045 (when (and first
7046 (org-element--cache-key-less-p
7047 (org-element--cache-key first)
7048 (org-element--request-key next)))
7049 (org-element--cache-log-message
7050 "Current request intersects with next. Updating. New parent: %S"
7051 (org-element--format-element first))
7052 (setf (org-element--request-key next) (org-element--cache-key first))
7053 (setf (org-element--request-beg next) (org-element-property :begin first))
7054 (setf (org-element--request-end next)
7055 (max (org-element-property :end first)
7056 (org-element--request-end next)))
7057 (setf (org-element--request-parent next) (org-element-property :parent first))))))
7058 ;; Ensure cache is correct up to END. Also make sure that NEXT,
7059 ;; if any, is no longer a 0-phase request, thus ensuring that
7060 ;; phases are properly ordered. We need to provide OFFSET as
7061 ;; optional parameter since current modifications are not known
7062 ;; yet to the otherwise correct part of the cache (i.e, before
7063 ;; the first request).
7064 (org-element--cache-log-message "Adding new phase 0 request")
7065 (when next (org-element--cache-sync (current-buffer) end beg offset))
7066 (let ((first (org-element--cache-for-removal beg end offset)))
7067 (if first
7068 (push (let ((first-beg (org-element-property :begin first))
7069 (key (org-element--cache-key first)))
7070 (cond
7071 ;; When changes happen before the first known
7072 ;; element, re-parent and shift the rest of the
7073 ;; cache.
7074 ((> first-beg end)
7075 (org-element--cache-log-message "Changes are before first known element. Submitting phase 1 request")
7076 (vector key first-beg nil offset nil 1))
7077 ;; Otherwise, we find the first non robust
7078 ;; element containing END. All elements between
7079 ;; FIRST and this one are to be removed.
7080 ;;
7081 ;; The current modification is completely inside
7082 ;; FIRST. Clear and update cached elements in
7083 ;; region containing FIRST.
7084 ((let ((first-end (org-element-property :end first)))
7085 (when (> first-end end)
7086 (org-element--cache-log-message "Extending to non-robust element %S" (org-element--format-element first))
7087 (vector key first-beg first-end offset (org-element-property :parent first) 0))))
7088 (t
7089 ;; Now, FIRST is the first element after BEG or
7090 ;; non-robust element containing BEG. However,
7091 ;; FIRST ends before END and there might be
7092 ;; another ELEMENT before END that spans beyond
7093 ;; END. If there is such element, we need to
7094 ;; extend the region down to end of the common
7095 ;; parent of FIRST and everything inside
7096 ;; BEG..END.
7097 (let* ((element (org-element--cache-find end))
7098 (element-end (org-element-property :end element))
7099 (up element))
7100 (while (and (not (eq up first))
7101 (setq up (org-element-property :parent up))
7102 (>= (org-element-property :begin up) first-beg))
7103 ;; Note that UP might have been already
7104 ;; shifted if it is a robust element. After
7105 ;; deletion, it can put it's end before yet
7106 ;; unprocessed ELEMENT.
7107 (setq element-end (max (org-element-property :end up) element-end)
7108 element up))
7109 ;; Extend region to remove elements between
7110 ;; beginning of first and the end of outermost
7111 ;; element starting before END but after
7112 ;; beginning of first.
7113 ;; of the FIRST.
7114 (org-element--cache-log-message
7115 "Extending to all elements between:\n 1: %S\n 2: %S"
7116 (org-element--format-element first)
7117 (org-element--format-element element))
7118 (vector key first-beg element-end offset up 0)))))
7119 org-element--cache-sync-requests)
7120 ;; No element to remove. No need to re-parent either.
7121 ;; Simply shift additional elements, if any, by OFFSET.
7122 (if org-element--cache-sync-requests
7123 (progn
7124 (org-element--cache-log-message
7125 "Nothing to remove. Updating offset of the next request by 𝝙%S: %S"
7126 offset
7127 (let ((print-level 3))
7128 (car org-element--cache-sync-requests)))
7129 (cl-incf (org-element--request-offset (car org-element--cache-sync-requests))
7130 offset))
7131 (org-element--cache-log-message
7132 "Nothing to remove. No elements in cache after %S. Terminating."
7133 end))))))
7134 (setq org-element--cache-change-warning nil)))
7135
7136 (defun org-element--cache-verify-element (element)
7137 "Verify correctness of ELEMENT when `org-element--cache-self-verify' is non-nil.
7138
7139 Return non-nil when verification failed."
7140 (let ((org-element--cache-self-verify
7141 (or org-element--cache-self-verify
7142 (and (boundp 'org-batch-test) org-batch-test)))
7143 (org-element--cache-self-verify-frequency
7144 (if (and (boundp 'org-batch-test) org-batch-test)
7145 1
7146 org-element--cache-self-verify-frequency)))
7147 ;; Verify correct parent for the element.
7148 (unless (or (not org-element--cache-self-verify)
7149 (org-element-property :parent element)
7150 (eq 'org-data (org-element-type element)))
7151 (org-element--cache-warn "Got element without parent (cache active?: %S). Please report it to Org mode mailing list (M-x org-submit-bug-report).\n%S" (org-element--cache-active-p) element)
7152 (org-element-cache-reset))
7153 (when (and org-element--cache-self-verify
7154 (org-element--cache-active-p)
7155 (eq 'headline (org-element-type element))
7156 ;; Avoid too much slowdown
7157 (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
7158 (org-with-point-at (org-element-property :begin element)
7159 (org-element-with-disabled-cache (org-up-heading-or-point-min))
7160 (unless (or (= (point) (org-element-property :begin (org-element-property :parent element)))
7161 (eq (point) (point-min)))
7162 (org-element--cache-warn
7163 "Cached element has wrong parent in %s. Resetting.
7164 If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
7165 The element is: %S\n The parent is: %S\n The real parent is: %S"
7166 (buffer-name (current-buffer))
7167 (org-element--format-element element)
7168 (org-element--format-element (org-element-property :parent element))
7169 (org-element--format-element (org-element--current-element (org-element-property :end (org-element-property :parent element)))))
7170 (org-element-cache-reset))
7171 (org-element--cache-verify-element (org-element-property :parent element))))
7172 ;; Verify the element itself.
7173 (when (and org-element--cache-self-verify
7174 (org-element--cache-active-p)
7175 element
7176 (not (memq (org-element-type element) '(section org-data)))
7177 ;; Avoid too much slowdown
7178 (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
7179 (let ((real-element (let (org-element-use-cache)
7180 (org-element--parse-to
7181 (if (memq (org-element-type element) '(table-row item))
7182 (1+ (org-element-property :begin element))
7183 (org-element-property :begin element))))))
7184 (unless (and (eq (org-element-type real-element) (org-element-type element))
7185 (eq (org-element-property :begin real-element) (org-element-property :begin element))
7186 (eq (org-element-property :end real-element) (org-element-property :end element))
7187 (eq (org-element-property :contents-begin real-element) (org-element-property :contents-begin element))
7188 (eq (org-element-property :contents-end real-element) (org-element-property :contents-end element))
7189 (or (not (org-element-property :ID real-element))
7190 (string= (org-element-property :ID real-element) (org-element-property :ID element))))
7191 (org-element--cache-warn "(%S) Cached element is incorrect in %s. (Cache tic up to date: %S) Resetting.
7192 If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
7193 The element is: %S\n The real element is: %S\n Cache around :begin:\n%S\n%S\n%S"
7194 this-command
7195 (buffer-name (current-buffer))
7196 (if (/= org-element--cache-change-tic
7197 (buffer-chars-modified-tick))
7198 "no" "yes")
7199 (org-element--format-element element)
7200 (org-element--format-element real-element)
7201 (org-element--cache-find (1- (org-element-property :begin real-element)))
7202 (car (org-element--cache-find (org-element-property :begin real-element) 'both))
7203 (cdr (org-element--cache-find (org-element-property :begin real-element) 'both)))
7204 (org-element-cache-reset))))))
7205
7206 ;;; Cache persistence
7207
7208 (defun org-element--cache-persist-before-write (container &optional associated)
7209 "Sync cache before saving."
7210 (when (equal container '(elisp org-element--cache))
7211 (if (and org-element-use-cache
7212 (plist-get associated :file)
7213 (get-file-buffer (plist-get associated :file))
7214 org-element-cache-persistent)
7215 (with-current-buffer (get-file-buffer (plist-get associated :file))
7216 (if (and (derived-mode-p 'org-mode)
7217 org-element--cache)
7218 (org-with-wide-buffer
7219 (org-element--cache-sync (current-buffer) (point-max))
7220 ;; Cleanup cache request keys to avoid collisions during next
7221 ;; Emacs session.
7222 (avl-tree-mapc
7223 (lambda (el)
7224 (org-element-put-property el :org-element--cache-sync-key nil))
7225 org-element--cache)
7226 nil)
7227 'forbid))
7228 'forbid)))
7229
7230 (defun org-element--cache-persist-before-read (container &optional associated)
7231 "Avoid reading cache before Org mode is loaded."
7232 (when (equal container '(elisp org-element--cache))
7233 (if (not (and (plist-get associated :file)
7234 (get-file-buffer (plist-get associated :file))))
7235 'forbid
7236 (with-current-buffer (get-file-buffer (plist-get associated :file))
7237 (unless (and org-element-use-cache
7238 org-element-cache-persistent
7239 (derived-mode-p 'org-mode)
7240 (equal (secure-hash 'md5 (current-buffer))
7241 (plist-get associated :hash)))
7242 'forbid)))))
7243
7244 (defun org-element--cache-persist-after-read (container &optional associated)
7245 "Setup restored cache."
7246 (when (and (plist-get associated :file)
7247 (get-file-buffer (plist-get associated :file)))
7248 (with-current-buffer (get-file-buffer (plist-get associated :file))
7249 (when (and org-element-use-cache org-element-cache-persistent)
7250 (when (and (equal container '(elisp org-element--cache)) org-element--cache)
7251 (setq-local org-element--cache-size (avl-tree-size org-element--cache)))
7252 (when (and (equal container '(elisp org-element--headline-cache)) org-element--headline-cache)
7253 (setq-local org-element--headline-cache-size (avl-tree-size org-element--headline-cache)))))))
7254
7255 (add-hook 'org-persist-before-write-hook #'org-element--cache-persist-before-write)
7256 (add-hook 'org-persist-before-read-hook #'org-element--cache-persist-before-read)
7257 (add-hook 'org-persist-after-read-hook #'org-element--cache-persist-after-read)
59367258
59377259 ;;;; Public Functions
59387260
7261 (defvar-local org-element--cache-gapless nil
7262 "An alist containing (granularity . `org-element--cache-change-tic') elements.
7263 Each element indicates the latest `org-element--cache-change-tic' when
7264 change did not contain gaps.")
7265
59397266 ;;;###autoload
5940 (defun org-element-cache-reset (&optional all)
7267 (defun org-element-cache-reset (&optional all no-persistence)
59417268 "Reset cache in current buffer.
59427269 When optional argument ALL is non-nil, reset cache in all Org
5943 buffers."
7270 buffers.
7271 When optional argument NO-PERSISTENCE is non-nil, do not try to update
7272 the cache persistence in the buffer."
59447273 (interactive "P")
59457274 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5946 (with-current-buffer buffer
7275 (org-with-base-buffer buffer
59477276 (when (and org-element-use-cache (derived-mode-p 'org-mode))
7277 ;; Only persist cache in file buffers.
7278 (when (and (buffer-file-name) (not no-persistence))
7279 (when (not org-element-cache-persistent)
7280 (org-persist-unregister 'org-element--headline-cache (current-buffer))
7281 (org-persist-unregister 'org-element--cache (current-buffer)))
7282 (when (and org-element-cache-persistent
7283 (buffer-file-name (current-buffer)))
7284 (org-persist-register 'org-element--cache (current-buffer))
7285 (org-persist-register 'org-element--headline-cache
7286 (current-buffer)
7287 :inherit 'org-element--cache)))
7288 (setq-local org-element--cache-change-tic (buffer-chars-modified-tick))
7289 (setq-local org-element--cache-last-buffer-size (buffer-size))
7290 (setq-local org-element--cache-gapless nil)
59487291 (setq-local org-element--cache
59497292 (avl-tree-create #'org-element--cache-compare))
5950 (setq-local org-element--cache-sync-keys
5951 (make-hash-table :weakness 'key :test #'eq))
7293 (setq-local org-element--headline-cache
7294 (avl-tree-create #'org-element--cache-compare))
7295 (setq-local org-element--cache-hash-left (make-vector org-element--cache-hash-size nil))
7296 (setq-local org-element--cache-hash-right (make-vector org-element--cache-hash-size nil))
7297 (setq-local org-element--cache-size 0)
7298 (setq-local org-element--headline-cache-size 0)
7299 (setq-local org-element--cache-sync-keys-value 0)
59527300 (setq-local org-element--cache-change-warning nil)
59537301 (setq-local org-element--cache-sync-requests nil)
59547302 (setq-local org-element--cache-sync-timer nil)
5955 (add-hook 'before-change-functions
5956 #'org-element--cache-before-change nil t)
5957 (add-hook 'after-change-functions
5958 #'org-element--cache-after-change nil t)))))
7303 (org-element--cache-setup-change-functions)
7304 ;; Make sure that `org-element--cache-after-change' and
7305 ;; `org-element--cache-before-change' are working inside properly created
7306 ;; indirect buffers. Note that `clone-indirect-buffer-hook'
7307 ;; will not work inside indirect buffers not created by
7308 ;; calling `clone-indirect-buffer'. We consider that the code
7309 ;; not using `clone-indirect-buffer' to be written with
7310 ;; awareness about possible consequences.
7311 (add-hook 'clone-indirect-buffer-hook
7312 #'org-element--cache-setup-change-functions)))))
59597313
59607314 ;;;###autoload
59617315 (defun org-element-cache-refresh (pos)
59657319 (org-element--cache-submit-request pos pos 0)
59667320 (org-element--cache-set-timer (current-buffer))))
59677321
7322 (defvar warning-minimum-log-level) ; Defined in warning.el
7323
7324 (defvar org-element-cache-map-continue-from nil
7325 "Position from where mapping should continue.
7326 This variable can be set by called function, especially when the
7327 function modified the buffer.")
7328 ;;;###autoload
7329 (cl-defun org-element-cache-map (func &key (granularity 'headline+inlinetask) restrict-elements
7330 next-re fail-re from-pos (to-pos (point-max-marker)) after-element limit-count
7331 narrow)
7332 "Map all elements in current buffer with FUNC according to
7333 GRANULARITY. Collect non-nil return values into result list.
7334
7335 FUNC should accept a single argument - the element.
7336
7337 FUNC can modify the buffer, but doing so may reduce performance. If
7338 buffer is modified, the mapping will continue from an element starting
7339 after the last mapped element. If the last mapped element is deleted,
7340 the subsequent element will be skipped as it cannot be distinguished
7341 deterministically from a changed element. If FUNC is expected to
7342 delete the element, it should directly set the value of
7343 `org-element-cache-map-continue-from' to force `org-element-cache-map'
7344 continue from the right point in buffer.
7345
7346 If some elements are not yet in cache, they will be added.
7347
7348 GRANULARITY can be `headline', `headline+inlinetask'
7349 `greater-element', or `element'. The default is
7350 `headline+inlinetask'. `object' granularity is not supported.
7351
7352 RESTRICT-ELEMENTS is a list of element types to be mapped over.
7353
7354 NEXT-RE is a regexp used to search next candidate match when FUNC
7355 returns non-nil and to search the first candidate match. FAIL-RE is a
7356 regexp used to search next candidate match when FUNC returns nil. The
7357 mapping will continue starting from headline at the RE match.
7358
7359 FROM-POS and TO-POS are buffer positions. When non-nil, they bound the
7360 mapped elements to elements starting at of after FROM-POS but before
7361 TO-POS.
7362
7363 AFTER-ELEMENT, when non-nil, bounds the mapping to all the elements
7364 after AFTER-ELEMENT (i.e. if AFTER-ELEMENT is a headline section, we
7365 map all the elements starting from first element inside section, but
7366 not including the section).
7367
7368 LIMIT-COUNT limits mapping to that many first matches where FUNC
7369 returns non-nil.
7370
7371 NARROW controls whether current buffer narrowing should be preserved.
7372
7373 This function does a subset of what `org-element-map' does, but with
7374 much better performance. Cached elements are supplied as the single
7375 argument of FUNC. Changes to elements made in FUNC will also alter
7376 the cache."
7377 (unless (org-element--cache-active-p)
7378 (error "Cache must be active."))
7379 (unless (memq granularity '( headline headline+inlinetask
7380 greater-element element))
7381 (error "Unsupported granularity: %S" granularity))
7382 ;; Make TO-POS marker. Otherwise, buffer edits may garble the the
7383 ;; process.
7384 (unless (markerp to-pos)
7385 (let ((mk (make-marker)))
7386 (set-marker mk to-pos)
7387 (setq to-pos mk)))
7388 (let (;; Bind variables used inside loop to avoid memory
7389 ;; re-allocation on every iteration.
7390 ;; See https://emacsconf.org/2021/talks/faster/
7391 tmpnext-start tmpparent tmpelement)
7392 (save-excursion
7393 (save-restriction
7394 (unless narrow (widen))
7395 ;; Synchronize cache up to the end of mapped region.
7396 (org-element-at-point to-pos)
7397 (cl-macrolet ((cache-root
7398 ;; Use the most optimal version of cache available.
7399 () `(org-with-base-buffer nil
7400 (if (memq granularity '(headline headline+inlinetask))
7401 (org-element--headline-cache-root)
7402 (org-element--cache-root))))
7403 (cache-size
7404 ;; Use the most optimal version of cache available.
7405 () `(org-with-base-buffer nil
7406 (if (memq granularity '(headline headline+inlinetask))
7407 org-element--headline-cache-size
7408 org-element--cache-size)))
7409 (cache-walk-restart
7410 ;; Restart tree traversal after AVL tree re-balance.
7411 () `(when node
7412 (org-element-at-point (point-max))
7413 (setq node (cache-root)
7414 stack (list nil)
7415 leftp t
7416 continue-flag t)))
7417 (cache-walk-abort
7418 ;; Abort tree traversal.
7419 () `(setq continue-flag t
7420 node nil))
7421 (element-match-at-point
7422 ;; Returning the first element to match around point.
7423 ;; For example, if point is inside headline and
7424 ;; granularity is restricted to headlines only, skip
7425 ;; over all the child elements inside the headline
7426 ;; and return the first parent headline.
7427 ;; When we are inside a cache gap, calling
7428 ;; `org-element-at-point' also fills the cache gap down to
7429 ;; point.
7430 () `(progn
7431 ;; Parsing is one of the performance
7432 ;; bottlenecks. Make sure to optimize it as
7433 ;; much as possible.
7434 ;;
7435 ;; Avoid extra staff like timer cancels et al
7436 ;; and only call `org-element--cache-sync-requests' when
7437 ;; there are pending requests.
7438 (org-with-base-buffer nil
7439 (when org-element--cache-sync-requests
7440 (org-element--cache-sync (current-buffer))))
7441 ;; Call `org-element--parse-to' directly avoiding any
7442 ;; kind of `org-element-at-point' overheads.
7443 (if restrict-elements
7444 ;; Search directly instead of calling
7445 ;; `org-element-lineage' to avoid funcall overheads
7446 ;; and making sure that we do not go all
7447 ;; the way to `org-data' as `org-element-lineage'
7448 ;; does.
7449 (progn
7450 (setq tmpelement (org-element--parse-to (point)))
7451 (while (and tmpelement (not (memq (org-element-type tmpelement) restrict-elements)))
7452 (setq tmpelement (org-element-property :parent tmpelement)))
7453 tmpelement)
7454 (org-element--parse-to (point)))))
7455 ;; Starting from (point), search RE and move START to
7456 ;; the next valid element to be matched according to
7457 ;; restriction. Abort cache walk if no next element
7458 ;; can be found. When RE is nil, just find element at
7459 ;; point.
7460 (move-start-to-next-match
7461 (re) `(save-match-data
7462 (if (or (not ,re)
7463 (if org-element--cache-map-statistics
7464 (progn
7465 (setq before-time (float-time))
7466 (re-search-forward (or (car-safe ,re) ,re) nil 'move)
7467 (cl-incf re-search-time
7468 (- (float-time)
7469 before-time)))
7470 (re-search-forward (or (car-safe ,re) ,re) nil 'move)))
7471 (unless (or (< (point) (or start -1))
7472 (and data
7473 (< (point) (org-element-property :begin data))))
7474 (if (cdr-safe ,re)
7475 ;; Avoid parsing when we are 100%
7476 ;; sure that regexp is good enough
7477 ;; to find new START.
7478 (setq start (match-beginning 0))
7479 (setq start (max (or start -1)
7480 (or (org-element-property :begin data) -1)
7481 (or (org-element-property :begin (element-match-at-point)) -1))))
7482 (when (>= start to-pos) (cache-walk-abort))
7483 (when (eq start -1) (setq start nil)))
7484 (cache-walk-abort))))
7485 ;; Find expected begin position of an element after
7486 ;; DATA.
7487 (next-element-start
7488 () `(progn
7489 (setq tmpnext-start nil)
7490 (if (memq granularity '(headline headline+inlinetask))
7491 (setq tmpnext-start (or (when (memq (org-element-type data) '(headline org-data))
7492 (org-element-property :contents-begin data))
7493 (org-element-property :end data)))
7494 (setq tmpnext-start (or (when (memq (org-element-type data) org-element-greater-elements)
7495 (org-element-property :contents-begin data))
7496 (org-element-property :end data))))
7497 ;; DATA end may be the last element inside
7498 ;; i.e. source block. Skip up to the end
7499 ;; of parent in such case.
7500 (setq tmpparent data)
7501 (catch :exit
7502 (when (eq tmpnext-start (org-element-property :contents-end tmpparent))
7503 (setq tmpnext-start (org-element-property :end tmpparent)))
7504 (while (setq tmpparent (org-element-property :parent tmpparent))
7505 (if (eq tmpnext-start (org-element-property :contents-end tmpparent))
7506 (setq tmpnext-start (org-element-property :end tmpparent))
7507 (throw :exit t))))
7508 tmpnext-start))
7509 ;; Check if cache does not have gaps.
7510 (cache-gapless-p
7511 () `(org-with-base-buffer nil
7512 (eq org-element--cache-change-tic
7513 (alist-get granularity org-element--cache-gapless)))))
7514 ;; The core algorithm is simple walk along binary tree. However,
7515 ;; instead of checking all the tree elements from first to last
7516 ;; (like in `avl-tree-mapcar'), we begin from FROM-POS skipping
7517 ;; the elements before FROM-POS efficiently: O(logN) instead of
7518 ;; O(Nbefore).
7519 ;;
7520 ;; Later, we may also not check every single element in the
7521 ;; binary tree after FROM-POS. Instead, we can find position of
7522 ;; next candidate elements by means of regexp search and skip the
7523 ;; binary tree branches that are before the next candidate:
7524 ;; again, O(logN) instead of O(Nbetween).
7525 ;;
7526 ;; Some elements might not yet be in the tree. So, we also parse
7527 ;; the empty gaps in cache as needed making sure that we do not
7528 ;; miss anything.
7529 (let* (;; START is always beginning of an element. When there is
7530 ;; no element in cache at START, we are inside cache gap
7531 ;; and need to fill it.
7532 (start (and from-pos
7533 (progn
7534 (goto-char from-pos)
7535 (org-element-property :begin (element-match-at-point)))))
7536 ;; Some elements may start at the same position, so we
7537 ;; also keep track of the last processed element and make
7538 ;; sure that we do not try to search it again.
7539 (prev after-element)
7540 (node (cache-root))
7541 data
7542 (stack (list nil))
7543 (leftp t)
7544 result
7545 ;; Whether previous element matched FUNC (FUNC
7546 ;; returned non-nil).
7547 (last-match t)
7548 continue-flag
7549 ;; Generic regexp to search next potential match. If it
7550 ;; is a cons of (regexp . 'match-beg), we are 100% sure
7551 ;; that the match beginning is the existing element
7552 ;; beginning.
7553 (next-element-re (pcase granularity
7554 ((or `headline
7555 (guard (equal '(headline)
7556 restrict-elements)))
7557 (cons
7558 (org-with-limited-levels
7559 org-element-headline-re)
7560 'match-beg))
7561 (`headline+inlinetask
7562 (cons
7563 (if (equal '(inlinetask) restrict-elements)
7564 (org-inlinetask-outline-regexp)
7565 org-element-headline-re)
7566 'match-beg))
7567 ;; TODO: May add other commonly
7568 ;; searched elements as needed.
7569 (_)))
7570 ;; Make sure that we are not checking the same regexp twice.
7571 (next-re (unless (and next-re
7572 (string= next-re
7573 (or (car-safe next-element-re)
7574 next-element-re)))
7575 next-re))
7576 (fail-re (unless (and fail-re
7577 (string= fail-re
7578 (or (car-safe next-element-re)
7579 next-element-re)))
7580 fail-re))
7581 (restrict-elements (or restrict-elements
7582 (pcase granularity
7583 (`headline
7584 '(headline))
7585 (`headline+inlinetask
7586 '(headline inlinetask))
7587 (`greater-element
7588 org-element-greater-elements)
7589 (_ nil))))
7590 ;; Statistics
7591 (time (float-time))
7592 (predicate-time 0)
7593 (pre-process-time 0)
7594 (re-search-time 0)
7595 (count-predicate-calls-match 0)
7596 (count-predicate-calls-fail 0)
7597 ;; Bind variables used inside loop to avoid memory
7598 ;; re-allocation on every iteration.
7599 ;; See https://emacsconf.org/2021/talks/faster/
7600 cache-size before-time modified-tic)
7601 ;; Skip to first element within region.
7602 (goto-char (or start (point-min)))
7603 (move-start-to-next-match next-element-re)
7604 (unless (and start (>= start to-pos))
7605 (while node
7606 (setq data (avl-tree--node-data node))
7607 (if (and leftp (avl-tree--node-left node) ; Left branch.
7608 ;; Do not move to left branch when we are before
7609 ;; PREV.
7610 (or (not prev)
7611 (not (org-element--cache-key-less-p
7612 (org-element--cache-key data)
7613 (org-element--cache-key prev))))
7614 ;; ... or when we are before START.
7615 (or (not start)
7616 (not (> start (org-element-property :begin data)))))
7617 (progn (push node stack)
7618 (setq node (avl-tree--node-left node)))
7619 ;; The whole tree left to DATA is before START and
7620 ;; PREV. DATA may still be before START (i.e. when
7621 ;; DATA is the root or when START moved), at START, or
7622 ;; after START.
7623 ;;
7624 ;; If DATA is before start, skip it over and move to
7625 ;; subsequent elements.
7626 ;; If DATA is at start, run FUNC if necessary and
7627 ;; update START according and NEXT-RE, FAIL-RE,
7628 ;; NEXT-ELEMENT-RE.
7629 ;; If DATA is after start, we have found a cache gap
7630 ;; and need to fill it.
7631 (unless (or (and start (< (org-element-property :begin data) start))
7632 (and prev (not (org-element--cache-key-less-p
7633 (org-element--cache-key prev)
7634 (org-element--cache-key data)))))
7635 ;; DATA is at of after START and PREV.
7636 (if (or (not start) (= (org-element-property :begin data) start))
7637 ;; DATA is at START. Match it.
7638 ;; In the process, we may alter the buffer,
7639 ;; so also keep track of the cache state.
7640 (progn
7641 (setq modified-tic
7642 (org-with-base-buffer nil
7643 org-element--cache-change-tic))
7644 (setq cache-size (cache-size))
7645 ;; When NEXT-RE/FAIL-RE is provided, skip to
7646 ;; next regexp match after :begin of the current
7647 ;; element.
7648 (when (if last-match next-re fail-re)
7649 (goto-char (org-element-property :begin data))
7650 (move-start-to-next-match
7651 (if last-match next-re fail-re)))
7652 (when (and (or (not start) (eq (org-element-property :begin data) start))
7653 (< (org-element-property :begin data) to-pos))
7654 ;; Calculate where next possible element
7655 ;; starts and update START if needed.
7656 (setq start (next-element-start))
7657 (goto-char start)
7658 ;; Move START further if possible.
7659 (when (and next-element-re
7660 ;; Do not move if we know for
7661 ;; sure that cache does not
7662 ;; contain gaps. Regexp
7663 ;; searches are not cheap.
7664 (not (cache-gapless-p)))
7665 (move-start-to-next-match next-element-re)
7666 ;; Make sure that point is at START
7667 ;; before running FUNC.
7668 (goto-char start))
7669 ;; Try FUNC if DATA matches all the
7670 ;; restrictions. Calculate new START.
7671 (when (or (not restrict-elements)
7672 (memq (org-element-type data) restrict-elements))
7673 ;; DATA matches restriction. FUNC may
7674 ;;
7675 ;; Call FUNC. FUNC may move point.
7676 (setq org-element-cache-map-continue-from nil)
7677 (if (org-with-base-buffer nil org-element--cache-map-statistics)
7678 (progn
7679 (setq before-time (float-time))
7680 (push (funcall func data) result)
7681 (cl-incf predicate-time
7682 (- (float-time)
7683 before-time))
7684 (if (car result)
7685 (cl-incf count-predicate-calls-match)
7686 (cl-incf count-predicate-calls-fail)))
7687 (push (funcall func data) result)
7688 (when (car result) (cl-incf count-predicate-calls-match)))
7689 ;; Set `last-match'.
7690 (setq last-match (car result))
7691 ;; If FUNC moved point forward, update
7692 ;; START.
7693 (when org-element-cache-map-continue-from
7694 (goto-char org-element-cache-map-continue-from))
7695 (when (> (point) start)
7696 (move-start-to-next-match nil)
7697 ;; (point) inside matching element.
7698 ;; Go further.
7699 (when (> (point) start)
7700 (setq data (element-match-at-point))
7701 (if (not data)
7702 (cache-walk-abort)
7703 (goto-char (next-element-start))
7704 (move-start-to-next-match next-element-re))))
7705 ;; Drop nil.
7706 (unless (car result) (pop result)))
7707 ;; If FUNC did not move the point and we
7708 ;; know for sure that cache does not contain
7709 ;; gaps, do not try to calculate START in
7710 ;; advance but simply loop to the next cache
7711 ;; element.
7712 (when (and (cache-gapless-p)
7713 (eq (next-element-start)
7714 start))
7715 (setq start nil))
7716 ;; Check if the buffer has been modified.
7717 (unless (org-with-base-buffer nil
7718 (and (eq modified-tic org-element--cache-change-tic)
7719 (eq cache-size (cache-size))))
7720 ;; START may no longer be valid, update
7721 ;; it to beginning of real element.
7722 ;; Upon modification, START may lay
7723 ;; inside an element. We want to move
7724 ;; it to real beginning then despite
7725 ;; START being larger.
7726 (setq start nil)
7727 (let ((data nil)) ; data may not be valid. ignore it.
7728 (move-start-to-next-match nil))
7729 ;; The new element may now start before
7730 ;; or at already processed position.
7731 ;; Make sure that we continue from an
7732 ;; element past already processed
7733 ;; place.
7734 (when (and start
7735 (<= start (org-element-property :begin data))
7736 (not org-element-cache-map-continue-from))
7737 (goto-char start)
7738 (setq data (element-match-at-point))
7739 ;; If DATA is nil, buffer is
7740 ;; empty. Abort.
7741 (when data
7742 (goto-char (next-element-start))
7743 (move-start-to-next-match next-element-re)))
7744 (org-element-at-point to-pos)
7745 (cache-walk-restart))
7746 ;; Reached LIMIT-COUNT. Abort.
7747 (when (and limit-count
7748 (>= count-predicate-calls-match
7749 limit-count))
7750 (cache-walk-abort))
7751 (if (org-element-property :cached data)
7752 (setq prev data)
7753 (setq prev nil))))
7754 ;; DATA is after START. Fill the gap.
7755 (if (memq (org-element-type (org-element--parse-to start)) '(plain-list table))
7756 ;; Tables and lists are special, we need a
7757 ;; trickery to make items/rows be populated
7758 ;; into cache.
7759 (org-element--parse-to (1+ start)))
7760 ;; Restart tree traversal as AVL tree is
7761 ;; re-balanced upon adding elements. We can no
7762 ;; longer trust STACK.
7763 (cache-walk-restart)))
7764 ;; Second, move to the right branch of the tree or skip
7765 ;; it altogether.
7766 (if continue-flag
7767 (setq continue-flag nil)
7768 (setq node (if (and (car stack)
7769 ;; If START advanced beyond stack parent, skip the right branch.
7770 (or (and start (< (org-element-property :begin (avl-tree--node-data (car stack))) start))
7771 (and prev (org-element--cache-key-less-p
7772 (org-element--cache-key (avl-tree--node-data (car stack)))
7773 (org-element--cache-key prev)))))
7774 (progn
7775 (setq leftp nil)
7776 (pop stack))
7777 ;; Otherwise, move ahead into the right
7778 ;; branch when it exists.
7779 (if (setq leftp (avl-tree--node-right node))
7780 (avl-tree--node-right node)
7781 (pop stack))))))))
7782 (when (and org-element--cache-map-statistics
7783 (or (not org-element--cache-map-statistics-threshold)
7784 (> (- (float-time) time) org-element--cache-map-statistics-threshold)))
7785 (message "Mapped over elements in %S. %d/%d predicate matches. Total time: %f sec. Pre-process time: %f sec. Predicate time: %f sec. Re-search time: %f sec.
7786 Calling parameters: :granularity %S :restrict-elements %S :next-re %S :fail-re %S :from-pos %S :to-pos %S :limit-count %S :after-element %S"
7787 (current-buffer)
7788 count-predicate-calls-match
7789 (+ count-predicate-calls-match
7790 count-predicate-calls-fail)
7791 (- (float-time) time)
7792 pre-process-time
7793 predicate-time
7794 re-search-time
7795 granularity restrict-elements next-re fail-re from-pos to-pos limit-count after-element))
7796 ;; Return result.
7797 (nreverse result)))))))
59687798
59697799
7800
7801
59707802 ;;; The Toolbox
59717803 ;;
59727804 ;; The first move is to implement a way to obtain the smallest element
59857817
59867818
59877819 ;;;###autoload
5988 (defun org-element-at-point ()
5989 "Determine closest element around point.
7820 (defun org-element-at-point (&optional pom cached-only)
7821 "Determine closest element around point or POM.
7822
7823 Only check cached element when CACHED-ONLY is non-nil and return nil
7824 unconditionally when element at POM is not in cache.
59907825
59917826 Return value is a list like (TYPE PROPS) where TYPE is the type
59927827 of the element and PROPS a plist of properties associated to the
60047839
60057840 When point is at the end of the buffer, return the innermost
60067841 element ending there."
6007 (org-with-wide-buffer
6008 (let ((origin (point)))
6009 (end-of-line)
6010 (skip-chars-backward " \r\t\n")
6011 (cond
6012 ;; Within blank lines at the beginning of buffer, return nil.
6013 ((bobp) nil)
6014 ;; Within blank lines right after a headline, return that
6015 ;; headline.
6016 ((org-with-limited-levels (org-at-heading-p))
6017 (beginning-of-line)
6018 (org-element-headline-parser (point-max) t))
6019 ;; Otherwise parse until we find element containing ORIGIN.
6020 (t
6021 (when (org-element--cache-active-p)
6022 (if (not org-element--cache) (org-element-cache-reset)
6023 (org-element--cache-sync (current-buffer) origin)))
6024 (org-element--parse-to origin))))))
7842 (setq pom (or pom (point)))
7843 ;; Allow re-parsing when the command can benefit from it.
7844 (when (and cached-only
7845 (memq this-command org-element--cache-non-modifying-commands))
7846 (setq cached-only nil))
7847 (let (element)
7848 (when (org-element--cache-active-p)
7849 (if (not (org-with-base-buffer nil org-element--cache)) (org-element-cache-reset)
7850 (unless cached-only (org-element--cache-sync (current-buffer) pom))))
7851 (setq element (if cached-only
7852 (when (and (org-element--cache-active-p)
7853 (or (not org-element--cache-sync-requests)
7854 (< pom
7855 (org-element--request-beg
7856 (car org-element--cache-sync-requests)))))
7857 (org-element--cache-find pom))
7858 (condition-case err
7859 (org-element--parse-to pom)
7860 (error
7861 (org-element--cache-warn
7862 "Org parser error in %s::%S. Resetting.\n The error was: %S\n Backtrace:\n%S\n Please report this to Org mode mailing list (M-x org-submit-bug-report)."
7863 (buffer-name (current-buffer))
7864 pom
7865 err
7866 (when (and (fboundp 'backtrace-get-frames)
7867 (fboundp 'backtrace-to-string))
7868 (backtrace-to-string (backtrace-get-frames 'backtrace))))
7869 (org-element-cache-reset)
7870 (org-element--parse-to pom)))))
7871 (when (and (org-element--cache-active-p)
7872 element
7873 (org-element--cache-verify-element element))
7874 (setq element (org-element--parse-to pom)))
7875 (unless (eq 'org-data (org-element-type element))
7876 (unless (and cached-only
7877 (not (and element
7878 (or (= pom (org-element-property :begin element))
7879 (and (not (memq (org-element-type element) org-element-greater-elements))
7880 (>= pom (org-element-property :begin element))
7881 (< pom (org-element-property :end element)))
7882 (and (org-element-property :contents-begin element)
7883 (>= pom (org-element-property :begin element))
7884 (< pom (org-element-property :contents-begin element)))
7885 (and (not (org-element-property :contents-end element))
7886 (>= pom (org-element-property :begin element))
7887 (< pom (org-element-property :end element)))))))
7888 (if (not (eq (org-element-type element) 'section))
7889 element
7890 (org-element-at-point (1+ pom) cached-only))))))
7891
7892 ;;;###autoload
7893 (defsubst org-element-at-point-no-context (&optional pom)
7894 "Quickly find element at point or POM.
7895
7896 It is a faster version of `org-element-at-point' that is not
7897 guaranteed to return correct `:parent' properties even when cache is
7898 enabled."
7899 (or (org-element-at-point pom 'cached-only)
7900 (let (org-element-use-cache) (org-element-at-point pom))))
60257901
60267902 ;;;###autoload
60277903 (defun org-element-context (&optional element)
60427918 Optional argument ELEMENT, when non-nil, is the closest element
60437919 containing point, as returned by `org-element-at-point'.
60447920 Providing it allows for quicker computation."
6045 (catch 'objects-forbidden
6046 (org-with-wide-buffer
6047 (let* ((pos (point))
6048 (element (or element (org-element-at-point)))
6049 (type (org-element-type element))
6050 (post (org-element-property :post-affiliated element)))
6051 ;; If point is inside an element containing objects or
6052 ;; a secondary string, narrow buffer to the container and
6053 ;; proceed with parsing. Otherwise, return ELEMENT.
6054 (cond
6055 ;; At a parsed affiliated keyword, check if we're inside main
6056 ;; or dual value.
6057 ((and post (< pos post))
6058 (beginning-of-line)
6059 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
6060 (cond
6061 ((not (member-ignore-case (match-string 1)
7921 (save-match-data
7922 (catch 'objects-forbidden
7923 (org-with-wide-buffer
7924 (let* ((pos (point))
7925 (element (or element (org-element-at-point)))
7926 (type (org-element-type element))
7927 (post (org-element-property :post-affiliated element)))
7928 ;; If point is inside an element containing objects or
7929 ;; a secondary string, narrow buffer to the container and
7930 ;; proceed with parsing. Otherwise, return ELEMENT.
7931 (cond
7932 ;; At a parsed affiliated keyword, check if we're inside main
7933 ;; or dual value.
7934 ((and post (< pos post))
7935 (beginning-of-line)
7936 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
7937 (cond
7938 ((not (member-ignore-case (match-string 1)
60627939 org-element-parsed-keywords))
6063 (throw 'objects-forbidden element))
6064 ((< (match-end 0) pos)
6065 (narrow-to-region (match-end 0) (line-end-position)))
6066 ((and (match-beginning 2)
6067 (>= pos (match-beginning 2))
6068 (< pos (match-end 2)))
6069 (narrow-to-region (match-beginning 2) (match-end 2)))
7940 (throw 'objects-forbidden element))
7941 ((< (match-end 0) pos)
7942 (narrow-to-region (match-end 0) (line-end-position)))
7943 ((and (match-beginning 2)
7944 (>= pos (match-beginning 2))
7945 (< pos (match-end 2)))
7946 (narrow-to-region (match-beginning 2) (match-end 2)))
7947 (t (throw 'objects-forbidden element)))
7948 ;; Also change type to retrieve correct restrictions.
7949 (setq type 'keyword))
7950 ;; At an item, objects can only be located within tag, if any.
7951 ((eq type 'item)
7952 (let ((tag (org-element-property :tag element)))
7953 (if (or (not tag) (/= (line-beginning-position) post))
7954 (throw 'objects-forbidden element)
7955 (beginning-of-line)
7956 (search-forward tag (line-end-position))
7957 (goto-char (match-beginning 0))
7958 (if (and (>= pos (point)) (< pos (match-end 0)))
7959 (narrow-to-region (point) (match-end 0))
7960 (throw 'objects-forbidden element)))))
7961 ;; At an headline or inlinetask, objects are in title.
7962 ((memq type '(headline inlinetask))
7963 (let ((case-fold-search nil))
7964 (goto-char (org-element-property :begin element))
7965 (looking-at org-complex-heading-regexp)
7966 (let ((end (match-end 4)))
7967 (if (not end) (throw 'objects-forbidden element)
7968 (goto-char (match-beginning 4))
7969 (when (looking-at org-element-comment-string)
7970 (goto-char (match-end 0)))
7971 (if (>= (point) end) (throw 'objects-forbidden element)
7972 (narrow-to-region (point) end))))))
7973 ;; At a paragraph, a table-row or a verse block, objects are
7974 ;; located within their contents.
7975 ((memq type '(paragraph table-row verse-block))
7976 (let ((cbeg (org-element-property :contents-begin element))
7977 (cend (org-element-property :contents-end element)))
7978 ;; CBEG is nil for table rules.
7979 (if (and cbeg cend (>= pos cbeg)
7980 (or (< pos cend) (and (= pos cend) (eobp))))
7981 (narrow-to-region cbeg cend)
7982 (throw 'objects-forbidden element))))
60707983 (t (throw 'objects-forbidden element)))
6071 ;; Also change type to retrieve correct restrictions.
6072 (setq type 'keyword))
6073 ;; At an item, objects can only be located within tag, if any.
6074 ((eq type 'item)
6075 (let ((tag (org-element-property :tag element)))
6076 (if (or (not tag) (/= (line-beginning-position) post))
6077 (throw 'objects-forbidden element)
6078 (beginning-of-line)
6079 (search-forward tag (line-end-position))
6080 (goto-char (match-beginning 0))
6081 (if (and (>= pos (point)) (< pos (match-end 0)))
6082 (narrow-to-region (point) (match-end 0))
6083 (throw 'objects-forbidden element)))))
6084 ;; At an headline or inlinetask, objects are in title.
6085 ((memq type '(headline inlinetask))
6086 (let ((case-fold-search nil))
6087 (goto-char (org-element-property :begin element))
6088 (looking-at org-complex-heading-regexp)
6089 (let ((end (match-end 4)))
6090 (if (not end) (throw 'objects-forbidden element)
6091 (goto-char (match-beginning 4))
6092 (when (looking-at org-comment-string)
6093 (goto-char (match-end 0)))
6094 (if (>= (point) end) (throw 'objects-forbidden element)
6095 (narrow-to-region (point) end))))))
6096 ;; At a paragraph, a table-row or a verse block, objects are
6097 ;; located within their contents.
6098 ((memq type '(paragraph table-row verse-block))
6099 (let ((cbeg (org-element-property :contents-begin element))
6100 (cend (org-element-property :contents-end element)))
6101 ;; CBEG is nil for table rules.
6102 (if (and cbeg cend (>= pos cbeg)
6103 (or (< pos cend) (and (= pos cend) (eobp))))
6104 (narrow-to-region cbeg cend)
6105 (throw 'objects-forbidden element))))
6106 (t (throw 'objects-forbidden element)))
6107 (goto-char (point-min))
6108 (let ((restriction (org-element-restriction type))
6109 (parent element)
6110 last)
6111 (catch 'exit
6112 (while t
6113 (let ((next (org-element--object-lex restriction)))
6114 (when next (org-element-put-property next :parent parent))
6115 ;; Process NEXT, if any, in order to know if we need to
6116 ;; skip it, return it or move into it.
6117 (if (or (not next) (> (org-element-property :begin next) pos))
6118 (throw 'exit (or last parent))
6119 (let ((end (org-element-property :end next))
6120 (cbeg (org-element-property :contents-begin next))
6121 (cend (org-element-property :contents-end next)))
6122 (cond
6123 ;; Skip objects ending before point. Also skip
6124 ;; objects ending at point unless it is also the
6125 ;; end of buffer, since we want to return the
6126 ;; innermost object.
6127 ((and (<= end pos) (/= (point-max) end))
6128 (goto-char end)
6129 ;; For convenience, when object ends at POS,
6130 ;; without any space, store it in LAST, as we
6131 ;; will return it if no object starts here.
6132 (when (and (= end pos)
6133 (not (memq (char-before) '(?\s ?\t))))
6134 (setq last next)))
6135 ;; If POS is within a container object, move into
6136 ;; that object.
6137 ((and cbeg cend
6138 (>= pos cbeg)
6139 (or (< pos cend)
6140 ;; At contents' end, if there is no
6141 ;; space before point, also move into
6142 ;; object, for consistency with
6143 ;; convenience feature above.
6144 (and (= pos cend)
6145 (or (= (point-max) pos)
6146 (not (memq (char-before pos)
6147 '(?\s ?\t)))))))
6148 (goto-char cbeg)
6149 (narrow-to-region (point) cend)
6150 (setq parent next)
6151 (setq restriction (org-element-restriction next)))
6152 ;; Otherwise, return NEXT.
6153 (t (throw 'exit next)))))))))))))
7984 (goto-char (point-min))
7985 (let ((restriction (org-element-restriction type))
7986 (parent element)
7987 last)
7988 (catch 'exit
7989 (while t
7990 (let ((next (org-element--object-lex restriction)))
7991 (when next (org-element-put-property next :parent parent))
7992 ;; Process NEXT, if any, in order to know if we need to
7993 ;; skip it, return it or move into it.
7994 (if (or (not next) (> (org-element-property :begin next) pos))
7995 (throw 'exit (or last parent))
7996 (let ((end (org-element-property :end next))
7997 (cbeg (org-element-property :contents-begin next))
7998 (cend (org-element-property :contents-end next)))
7999 (cond
8000 ;; Skip objects ending before point. Also skip
8001 ;; objects ending at point unless it is also the
8002 ;; end of buffer, since we want to return the
8003 ;; innermost object.
8004 ((and (<= end pos) (/= (point-max) end))
8005 (goto-char end)
8006 ;; For convenience, when object ends at POS,
8007 ;; without any space, store it in LAST, as we
8008 ;; will return it if no object starts here.
8009 (when (and (= end pos)
8010 (not (memq (char-before) '(?\s ?\t))))
8011 (setq last next)))
8012 ;; If POS is within a container object, move into
8013 ;; that object.
8014 ((and cbeg cend
8015 (>= pos cbeg)
8016 (or (< pos cend)
8017 ;; At contents' end, if there is no
8018 ;; space before point, also move into
8019 ;; object, for consistency with
8020 ;; convenience feature above.
8021 (and (= pos cend)
8022 (or (= (point-max) pos)
8023 (not (memq (char-before pos)
8024 '(?\s ?\t)))))))
8025 (goto-char cbeg)
8026 (narrow-to-region (point) cend)
8027 (setq parent next)
8028 (setq restriction (org-element-restriction next)))
8029 ;; Otherwise, return NEXT.
8030 (t (throw 'exit next))))))))))))))
61548031
61558032 (defun org-element-lineage (datum &optional types with-self)
61568033 "List all ancestors of a given element or object.
62008077 (when (and specialp
62018078 (or (not (eq (org-element-type elem-B) 'paragraph))
62028079 (/= (org-element-property :begin elem-B)
6203 (org-element-property :contents-begin elem-B))))
8080 (org-element-property :contents-begin elem-B))))
62048081 (error "Cannot swap elements"))
6205 ;; In a special situation, ELEM-A will have no indentation. We'll
6206 ;; give it ELEM-B's (which will in, in turn, have no indentation).
6207 (let* ((ind-B (when specialp
6208 (goto-char (org-element-property :begin elem-B))
6209 (current-indentation)))
6210 (beg-A (org-element-property :begin elem-A))
6211 (end-A (save-excursion
6212 (goto-char (org-element-property :end elem-A))
6213 (skip-chars-backward " \r\t\n")
6214 (point-at-eol)))
6215 (beg-B (org-element-property :begin elem-B))
6216 (end-B (save-excursion
6217 (goto-char (org-element-property :end elem-B))
6218 (skip-chars-backward " \r\t\n")
6219 (point-at-eol)))
6220 ;; Store inner overlays responsible for visibility status.
6221 ;; We also need to store their boundaries as they will be
6222 ;; removed from buffer.
6223 (overlays
6224 (cons
6225 (delq nil
6226 (mapcar (lambda (o)
6227 (and (>= (overlay-start o) beg-A)
6228 (<= (overlay-end o) end-A)
6229 (list o (overlay-start o) (overlay-end o))))
6230 (overlays-in beg-A end-A)))
6231 (delq nil
6232 (mapcar (lambda (o)
6233 (and (>= (overlay-start o) beg-B)
6234 (<= (overlay-end o) end-B)
6235 (list o (overlay-start o) (overlay-end o))))
6236 (overlays-in beg-B end-B)))))
6237 ;; Get contents.
6238 (body-A (buffer-substring beg-A end-A))
6239 (body-B (delete-and-extract-region beg-B end-B)))
6240 (goto-char beg-B)
6241 (when specialp
6242 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
6243 (indent-to-column ind-B))
6244 (insert body-A)
6245 ;; Restore ex ELEM-A overlays.
6246 (let ((offset (- beg-B beg-A)))
6247 (dolist (o (car overlays))
6248 (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
8082 ;; Preserve folding state when `org-fold-core-style' is set to
8083 ;; `text-properties'.
8084 (org-fold-core-ignore-modifications
8085 ;; In a special situation, ELEM-A will have no indentation. We'll
8086 ;; give it ELEM-B's (which will in, in turn, have no indentation).
8087 (let* ((ind-B (when specialp
8088 (goto-char (org-element-property :begin elem-B))
8089 (current-indentation)))
8090 (beg-A (org-element-property :begin elem-A))
8091 (end-A (save-excursion
8092 (goto-char (org-element-property :end elem-A))
8093 (skip-chars-backward " \r\t\n")
8094 (line-end-position)))
8095 (beg-B (org-element-property :begin elem-B))
8096 (end-B (save-excursion
8097 (goto-char (org-element-property :end elem-B))
8098 (skip-chars-backward " \r\t\n")
8099 (line-end-position)))
8100 ;; Store inner folds responsible for visibility status.
8101 (folds
8102 (cons
8103 (org-fold-core-get-regions :from beg-A :to end-A :relative t)
8104 (org-fold-core-get-regions :from beg-B :to end-B :relative t)))
8105 ;; Get contents.
8106 (body-A (buffer-substring beg-A end-A))
8107 (body-B (buffer-substring beg-B end-B)))
8108 ;; Clear up the folds.
8109 (org-fold-region beg-A end-A nil)
8110 (org-fold-region beg-B end-B nil)
8111 (delete-region beg-B end-B)
8112 (goto-char beg-B)
8113 (when specialp
8114 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
8115 (indent-to-column ind-B))
8116 (insert body-A)
8117 ;; Restore ex ELEM-A folds.
8118 (org-fold-core-regions (car folds) :relative beg-B)
62498119 (goto-char beg-A)
62508120 (delete-region beg-A end-A)
62518121 (insert body-B)
6252 ;; Restore ex ELEM-B overlays.
6253 (dolist (o (cdr overlays))
6254 (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
6255 (goto-char (org-element-property :end elem-B)))))
6256
8122 ;; Restore ex ELEM-A folds.
8123 (org-fold-core-regions (cdr folds) :relative beg-A)
8124 (goto-char (org-element-property :end elem-B))))))
62578125
62588126 (provide 'org-element)
62598127
00 ;;; org-entities.el --- Support for Special Entities -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>,
55 ;; Ulf Stegemann <ulf at zeitform dot de>
66 ;; Keywords: outlines, calendar, wp
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88 ;;
99 ;; This file is part of GNU Emacs.
1010 ;;
2525 ;;; Commentary:
2626
2727 ;;; Code:
28
29 (require 'org-macs)
30 (org-assert-version)
2831
2932 (declare-function org-mode "org" ())
3033 (declare-function org-toggle-pretty-entities "org" ())
8891 ("aacute" "\\'{a}" nil "&aacute;" "a" "á" "á")
8992 ("Acirc" "\\^{A}" nil "&Acirc;" "A" "Â" "Â")
9093 ("acirc" "\\^{a}" nil "&acirc;" "a" "â" "â")
91 ("Amacr" "\\bar{A}" nil "&Amacr;" "A" "Ã" "Ã")
92 ("amacr" "\\bar{a}" nil "&amacr;" "a" "ã" "ã")
94 ("Amacr" "\\={A}" nil "&Amacr;" "A" "Ã" "Ã")
95 ("amacr" "\\={a}" nil "&amacr;" "a" "ã" "ã")
9396 ("Atilde" "\\~{A}" nil "&Atilde;" "A" "Ã" "Ã")
9497 ("atilde" "\\~{a}" nil "&atilde;" "a" "ã" "ã")
9598 ("Auml" "\\\"{A}" nil "&Auml;" "Ae" "Ä" "Ä")
306309 ("trade" "\\texttrademark{}" nil "&trade;" "TM" "TM" "™")
307310
308311 "** Science et al."
309 ("minus" "\\minus" t "&minus;" "-" "-" "−")
312 ("minus" "-" t "&minus;" "-" "-" "−")
310313 ("pm" "\\textpm{}" nil "&plusmn;" "+-" "±" "±")
311314 ("plusmn" "\\textpm{}" nil "&plusmn;" "+-" "±" "±")
312315 ("times" "\\texttimes{}" nil "&times;" "*" "×" "×")
00 ;;; org-faces.el --- Face definitions -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2727
2828 ;;; Code:
2929
30 (require 'org-macs)
31 (org-assert-version)
32
3033 (defgroup org-faces nil
3134 "Faces in Org mode."
3235 :tag "Org Faces"
3740 :group 'org-faces)
3841
3942 (defface org-hide
40 '((default :inherit fixed-pitch)
41 (((background light)) (:foreground "white"))
43 '((((background light)) (:foreground "white"))
4244 (((background dark)) (:foreground "black")))
4345 "Face used to hide leading stars in headlines.
4446 The foreground color of this face should be equal to the background
105107 "Face used for drawers."
106108 :group 'org-faces)
107109
108 (defface org-property-value nil
110 (defface org-property-value '((t :inherit default))
109111 "Face used for the value of a property."
110112 :group 'org-faces)
111113
137139
138140 Since column view works by putting overlays with a display property
139141 over individual characters in the buffer, the face of the underlining
140 character (this might for example be the a TODO keyword) might still
142 character (this might for example be the TODO keyword) might still
141143 shine through in some properties. So when your column view looks
142144 funny, with \"random\" colors, weight, strike-through, try to explicitly
143145 set the properties in the `org-column' face. For example, set
201203 :group 'org-faces)
202204
203205 (defface org-date
204 '((default :inherit fixed-pitch)
205 (((class color) (background light)) (:foreground "Purple" :underline t))
206 '((((class color) (background light)) (:foreground "Purple" :underline t))
206207 (((class color) (background dark)) (:foreground "Cyan" :underline t))
207208 (t (:underline t)))
208209 "Face for date/time stamps."
339340
340341 (defvar org-tags-special-faces-re nil)
341342 (defun org-set-tag-faces (var value)
342 (set var value)
343 (set-default-toplevel-value var value)
343344 (if (not value)
344345 (setq org-tags-special-faces-re nil)
345346 (setq org-tags-special-faces-re
378379 (sexp :tag "Face")))))
379380
380381 (defface org-table ;Copied from `font-lock-function-name-face'
381 '((default :inherit fixed-pitch)
382 (((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
382 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
383383 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
384384 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
385385 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
395395 :group 'org-faces)
396396
397397 (defface org-formula
398 '((default :inherit fixed-pitch)
399 (((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
398 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
400399 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
401400 (((class color) (min-colors 8) (background light)) (:foreground "red"))
402401 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
404403 "Face for formulas."
405404 :group 'org-faces)
406405
407 (defface org-code '((t :inherit (fixed-pitch shadow)))
406 (defface org-code '((t :inherit shadow))
408407 "Face for fixed-width text like code snippets."
409408 :group 'org-faces
410409 :version "22.1")
411410
412 (defface org-meta-line '((t :inherit (fixed-pitch font-lock-comment-face)))
411 (defface org-meta-line '((t :inherit font-lock-comment-face))
413412 "Face for meta lines starting with \"#+\"."
414413 :group 'org-faces
415414 :version "22.1")
436435 #+EMAIL: and #+DATE: keywords."
437436 :group 'org-faces)
438437
439 (defface org-block `((t :inherit (fixed-pitch shadow)
438 (defface org-block `((t :inherit shadow
440439 ,@(and (>= emacs-major-version 27) '(:extend t))))
441440 "Face used for text inside various blocks.
442441
458457 "Face used for the line delimiting the end of source blocks."
459458 :group 'org-faces)
460459
461 (defface org-verbatim '((t (:inherit (fixed-pitch shadow))))
460 (defface org-inline-src-block '((t (:inherit org-block)))
461 "Face used for inline source blocks as a whole."
462 :group 'org-faces)
463
464 (defface org-verbatim '((t (:inherit shadow)))
462465 "Face for fixed-with text like code snippets."
463466 :group 'org-faces
464467 :version "22.1")
513516 (defface org-agenda-structure-filter '((t (:inherit (org-warning org-agenda-structure))))
514517 "Face used for the current type of task filter in the agenda.
515518 It inherits from `org-agenda-structure' so it can adapt to
516 it (e.g. if that is assigned a diffent font height or family)."
519 it (e.g. if that is assigned a different font height or family)."
517520 :group 'org-faces)
518521
519522 (defface org-agenda-date '((t (:inherit org-agenda-structure)))
596599 (0.0 . org-upcoming-distant-deadline))
597600 "Faces for showing deadlines in the agenda.
598601 This is a list of cons cells. The cdr of each cell is a face to be used,
599 and it can also just be like \\='(:foreground \"yellow\").
602 and it can also just be like (:foreground \"yellow\").
600603 Each car is a fraction of the head-warning time that must have passed for
601604 this the face in the cdr to be used for display. The numbers must be
602605 given in descending order. The head-warning time is normally taken
00 ;;; org-feed.el --- Add RSS feed items to Org files -*- lexical-binding: t; -*-
11 ;;
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
8686 ;; similar mechanism using shell and awk scripts.
8787
8888 ;;; Code:
89
90 (require 'org-macs)
91 (org-assert-version)
8992
9093 (require 'org)
9194 (require 'sha1)
405408
406409 ;; Write the new status
407410 ;; We do this only now, in case something goes wrong above, so
408 ;; that would would end up with a status that does not reflect
411 ;; that would end up with a status that does not reflect
409412 ;; which items truly have been handled
410413 (org-feed-write-status inbox-pos drawer status)
411414
412415 ;; Normalize the visibility of the inbox tree
413416 (goto-char inbox-pos)
414 (org-flag-subtree t)
415 (org-show-children)
417 (org-fold-subtree t)
418 (org-fold-show-children)
416419
417420 ;; Hooks and messages
418421 (when org-feed-save-after-adding (save-buffer))
0 ;;; org-fold-core.el --- Folding buffer text -*- lexical-binding: t; -*-
1 ;;
2 ;; Copyright (C) 2020-2023 Free Software Foundation, Inc.
3 ;;
4 ;; Author: Ihor Radchenko <yantar92 at gmail dot com>
5 ;; Keywords: folding, invisible text
6 ;; URL: https://orgmode.org
7 ;;
8 ;; This file is part of GNU Emacs.
9 ;;
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
22 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
23 ;;
24 ;;; Commentary:
25
26 ;; This file contains library to control temporary invisibility
27 ;; (folding and unfolding) of text in buffers.
28
29 ;; The file implements the following functionality:
30 ;;
31 ;; - Folding/unfolding regions of text
32 ;; - Searching and examining boundaries of folded text
33 ;; - Interactive searching in folded text (via isearch)
34 ;; - Handling edits in folded text
35 ;; - Killing/yanking (copying/pasting) of the folded text
36
37 ;; To setup folding in an arbitrary buffer, one must call
38 ;; `org-fold-core-initialize', optionally providing the list of folding specs to be
39 ;; used in the buffer. The specs can be added, removed, or
40 ;; re-configured later. Read below for more details.
41
42 ;;; Folding/unfolding regions of text
43
44 ;; User can temporarily hide/reveal (fold/unfold) arbitrary regions or
45 ;; text. The folds can be nested.
46
47 ;; Internally, nested folds are marked with different folding specs
48 ;; Overlapping folds marked with the same folding spec are
49 ;; automatically merged, while folds with different folding specs can
50 ;; coexist and be folded/unfolded independently.
51
52 ;; When multiple folding specs are applied to the same region of text,
53 ;; text visibility is decided according to the folding spec with
54 ;; topmost priority.
55
56 ;; By default, we define two types of folding specs:
57 ;; - 'org-fold-visible :: the folded text is not hidden
58 ;; - 'org-fold-hidden :: the folded text is completely hidden
59 ;;
60 ;; The 'org-fold-visible spec has highest priority allowing parts of
61 ;; text folded with 'org-fold-hidden to be shown unconditionally.
62
63 ;; Consider the following Org mode link:
64 ;; [[file:/path/to/file/file.ext][description]]
65 ;; Only the word "description" is normally visible in this link.
66 ;;
67 ;; The way this partial visibility is achieved is combining the two
68 ;; folding specs. The whole link is folded using 'org-fold-hidden
69 ;; folding spec, but the visible part is additionally folded using
70 ;; 'org-fold-visible:
71 ;;
72 ;; <begin org-fold-hidden>[[file:/path/to/file/file.ext][<begin org-fold-visible>description<end org-fold-visible>]]<end org-fold-hidden>
73 ;;
74 ;; Because 'org-fold-visible has higher priority than
75 ;; 'org-fold-hidden, it suppresses the 'org-fold-hidden effect and
76 ;; thus reveals the description part of the link.
77
78 ;; Similar to 'org-fold-visible, display of any arbitrary folding spec
79 ;; can be configured using folding spec properties. In particular,
80 ;; `:visible' folding spec property controls whether the folded text
81 ;; is visible or not. If the `:visible' folding spec property is nil,
82 ;; folded text is hidden or displayed as a constant string (ellipsis)
83 ;; according to the value of `:ellipsis' folding spec property. See
84 ;; docstring of `org-fold-core--specs' for the description of all the available
85 ;; folding spec properties.
86
87 ;; Folding spec properties of any valid folding spec can be changed
88 ;; any time using `org-fold-core-set-folding-spec-property'.
89
90 ;; If necessary, one can add or remove folding specs using
91 ;; `org-fold-core-add-folding-spec' and `org-fold-core-remove-folding-spec'.
92
93 ;; If a buffer initialized with `org-fold-core-initialize' is cloned into indirect
94 ;; buffers, it's folding state is copied to that indirect buffer.
95 ;; The folding states are independent.
96
97 ;; When working with indirect buffers that are handled by this
98 ;; library, one has to keep in mind that folding state is preserved on
99 ;; copy when using non-interactive functions. Moreover, the folding
100 ;; states of all the indirect buffers will be copied together.
101 ;;
102 ;; Example of the implications:
103 ;; Consider a base buffer and indirect buffer with the following state:
104 ;; ----- base buffer --------
105 ;; * Heading<begin fold>
106 ;; Some text folded in the base buffer, but unfolded in the indirect buffer<end fold>
107 ;; * Other heading
108 ;; Heading unfolded in both the buffers.
109 ;; ---------------------------
110 ;; ------ indirect buffer ----
111 ;; * Heading
112 ;; Some text folded in the base buffer, but unfolded in the indirect buffer
113 ;; * Other heading
114 ;; Heading unfolded in both the buffers.
115 ;; ----------------------------
116 ;; If some Elisp code copies the whole "Heading" from the indirect
117 ;; buffer with `buffer-substring' or match data and inserts it into
118 ;; the base buffer, the inserted heading will be folded since the
119 ;; internal setting for the folding state is shared between the base
120 ;; and indirect buffers. It's just that the indirect buffer ignores
121 ;; the base buffer folding settings. However, as soon as the text is
122 ;; copied back to the base buffer, the folding state will become
123 ;; respected again.
124
125 ;; If the described situation is undesired, Elisp code can use
126 ;; `filter-buffer-substring' instead of `buffer-substring'. All the
127 ;; folding states that do not belong to the currently active buffer
128 ;; will be cleared in the copied text then. See
129 ;; `org-fold-core--buffer-substring-filter' for more details.
130
131 ;; Because of details of implementation of the folding, it is also not
132 ;; recommended to set text visibility in buffer directly by setting
133 ;; `invisible' text property to anything other than t. While this
134 ;; should usually work just fine, normal folding can be broken if one
135 ;; sets `invisible' text property to a value not listed in
136 ;; `buffer-invisibility-spec'.
137
138 ;;; Searching and examining boundaries of folded text
139
140 ;; It is possible to examine folding specs (there may be several) of
141 ;; text at point or search for regions with the same folding spec.
142 ;; See functions defined under ";;;; Searching and examining folded
143 ;; text" below for details.
144
145 ;; All the folding specs can be specified by symbol representing their
146 ;; name. However, this is not always convenient, especially if the
147 ;; same spec can be used for fold different syntactical structures.
148 ;; Any folding spec can be additionally referenced by a symbol listed
149 ;; in the spec's `:alias' folding spec property. For example, Org
150 ;; mode's `org-fold-outline' folding spec can be referenced as any
151 ;; symbol from the following list: '(headline heading outline
152 ;; inlinetask plain-list) The list is the value of the spec's `:alias'
153 ;; property.
154
155 ;; Most of the functions defined below that require a folding spec
156 ;; symbol as their argument, can also accept any symbol from the
157 ;; `:alias' spec property to reference that folding spec.
158
159 ;; If one wants to search invisible text without using the provided
160 ;; functions, it is important to keep in mind that 'invisible text
161 ;; property may have multiple possible values (not just nil and
162 ;; t). Hence, (next-single-char-property-change pos 'invisible) is not
163 ;; guaranteed to return the boundary of invisible/visible text.
164
165 ;;; Interactive searching inside folded text (via isearch)
166
167 ;; The library provides a way to control if the folded text can be
168 ;; searchable using isearch. If the text is searchable, it is also
169 ;; possible to control to unfold it temporarily during interactive
170 ;; isearch session.
171
172 ;; The isearch behavior is controlled on per-folding-spec basis by
173 ;; setting `isearch-open' and `isearch-ignore' folding spec
174 ;; properties. The the docstring of `org-fold-core--specs' for more details.
175
176 ;;; Handling edits inside folded text
177
178 ;; The visibility of the text inserted in front, rear, or in the
179 ;; middle of a folded region is managed according to `:front-sticky'
180 ;; and `:rear-sticky' folding properties of the corresponding folding
181 ;; spec. The rules are the same with stickiness of text properties in
182 ;; Elisp.
183
184 ;; If a text being inserted into the buffer is already folded and
185 ;; invisible (before applying the stickiness rules), then it is
186 ;; revealed. This behavior can be changed by wrapping the insertion
187 ;; code into `org-fold-core-ignore-modifications' macro. The macro will disable
188 ;; all the processing related to buffer modifications.
189
190 ;; The library also provides a way to unfold the text after some
191 ;; destructive changes breaking syntactical structure of the buffer.
192 ;; For example, Org mode automatically reveals folded drawers when the
193 ;; drawer becomes syntactically incorrect:
194 ;; ------- before modification -------
195 ;; :DRAWER:<begin fold>
196 ;; Some folded text inside drawer
197 ;; :END:<end fold>
198 ;; -----------------------------------
199 ;; If the ":END:" is edited, drawer syntax is not correct anymore and
200 ;; the folded text is automatically unfolded.
201 ;; ------- after modification --------
202 ;; :DRAWER:
203 ;; Some folded text inside drawer
204 ;; :EN:
205 ;; -----------------------------------
206
207 ;; The described automatic unfolding is controlled by `:fragile'
208 ;; folding spec property. It's value can be a function checking if
209 ;; changes inside (or around) the fold should drigger the unfold. By
210 ;; default, only changes that directly involve folded regions will
211 ;; trigger the check. In addition, `org-fold-core-extend-changed-region-functions'
212 ;; can be set to extend the checks to all folded regions intersecting
213 ;; with the region returned by the functions listed in the variable.
214
215 ;; The fragility checks can be bypassed if the code doing
216 ;; modifications is wrapped into `org-fold-core-ignore-fragility-checks' macro.
217
218 ;;; Performance considerations
219
220 ;; This library is using text properties to hide text. Text
221 ;; properties are much faster than overlays, that could be used for
222 ;; the same purpose. Overlays are implemented with O(n) complexity in
223 ;; Emacs (as for 2021-03-11). It means that any attempt to move
224 ;; through hidden text in a file with many invisible overlays will
225 ;; require time scaling with the number of folded regions (the problem
226 ;; Overlays note of the manual warns about). For curious, historical
227 ;; reasons why overlays are not efficient can be found in
228 ;; https://www.jwz.org/doc/lemacs.html.
229
230 ;; Despite using text properties, the performance is still limited by
231 ;; Emacs display engine. For example, >7Mb of text hidden within
232 ;; visible part of a buffer may cause noticeable lags (which is still
233 ;; orders of magnitude better in comparison with overlays). If the
234 ;; performance issues become critical while using this library, it is
235 ;; recommended to minimize the number of folding specs used in the
236 ;; same buffer at a time.
237
238 ;; Alternatively, the library provides `org-fold-core--optimise-for-huge-buffers'
239 ;; for additional speedup. This can be used as a file-local variable
240 ;; in huge buffers. The variable can be set to enable various levels
241 ;; of extra optimization. See the docstring for detailed information.
242
243 ;; It is worth noting that when using `org-fold-core--optimise-for-huge-buffers'
244 ;; with `grab-invisible' option, folded regions copied to other
245 ;; buffers (including buffers that do not use this library) will
246 ;; remain invisible. org-fold-core provides functions to work around
247 ;; this issue: `org-fold-core-remove-optimisation' and `org-fold-core-update-optimisation', but
248 ;; it is unlikely that a random external package will use them.
249
250 ;; Another possible bottleneck is the fragility check after the change
251 ;; related to the folded text. The functions used in `:fragile'
252 ;; folding properties must be optimized. Also,
253 ;; `org-fold-core-ignore-fragility-checks' or even `org-fold-core-ignore-modifications' may be
254 ;; used when appropriate in the performance-critical code. When
255 ;; inserting text from within `org-fold-core-ignore-modifications' macro, it is
256 ;; recommended to use `insert-and-inherit' instead of `insert' and
257 ;; `insert-before-markers-and-inherit' instead of
258 ;; `insert-before-markers' to avoid revealing inserted text in the
259 ;; middle of a folded region.
260
261 ;; Performance of isearch is currently limited by Emacs isearch
262 ;; implementation. For now, Emacs isearch only supports searching
263 ;; through text hidden using overlays. This library handles isearch
264 ;; by converting folds with matching text to overlays, which may
265 ;; affect performance in case of large number of matches. In the
266 ;; future, Emacs will hopefully accept the relevant patch allowing
267 ;; isearch to work with text hidden via text properties, but the
268 ;; performance hit has to be accepted meanwhile.
269
270 ;;; Code:
271
272 (require 'org-macs)
273 (org-assert-version)
274
275 (require 'org-macs)
276 (require 'org-compat)
277
278 (declare-function isearch-filter-visible "isearch" (beg end))
279
280 ;;; Customization
281
282 (defcustom org-fold-core-style 'text-properties
283 "Internal implementation detail used to hide folded text.
284 Can be either `text-properties' or `overlays'.
285 The former is faster on large files, while the latter is generally
286 less error-prone with regard to third-party packages that haven't yet
287 adapted to the new folding implementation.
288
289 Important: This variable must be set before loading Org."
290 :group 'org
291 :package-version '(Org . "9.6")
292 :type '(choice
293 (const :tag "Overlays" overlays)
294 (const :tag "Text properties" text-properties)))
295
296 (defvar-local org-fold-core-isearch-open-function #'org-fold-core--isearch-reveal
297 "Function used to reveal hidden text found by isearch.
298 The function is called with a single argument - point where text is to
299 be revealed.")
300
301 (defvar-local org-fold-core--optimise-for-huge-buffers nil
302 "Non-nil turns on extra speedup on huge buffers (Mbs of folded text).
303
304 This setting is risky and may cause various artifacts and degraded
305 functionality, especially when using external packages. It is
306 recommended to enable it on per-buffer basis as file-local variable.
307
308 When set to non-nil, must be a list containing one or multiple the
309 following symbols:
310
311 - `grab-invisible': Use `invisible' text property to hide text. This
312 will reduce the load on Emacs display engine and one may use it if
313 moving point across folded regions becomes slow. However, as a side
314 effect, some external packages extracting i.e. headlings from folded
315 parts of buffer may keep the text invisible.
316
317 - `ignore-fragility-checks': Do not try to detect when user edits
318 break structure of the folded elements. This will speed up
319 modifying the folded regions at the cost that some higher-level
320 functions relying on this package might not be able to unfold the
321 edited text. For example, removed leading stars from a folded
322 headline in Org mode will break visibility cycling since Org mode
323 will not be aware that the following folded text belonged to
324 headline.
325
326 - `ignore-modification-checks': Do not try to detect insertions in the
327 middle of the folded regions. This will speed up non-interactive
328 edits of the folded regions. However, text inserted in the middle
329 of the folded regions may become visible for some external packages
330 inserting text using `insert' instead of `insert-and-inherit' (the
331 latter is rarely used in practice).
332
333 - `ignore-indirect': Do not decouple folding state in the indirect
334 buffers. This can speed up Emacs display engine (and thus motion of
335 point), especially when large number of indirect buffers is being
336 used.
337
338 - `merge-folds': Do not distinguish between different types of folding
339 specs. This is the most aggressive optimization with unforeseen and
340 potentially drastic effects.")
341 (put 'org-fold-core--optimise-for-huge-buffers 'safe-local-variable 'listp)
342
343 ;;; Core functionality
344
345 ;;;; Folding specs
346
347 (defvar-local org-fold-core--specs '((org-fold-visible
348 (:visible . t)
349 (:alias . (visible)))
350 (org-fold-hidden
351 (:ellipsis . "...")
352 (:isearch-open . t)
353 (:alias . (hidden))))
354 "Folding specs defined in current buffer.
355
356 Each spec is a list (SPEC-SYMBOL SPEC-PROPERTIES).
357 SPEC-SYMBOL is the symbol representing the folding spec.
358 SPEC-PROPERTIES is an alist defining folding spec properties.
359
360 If a text region is folded using multiple specs, only the folding spec
361 listed earlier is used.
362
363 The following properties are known:
364 - :ellipsis :: must be nil or string to show when text is folded
365 using this spec.
366 - :global :: non-nil means that folding state will be preserved
367 when copying folded text between buffers.
368 - :isearch-ignore :: non-nil means that folded text is not searchable
369 using isearch.
370 - :isearch-open :: non-nil means that isearch can reveal text hidden
371 using this spec. This property does nothing
372 when `isearch-ignore' property is non-nil.
373 - :front-sticky :: non-nil means that text prepended to the folded text
374 is automatically folded.
375 - :rear-sticky :: non-nil means that text appended to the folded text
376 is folded.
377 - :visible :: non-nil means that folding spec visibility is not
378 managed. Instead, visibility settings in
379 `buffer-invisibility-spec' will be used as is.
380 Note that changing this property from nil to t may
381 clear the setting in `buffer-invisibility-spec'.
382 - :alias :: a list of aliases for the SPEC-SYMBOL.
383 - :fragile :: Must be a function accepting two arguments.
384 Non-nil means that changes in region may cause
385 the region to be revealed. The region is
386 revealed after changes if the function returns
387 non-nil.
388 The function called after changes are made with
389 two arguments: cons (beg . end) representing the
390 folded region and spec symbol.")
391 (defvar-local org-fold-core--spec-symbols nil
392 "Alist holding buffer spec symbols and aliases.
393
394 This variable is defined to reduce load on Emacs garbage collector
395 reducing the number of transiently allocated variables.")
396 (defvar-local org-fold-core--spec-list nil
397 "List holding buffer spec symbols, but not aliases.
398
399 This variable is defined to reduce load on Emacs garbage collector
400 reducing the number of transiently allocated variables.")
401
402 (defvar-local org-fold-core-extend-changed-region-functions nil
403 "Special hook run just before handling changes in buffer.
404
405 This is used to account changes outside folded regions that still
406 affect the folded region visibility. For example, removing all stars
407 at the beginning of a folded Org mode heading should trigger the
408 folded text to be revealed. Each function is called with two
409 arguments: beginning and the end of the changed region.")
410
411 ;;; Utility functions
412
413 (defsubst org-fold-core-folding-spec-list (&optional buffer)
414 "Return list of all the folding spec symbols in BUFFER."
415 (or (buffer-local-value 'org-fold-core--spec-list (or buffer (current-buffer)))
416 (with-current-buffer (or buffer (current-buffer))
417 (setq org-fold-core--spec-list (mapcar #'car org-fold-core--specs)))))
418
419 (defun org-fold-core-get-folding-spec-from-alias (spec-or-alias)
420 "Return the folding spec symbol for SPEC-OR-ALIAS.
421 Return nil when there is no matching folding spec."
422 (when spec-or-alias
423 (unless org-fold-core--spec-symbols
424 (dolist (spec (org-fold-core-folding-spec-list))
425 (push (cons spec spec) org-fold-core--spec-symbols)
426 (dolist (alias (assq :alias (assq spec org-fold-core--specs)))
427 (push (cons alias spec) org-fold-core--spec-symbols))))
428 (alist-get spec-or-alias org-fold-core--spec-symbols)))
429
430 (defsubst org-fold-core-folding-spec-p (spec-or-alias)
431 "Check if SPEC-OR-ALIAS is a registered folding spec."
432 (org-fold-core-get-folding-spec-from-alias spec-or-alias))
433
434 (defsubst org-fold-core--check-spec (spec-or-alias)
435 "Throw an error if SPEC-OR-ALIAS is not in `org-fold-core--spec-priority-list'."
436 (unless (org-fold-core-folding-spec-p spec-or-alias)
437 (error "%s is not a valid folding spec" spec-or-alias)))
438
439 (defsubst org-fold-core-get-folding-spec-property (spec-or-alias property)
440 "Get PROPERTY of a folding SPEC-OR-ALIAS.
441 Possible properties can be found in `org-fold-core--specs' docstring."
442 (org-fold-core--check-spec spec-or-alias)
443 (if (and (memql 'ignore-indirect org-fold-core--optimise-for-huge-buffers)
444 (eq property :global))
445 t
446 (if (and (memql 'merge-folds org-fold-core--optimise-for-huge-buffers)
447 (eq property :visible))
448 nil
449 (cdr (assq property (assq (org-fold-core-get-folding-spec-from-alias spec-or-alias) org-fold-core--specs))))))
450
451 (defconst org-fold-core--spec-property-prefix "org-fold--spec-"
452 "Prefix used to create property symbol.")
453
454 (defsubst org-fold-core-get-folding-property-symbol (spec &optional buffer global)
455 "Get folding text property using to store SPEC in current buffer or BUFFER.
456 If GLOBAL is non-nil, do not make the property unique in the BUFFER."
457 (if (memql 'merge-folds org-fold-core--optimise-for-huge-buffers)
458 (intern (format "%s-global" org-fold-core--spec-property-prefix))
459 (intern (format (concat org-fold-core--spec-property-prefix "%s-%S")
460 (symbol-name spec)
461 ;; (sxhash buf) appears to be not constant over time.
462 ;; Using buffer-name is safe, since the only place where
463 ;; buffer-local text property actually matters is an indirect
464 ;; buffer, where the name cannot be same anyway.
465 (if (or global
466 (memql 'ignore-indirect org-fold-core--optimise-for-huge-buffers))
467 'global
468 (sxhash (buffer-name (or buffer (current-buffer)))))))))
469
470 (defsubst org-fold-core-get-folding-spec-from-folding-prop (folding-prop)
471 "Return folding spec symbol used for folding property with name FOLDING-PROP."
472 (catch :exit
473 (dolist (spec (org-fold-core-folding-spec-list))
474 ;; We know that folding properties have
475 ;; folding spec in their name.
476 (when (string-match-p (symbol-name spec)
477 (symbol-name folding-prop))
478 (throw :exit spec)))))
479
480 (defvar org-fold-core--property-symbol-cache (make-hash-table :test 'equal)
481 "Saved values of folding properties for (buffer . spec) conses.")
482 (defvar-local org-fold-core--indirect-buffers nil
483 "List of indirect buffers created from current buffer.
484
485 The first element of the list is always the current buffer.
486
487 This variable is needed to work around Emacs bug#46982, while Emacs
488 does not provide a way `after-change-functions' in any other buffer
489 than the buffer where the change was actually made.")
490
491 (defmacro org-fold-core-cycle-over-indirect-buffers (&rest body)
492 "Execute BODY in current buffer and all its indirect buffers.
493
494 Also, make sure that folding properties from killed buffers are not
495 hanging around."
496 (declare (debug (form body)) (indent 0))
497 `(let (buffers dead-properties)
498 (if (and (not (buffer-base-buffer))
499 (not (memq (current-buffer) org-fold-core--indirect-buffers)))
500 ;; We are in base buffer with `org-fold-core--indirect-buffers' value from
501 ;; different buffer. This can happen, for example, when
502 ;; org-capture copies local variables into *Capture* buffer.
503 (setq buffers (list (current-buffer)))
504 (let ((all-buffers (buffer-local-value
505 'org-fold-core--indirect-buffers
506 (or (buffer-base-buffer) (current-buffer)))))
507 (dolist (buf (cons (or (buffer-base-buffer) (current-buffer))
508 (buffer-local-value 'org-fold-core--indirect-buffers (or (buffer-base-buffer) (current-buffer)))))
509 (if (buffer-live-p buf)
510 (push buf buffers)
511 (dolist (spec (org-fold-core-folding-spec-list))
512 (when (and (not (org-fold-core-get-folding-spec-property spec :global))
513 (gethash (cons buf spec) org-fold-core--property-symbol-cache))
514 ;; Make sure that dead-properties variable can be passed
515 ;; as argument to `remove-text-properties'.
516 (push t dead-properties)
517 (push (gethash (cons buf spec) org-fold-core--property-symbol-cache)
518 dead-properties)))))
519 (when dead-properties
520 (with-current-buffer (or (buffer-base-buffer) (current-buffer))
521 (setq-local org-fold-core--indirect-buffers
522 (seq-filter #'buffer-live-p all-buffers))))))
523 (dolist (buf buffers)
524 (with-current-buffer buf
525 (when dead-properties
526 (with-silent-modifications
527 (save-restriction
528 (widen)
529 (remove-text-properties
530 (point-min) (point-max)
531 dead-properties))))
532 ,@body))))
533
534 ;; This is the core function used to fold text in buffers. We use
535 ;; text properties to hide folded text, however 'invisible property is
536 ;; not directly used (unless risky `org-fold-core--optimise-for-huge-buffers' is
537 ;; enabled). Instead, we define unique text property (folding
538 ;; property) for every possible folding spec and add the resulting
539 ;; text properties into `char-property-alias-alist', so that
540 ;; 'invisible text property is automatically defined if any of the
541 ;; folding properties is non-nil. This approach lets us maintain
542 ;; multiple folds for the same text region - poor man's overlays (but
543 ;; much faster). Additionally, folding properties are ensured to be
544 ;; unique for different buffers (especially for indirect
545 ;; buffers). This is done to allow different folding states in
546 ;; indirect buffers.
547 (defun org-fold-core--property-symbol-get-create (spec &optional buffer return-only)
548 "Return a unique symbol suitable as folding text property.
549 Return value is unique for folding SPEC in BUFFER.
550 If the buffer already have buffer-local setup in `char-property-alias-alist'
551 and the setup appears to be created for different buffer,
552 copy the old invisibility state into new buffer-local text properties,
553 unless RETURN-ONLY is non-nil."
554 (if (eq org-fold-core-style 'overlays)
555 (org-fold-core-get-folding-property-symbol spec nil 'global)
556 (let* ((buf (or buffer (current-buffer))))
557 ;; Create unique property symbol for SPEC in BUFFER
558 (let ((local-prop (or (gethash (cons buf spec) org-fold-core--property-symbol-cache)
559 (puthash (cons buf spec)
560 (org-fold-core-get-folding-property-symbol
561 spec buf
562 (org-fold-core-get-folding-spec-property spec :global))
563 org-fold-core--property-symbol-cache))))
564 (prog1
565 local-prop
566 (unless return-only
567 (with-current-buffer buf
568 ;; Update folding properties carried over from other
569 ;; buffer (implying that current buffer is indirect
570 ;; buffer). Normally, `char-property-alias-alist' in new
571 ;; indirect buffer is a copy of the same variable from
572 ;; the base buffer. Then, `char-property-alias-alist'
573 ;; would contain folding properties, which are not
574 ;; matching the generated `local-prop'.
575 (unless (member local-prop (cdr (assq 'invisible char-property-alias-alist)))
576 ;; Add current buffer to the list of indirect buffers in the base buffer.
577 (when (buffer-base-buffer)
578 (with-current-buffer (buffer-base-buffer)
579 (setq-local org-fold-core--indirect-buffers
580 (let (bufs)
581 (org-fold-core-cycle-over-indirect-buffers
582 (push (current-buffer) bufs))
583 (push buf bufs)
584 (delete-dups bufs)))))
585 ;; Copy all the old folding properties to preserve the folding state
586 (with-silent-modifications
587 (dolist (old-prop (cdr (assq 'invisible char-property-alias-alist)))
588 (org-with-wide-buffer
589 (let* ((pos (point-min))
590 (spec (org-fold-core-get-folding-spec-from-folding-prop old-prop))
591 ;; Generate new buffer-unique folding property
592 (new-prop (when spec (org-fold-core--property-symbol-get-create spec nil 'return-only))))
593 ;; Copy the visibility state for `spec' from `old-prop' to `new-prop'
594 (unless (eq old-prop new-prop)
595 (while (< pos (point-max))
596 (let ((val (get-text-property pos old-prop))
597 (next (next-single-char-property-change pos old-prop)))
598 (when val
599 (put-text-property pos next new-prop val))
600 (setq pos next)))))))
601 ;; Update `char-property-alias-alist' with folding
602 ;; properties unique for the current buffer.
603 (setq-local char-property-alias-alist
604 (cons (cons 'invisible
605 (mapcar (lambda (spec)
606 (org-fold-core--property-symbol-get-create spec nil 'return-only))
607 (org-fold-core-folding-spec-list)))
608 (remove (assq 'invisible char-property-alias-alist)
609 char-property-alias-alist)))
610 ;; Set folding property stickiness according to
611 ;; their `:font-sticky' and `:rear-sticky'
612 ;; parameters.
613 (let (full-prop-list)
614 (org-fold-core-cycle-over-indirect-buffers
615 (setq full-prop-list
616 (append full-prop-list
617 (delq nil
618 (mapcar (lambda (spec)
619 (cond
620 ((org-fold-core-get-folding-spec-property spec :front-sticky)
621 (cons (org-fold-core--property-symbol-get-create spec nil 'return-only)
622 nil))
623 ((org-fold-core-get-folding-spec-property spec :rear-sticky)
624 nil)
625 (t
626 (cons (org-fold-core--property-symbol-get-create spec nil 'return-only)
627 t))))
628 (org-fold-core-folding-spec-list))))))
629 (org-fold-core-cycle-over-indirect-buffers
630 (setq-local text-property-default-nonsticky
631 (delete-dups (append
632 text-property-default-nonsticky
633 full-prop-list))))))))))))))
634
635 (defun org-fold-core-decouple-indirect-buffer-folds ()
636 "Copy and decouple folding state in a newly created indirect buffer.
637 This function is mostly intended to be used in
638 `clone-indirect-buffer-hook'."
639 (when (and (buffer-base-buffer)
640 (eq org-fold-core-style 'text-properties)
641 (not (memql 'ignore-indirect org-fold-core--optimise-for-huge-buffers)))
642 (org-fold-core--property-symbol-get-create (car (org-fold-core-folding-spec-list)))))
643
644 ;;; API
645
646 ;;;; Modifying folding specs
647
648 (defun org-fold-core-set-folding-spec-property (spec property value &optional force)
649 "Set PROPERTY of a folding SPEC to VALUE.
650 Possible properties and values can be found in `org-fold-core--specs' docstring.
651 Do not check previous value when FORCE is non-nil."
652 (pcase property
653 (:ellipsis
654 (unless (and (not force) (equal value (org-fold-core-get-folding-spec-property spec :ellipsis)))
655 (remove-from-invisibility-spec (cons spec (org-fold-core-get-folding-spec-property spec :ellipsis)))
656 (unless (org-fold-core-get-folding-spec-property spec :visible)
657 (add-to-invisibility-spec (cons spec value)))))
658 (:visible
659 (unless (or (memql 'merge-folds org-fold-core--optimise-for-huge-buffers)
660 (and (not force) (equal value (org-fold-core-get-folding-spec-property spec :visible))))
661 (if value
662 (remove-from-invisibility-spec (cons spec (org-fold-core-get-folding-spec-property spec :ellipsis)))
663 (add-to-invisibility-spec (cons spec (org-fold-core-get-folding-spec-property spec :ellipsis))))))
664 (:alias
665 ;; Clear symbol cache.
666 (setq org-fold-core--spec-symbols nil))
667 (:isearch-open nil)
668 (:isearch-ignore nil)
669 (:front-sticky nil)
670 (:rear-sticky nil)
671 (_ nil))
672 (setf (cdr (assq property (assq spec org-fold-core--specs))) value))
673
674 (defun org-fold-core-add-folding-spec (spec &optional properties buffer append)
675 "Add a new folding SPEC with PROPERTIES in BUFFER.
676
677 SPEC must be a symbol. BUFFER can be a buffer to set SPEC in or nil to
678 set SPEC in current buffer.
679
680 By default, the added SPEC will have highest priority among the
681 previously defined specs. When optional APPEND argument is non-nil,
682 SPEC will have the lowest priority instead. If SPEC was already
683 defined earlier, it will be redefined according to provided optional
684 arguments.
685 `
686 The folding spec properties will be set to PROPERTIES (see
687 `org-fold-core--specs' for details)."
688 (when (eq spec 'all) (error "Cannot use reserved folding spec symbol 'all"))
689 (with-current-buffer (or buffer (current-buffer))
690 ;; Clear the cache.
691 (setq org-fold-core--spec-list nil
692 org-fold-core--spec-symbols nil)
693 (let* ((full-properties (mapcar (lambda (prop) (cons prop (cdr (assq prop properties))))
694 '( :visible :ellipsis :isearch-ignore
695 :global :isearch-open :front-sticky
696 :rear-sticky :fragile :alias)))
697 (full-spec (cons spec full-properties)))
698 (add-to-list 'org-fold-core--specs full-spec append)
699 (mapc (lambda (prop-cons) (org-fold-core-set-folding-spec-property spec (car prop-cons) (cdr prop-cons) 'force)) full-properties)
700 ;; Update buffer inivisibility specs.
701 (org-fold-core--property-symbol-get-create spec))))
702
703 (defun org-fold-core-remove-folding-spec (spec &optional buffer)
704 "Remove a folding SPEC in BUFFER.
705
706 SPEC must be a symbol.
707
708 BUFFER can be a buffer to remove SPEC in, nil to remove SPEC in current
709 buffer, or `all' to remove SPEC in all open `org-mode' buffers and all
710 future org buffers."
711 (org-fold-core--check-spec spec)
712 (when (eq buffer 'all)
713 (setq-default org-fold-core--specs (delete (cdr (assq spec org-fold-core--specs)) org-fold-core--specs))
714 (mapc (lambda (buf)
715 (org-fold-core-remove-folding-spec spec buf))
716 (buffer-list)))
717 (let ((buffer (or buffer (current-buffer))))
718 (with-current-buffer buffer
719 ;; Clear the cache.
720 (setq org-fold-core--spec-list nil
721 org-fold-core--spec-symbols nil)
722 (org-fold-core-set-folding-spec-property spec :visible t)
723 (setq org-fold-core--specs (delete (cdr (assq spec org-fold-core--specs)) org-fold-core--specs)))))
724
725 (defun org-fold-core-initialize (&optional specs)
726 "Setup folding in current buffer using SPECS as value of `org-fold-core--specs'."
727 ;; Preserve the priorities.
728 (when specs (setq specs (nreverse specs)))
729 (unless specs (setq specs org-fold-core--specs))
730 (setq org-fold-core--specs nil
731 org-fold-core--spec-list nil
732 org-fold-core--spec-symbols nil)
733 (dolist (spec specs)
734 (org-fold-core-add-folding-spec (car spec) (cdr spec)))
735 (add-hook 'after-change-functions 'org-fold-core--fix-folded-region nil 'local)
736 (add-hook 'clone-indirect-buffer-hook #'org-fold-core-decouple-indirect-buffer-folds nil 'local)
737 ;; Setup killing text
738 (setq-local filter-buffer-substring-function #'org-fold-core--buffer-substring-filter)
739 (if (and (boundp 'isearch-opened-regions)
740 (eq org-fold-core-style 'text-properties))
741 ;; Use new implementation of isearch allowing to search inside text
742 ;; hidden via text properties.
743 (org-fold-core--isearch-setup 'text-properties)
744 (org-fold-core--isearch-setup 'overlays)))
745
746 ;;;; Searching and examining folded text
747
748 (defsubst org-fold-core-folded-p (&optional pos spec-or-alias)
749 "Non-nil if the character after POS is folded.
750 If POS is nil, use `point' instead.
751 If SPEC-OR-ALIAS is a folding spec or a list, only check the given
752 folding spec or the listed specs."
753 (if (and spec-or-alias (listp spec-or-alias))
754 (catch :found
755 (dolist (spec spec-or-alias)
756 (let ((val (org-fold-core-get-folding-spec spec pos)))
757 (when val (throw :found val)))))
758 (org-fold-core-get-folding-spec spec-or-alias pos)))
759
760 (defun org-fold-core-region-folded-p (beg end &optional spec-or-alias)
761 "Non-nil if the region between BEG and END is folded.
762 If SPEC-OR-ALIAS is a folding spec, only check the given folding spec."
763 (org-with-point-at beg
764 (catch :visible
765 (while (< (point) end)
766 (unless (org-fold-core-get-folding-spec spec-or-alias) (throw :visible nil))
767 (goto-char (org-fold-core-next-folding-state-change spec-or-alias nil end)))
768 t)))
769
770 (defun org-fold-core-get-folding-spec (&optional spec-or-alias pom)
771 "Get folding state at `point' or POM.
772 Return nil if there is no folding at point or POM.
773 If SPEC-OR-ALIAS is nil, return a folding spec with highest priority
774 among present at `point' or POM.
775 If SPEC-OR-ALIAS is `all', return the list of all present folding
776 specs.
777 If SPEC-OR-ALIAS is a valid folding spec or a spec alias, return the
778 corresponding folding spec (if the text is folded using that spec)."
779 (let ((spec (if (eq spec-or-alias 'all)
780 'all
781 (org-fold-core-get-folding-spec-from-alias spec-or-alias))))
782 (when (and spec (not (eq spec 'all))) (org-fold-core--check-spec spec))
783 (org-with-point-at pom
784 (cond
785 ((eq spec 'all)
786 (let ((result))
787 (dolist (spec (org-fold-core-folding-spec-list))
788 (let ((val (get-char-property (point) (org-fold-core--property-symbol-get-create spec nil t))))
789 (when val (push val result))))
790 (reverse result)))
791 ((null spec)
792 (let ((result (get-char-property (point) 'invisible)))
793 (when (org-fold-core-folding-spec-p result) result)))
794 (t (get-char-property (point) (org-fold-core--property-symbol-get-create spec nil t)))))))
795
796 (defun org-fold-core-get-folding-specs-in-region (beg end)
797 "Get all folding specs in region from BEG to END."
798 (let ((pos beg)
799 all-specs)
800 (while (< pos end)
801 (setq all-specs (append all-specs (org-fold-core-get-folding-spec nil pos)))
802 (setq pos (org-fold-core-next-folding-state-change nil pos end)))
803 (unless (listp all-specs) (setq all-specs (list all-specs)))
804 (delete-dups all-specs)))
805
806 (defun org-fold-core-get-region-at-point (&optional spec-or-alias pom)
807 "Return region folded using SPEC-OR-ALIAS at POM.
808 If SPEC is nil, return the largest possible folded region.
809 The return value is a cons of beginning and the end of the region.
810 Return nil when no fold is present at point of POM."
811 (let ((spec (org-fold-core-get-folding-spec-from-alias spec-or-alias)))
812 (org-with-point-at (or pom (point))
813 (if spec
814 (if (eq org-fold-core-style 'text-properties)
815 (org-find-text-property-region (point) (org-fold-core--property-symbol-get-create spec nil t))
816 (let ((ov (cdr (get-char-property-and-overlay (point) (org-fold-core--property-symbol-get-create spec nil t)))))
817 (when ov (cons (overlay-start ov) (overlay-end ov)))))
818 (let ((region (cons (point) (point))))
819 (dolist (spec (org-fold-core-get-folding-spec 'all))
820 (let ((local-region (org-fold-core-get-region-at-point spec)))
821 (when (< (car local-region) (car region))
822 (setcar region (car local-region)))
823 (when (> (cdr local-region) (cdr region))
824 (setcdr region (cdr local-region)))))
825 (unless (eq (car region) (cdr region)) region))))))
826
827 (defun org-fold-core-next-visibility-change (&optional pos limit ignore-hidden-p previous-p)
828 "Return next point from POS up to LIMIT where text becomes visible/invisible.
829 By default, text hidden by any means (i.e. not only by folding, but
830 also via fontification) will be considered.
831 If IGNORE-HIDDEN-P is non-nil, consider only folded text.
832 If PREVIOUS-P is non-nil, search backwards."
833 (let* ((pos (or pos (point)))
834 (invisible-p (if ignore-hidden-p
835 #'org-fold-core-folded-p
836 #'invisible-p))
837 (invisible-initially? (funcall invisible-p pos))
838 (limit (or limit (if previous-p
839 (point-min)
840 (point-max))))
841 (cmp (if previous-p #'> #'<))
842 (next-change (if previous-p
843 (if ignore-hidden-p
844 (lambda (p) (org-fold-core-previous-folding-state-change (org-fold-core-get-folding-spec nil p) p limit))
845 (lambda (p) (max limit (1- (previous-single-char-property-change p 'invisible nil limit)))))
846 (if ignore-hidden-p
847 (lambda (p) (org-fold-core-next-folding-state-change (org-fold-core-get-folding-spec nil p) p limit))
848 (lambda (p) (next-single-char-property-change p 'invisible nil limit)))))
849 (next pos))
850 (while (and (funcall cmp next limit)
851 (not (org-xor invisible-initially? (funcall invisible-p next))))
852 (setq next (funcall next-change next)))
853 next))
854
855 (defun org-fold-core-previous-visibility-change (&optional pos limit ignore-hidden-p)
856 "Call `org-fold-core-next-visibility-change' searching backwards."
857 (org-fold-core-next-visibility-change pos limit ignore-hidden-p 'previous))
858
859 (defun org-fold-core-next-folding-state-change (&optional spec-or-alias pos limit previous-p)
860 "Return point after POS where folding state changes up to LIMIT.
861 If SPEC-OR-ALIAS is nil, return next point where _any_ single folding
862 spec changes.
863 For example, (org-fold-core-next-folding-state-change nil) with point
864 somewhere in the below structure will return the nearest <...> point.
865
866 * Headline <begin outline fold>
867 :PROPERTIES:<begin drawer fold>
868 :ID: test
869 :END:<end drawer fold>
870
871 Fusce suscipit, wisi nec facilisis facilisis, est dui fermentum leo,
872 quis tempor ligula erat quis odio.
873
874 ** Another headline
875 :DRAWER:<begin drawer fold>
876 :END:<end drawer fold>
877 ** Yet another headline
878 <end of outline fold>
879
880 If SPEC-OR-ALIAS is a folding spec symbol, only consider that folding
881 spec.
882
883 If SPEC-OR-ALIAS is a list, only consider changes of folding specs
884 from the list.
885
886 Search backwards when PREVIOUS-P is non-nil."
887 (when (and spec-or-alias (symbolp spec-or-alias))
888 (setq spec-or-alias (list spec-or-alias)))
889 (when spec-or-alias
890 (setq spec-or-alias
891 (mapcar (lambda (spec-or-alias)
892 (or (org-fold-core-get-folding-spec-from-alias spec-or-alias)
893 spec-or-alias))
894 spec-or-alias))
895 (mapc #'org-fold-core--check-spec spec-or-alias))
896 (unless spec-or-alias
897 (setq spec-or-alias (org-fold-core-folding-spec-list)))
898 (setq pos (or pos (point)))
899 (apply (if previous-p
900 #'max
901 #'min)
902 (mapcar (if previous-p
903 (lambda (prop) (max (or limit (point-min)) (previous-single-char-property-change pos prop nil (or limit (point-min)))))
904 (lambda (prop) (next-single-char-property-change pos prop nil (or limit (point-max)))))
905 (mapcar (lambda (el) (org-fold-core--property-symbol-get-create el nil t))
906 spec-or-alias))))
907
908 (defun org-fold-core-previous-folding-state-change (&optional spec-or-alias pos limit)
909 "Call `org-fold-core-next-folding-state-change' searching backwards."
910 (org-fold-core-next-folding-state-change spec-or-alias pos limit 'previous))
911
912 (defun org-fold-core-search-forward (spec-or-alias &optional limit)
913 "Search next region folded via folding SPEC-OR-ALIAS up to LIMIT.
914 Move point right after the end of the region, to LIMIT, or
915 `point-max'. The `match-data' will contain the region."
916 (let ((spec (org-fold-core-get-folding-spec-from-alias spec-or-alias)))
917 (let ((prop-symbol (org-fold-core--property-symbol-get-create spec nil t)))
918 (goto-char (or (next-single-char-property-change (point) prop-symbol nil limit) limit (point-max)))
919 (when (and (< (point) (or limit (point-max)))
920 (not (org-fold-core-get-folding-spec spec)))
921 (goto-char (next-single-char-property-change (point) prop-symbol nil limit)))
922 (when (org-fold-core-get-folding-spec spec)
923 (let ((region (org-fold-core-get-region-at-point spec)))
924 (when (< (cdr region) (or limit (point-max)))
925 (goto-char (1+ (cdr region)))
926 (set-match-data (list (set-marker (make-marker) (car region) (current-buffer))
927 (set-marker (make-marker) (cdr region) (current-buffer))))))))))
928
929 (cl-defun org-fold-core-get-regions (&key specs from to with-markers relative)
930 "Find all the folded regions in current buffer.
931
932 Each element of the returned list represent folded region boundaries
933 and the folding spec: (BEG END SPEC).
934
935 Search folds intersecting with (FROM TO) buffer region if FROM and TO
936 are provided.
937
938 If FROM is non-nil and TO is nil, search the folded regions at FROM.
939
940 When both FROM and TO are nil, search folded regions in the whole buffer.
941
942 When SPECS is non-nil it should be a list of folding specs or a symbol.
943 Only return the matching fold types.
944
945 When WITH-MARKERS is non-nil, use markers to represent region
946 boundaries.
947
948 When RELATIVE is a buffer position, regions boundaries are given
949 relative to that position.
950 When RELATIVE is t, use FROM as the position.
951 WITH-MARKERS must be nil when RELATIVE is non-nil."
952 (when (and relative with-markers)
953 (error "Cannot use markers in non-absolute region boundaries"))
954 (when (eq relative t) (setq relative from))
955 (unless (listp specs) (setq specs (list specs)))
956 (let (regions region mk-region)
957 (org-with-wide-buffer
958 (when (and (not from) (not to))
959 (setq from (point-min)
960 to (point-max)))
961 (when (and from (not to)) (setq to (point-max)))
962 (when (and from (< from (point-min))) (setq from (point-min)))
963 (when (and to (> to (point-max))) (setq to (point-max)))
964 (unless from (setq from (point-min)))
965 (dolist (spec (or specs (org-fold-core-folding-spec-list)) regions)
966 (goto-char from)
967 (catch :exit
968 (while (or (not to) (< (point) to))
969 (when (org-fold-core-get-folding-spec spec)
970 (setq region (org-fold-core-get-region-at-point spec))
971 (when relative
972 (cl-decf (car region) relative)
973 (cl-decf (cdr region) relative))
974 (if (not with-markers)
975 (setq mk-region `(,(car region) ,(cdr region) ,spec))
976 (setq mk-region `(,(make-marker) ,(make-marker) ,spec))
977 (move-marker (nth 0 mk-region) (car region))
978 (move-marker (nth 1 mk-region) (cdr region)))
979 (push mk-region regions))
980 (unless to (throw :exit nil))
981 (goto-char (org-fold-core-next-folding-state-change spec nil to))))))))
982
983 ;;;; Changing visibility
984
985 ;;;;; Region visibility
986
987 ;; This is the core function performing actual folding/unfolding. The
988 ;; folding state is stored in text property (folding property)
989 ;; returned by `org-fold-core--property-symbol-get-create'. The value of the
990 ;; folding property is folding spec symbol.
991 (defun org-fold-core-region (from to flag &optional spec-or-alias)
992 "Hide or show lines from FROM to TO, according to FLAG.
993 SPEC-OR-ALIAS is the folding spec or foldable element, as a symbol.
994 If SPEC-OR-ALIAS is omitted and FLAG is nil, unfold everything in the region."
995 (let ((spec (org-fold-core-get-folding-spec-from-alias spec-or-alias)))
996 (when spec (org-fold-core--check-spec spec))
997 (with-silent-modifications
998 (org-with-wide-buffer
999 (when (eq org-fold-core-style 'overlays) (remove-overlays from to 'invisible spec))
1000 (if flag
1001 (if (not spec)
1002 (error "Calling `org-fold-core-region' with missing SPEC")
1003 (if (eq org-fold-core-style 'overlays)
1004 ;; Use `front-advance' since text right before to the beginning of
1005 ;; the overlay belongs to the visible line than to the contents.
1006 (let ((o (make-overlay from to nil
1007 (org-fold-core-get-folding-spec-property spec :front-sticky)
1008 (org-fold-core-get-folding-spec-property spec :rear-sticky))))
1009 (overlay-put o 'evaporate t)
1010 (overlay-put o (org-fold-core--property-symbol-get-create spec) spec)
1011 (overlay-put o 'invisible spec)
1012 (overlay-put o 'isearch-open-invisible #'org-fold-core--isearch-show)
1013 ;; FIXME: Disabling to work around Emacs bug#60399
1014 ;; and https://orgmode.org/list/87zgb6tk6h.fsf@localhost.
1015 ;; The proper fix will require making sure that
1016 ;; `org-fold-core-isearch-open-function' does not
1017 ;; delete the overlays used by isearch.
1018 ;; (overlay-put o 'isearch-open-invisible-temporary #'org-fold-core--isearch-show-temporary)
1019 )
1020 (put-text-property from to (org-fold-core--property-symbol-get-create spec) spec)
1021 (put-text-property from to 'isearch-open-invisible #'org-fold-core--isearch-show)
1022 (put-text-property from to 'isearch-open-invisible-temporary #'org-fold-core--isearch-show-temporary)
1023 (when (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
1024 ;; If the SPEC has highest priority, assign it directly
1025 ;; to 'invisible property as well. This is done to speed
1026 ;; up Emacs redisplay on huge (Mbs) folded regions where
1027 ;; we don't even want Emacs to spend time cycling over
1028 ;; `char-property-alias-alist'.
1029 (when (eq spec (caar org-fold-core--specs)) (put-text-property from to 'invisible spec)))))
1030 (if (not spec)
1031 (mapc (lambda (spec) (org-fold-core-region from to nil spec)) (org-fold-core-folding-spec-list))
1032 (when (and (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
1033 (eq org-fold-core-style 'text-properties))
1034 (when (eq spec (caar org-fold-core--specs))
1035 (let ((pos from))
1036 (while (< pos to)
1037 (if (eq spec (get-text-property pos 'invisible))
1038 (let ((next (org-fold-core-next-folding-state-change spec pos to)))
1039 (remove-text-properties pos next '(invisible t))
1040 (setq pos next))
1041 (setq pos (next-single-char-property-change pos 'invisible nil to)))))))
1042 (when (eq org-fold-core-style 'text-properties)
1043 (remove-text-properties from to (list (org-fold-core--property-symbol-get-create spec) nil)))))))))
1044
1045 (cl-defmacro org-fold-core-regions (regions &key override clean-markers relative)
1046 "Fold every region in REGIONS list in current buffer.
1047
1048 Each region in the list is a list (BEG END SPEC-OR-ALIAS) describing
1049 region and folding spec to be applied.
1050
1051 When optional argument OVERRIDE is non-nil, clear folding state in the
1052 buffer first.
1053
1054 When optional argument CLEAN-MARKERS is non-nil, clear markers used to
1055 mark region boundaries in REGIONS.
1056
1057 When optional argument RELATIVE is non-nil, it must be a buffer
1058 position. REGION boundaries are then treated as relative distances
1059 from that position."
1060 `(org-with-wide-buffer
1061 (when ,override (org-fold-core-region (point-min) (point-max) nil))
1062 (pcase-dolist (`(,beg ,end ,spec) (delq nil ,regions))
1063 (let ((rel ,relative))
1064 (if rel
1065 (org-fold-core-region (+ rel beg) (+ rel end) t spec)
1066 (org-fold-core-region beg end t spec)))
1067 (when ,clean-markers
1068 (when (markerp beg) (set-marker beg nil))
1069 (when (markerp end) (set-marker end nil))))))
1070
1071 (defmacro org-fold-core-save-visibility (use-markers &rest body)
1072 "Save and restore folding state around BODY.
1073 If USE-MARKERS is non-nil, use markers for the positions. This
1074 means that the buffer may change while running BODY, but it also
1075 means that the buffer should stay alive during the operation,
1076 because otherwise all these markers will point to nowhere."
1077 (declare (debug (form body)) (indent 1))
1078 (org-with-gensyms (regions)
1079 `(let* ((,regions (org-fold-core-get-regions :with-markers ,use-markers)))
1080 (unwind-protect (progn ,@body)
1081 (org-fold-core-regions ,regions :override t :clean-markers t)))))
1082
1083 ;;; Make isearch search in some text hidden via text propertoes
1084
1085 (defvar org-fold-core--isearch-overlays nil
1086 "List of overlays temporarily created during isearch.
1087 This is used to allow searching in regions hidden via text properties.
1088 As for [2020-05-09 Sat], Isearch only has special handling of hidden overlays.
1089 Any text hidden via text properties is not revealed even if `search-invisible'
1090 is set to `t'.")
1091
1092 (defvar-local org-fold-core--isearch-local-regions (make-hash-table :test 'equal)
1093 "Hash table storing temporarily shown folds from isearch matches.")
1094
1095 (defun org-fold-core--isearch-setup (type)
1096 "Initialize isearch in org buffer.
1097 TYPE can be either `text-properties' or `overlays'."
1098 (pcase type
1099 (`text-properties
1100 (setq-local search-invisible 'open-all)
1101 (add-hook 'isearch-mode-end-hook #'org-fold-core--clear-isearch-state nil 'local)
1102 (add-hook 'isearch-mode-hook #'org-fold-core--clear-isearch-state nil 'local)
1103 (setq-local isearch-filter-predicate #'org-fold-core--isearch-filter-predicate-text-properties))
1104 (`overlays
1105 (when (eq org-fold-core-style 'text-properties)
1106 (setq-local isearch-filter-predicate #'org-fold-core--isearch-filter-predicate-overlays)
1107 (add-hook 'isearch-mode-end-hook #'org-fold-core--clear-isearch-overlays nil 'local)))
1108 (_ (error "%s: Unknown type of setup for `org-fold-core--isearch-setup'" type))))
1109
1110 (defun org-fold-core--isearch-reveal (pos)
1111 "Default function used to reveal hidden text at POS for isearch."
1112 (let ((region (org-fold-core-get-region-at-point pos)))
1113 (org-fold-core-region (car region) (cdr region) nil)))
1114
1115 (defun org-fold-core--isearch-filter-predicate-text-properties (beg end)
1116 "Make sure that folded text is searchable when user want so.
1117 This function is intended to be used as `isearch-filter-predicate'."
1118 (and
1119 ;; Check folding specs that cannot be searched
1120 (not (memq nil (mapcar (lambda (spec) (not (org-fold-core-get-folding-spec-property spec :isearch-ignore)))
1121 (org-fold-core-get-folding-specs-in-region beg end))))
1122 ;; Check 'invisible properties that are not folding specs.
1123 (or (eq search-invisible t) ; User wants to search anyway, allow it.
1124 (let ((pos beg)
1125 unknown-invisible-property)
1126 (while (and (< pos end)
1127 (not unknown-invisible-property))
1128 (when (and (get-text-property pos 'invisible)
1129 (not (org-fold-core-folding-spec-p (get-text-property pos 'invisible))))
1130 (setq unknown-invisible-property t))
1131 (setq pos (next-single-char-property-change pos 'invisible)))
1132 (not unknown-invisible-property)))
1133 (or (and (eq search-invisible t)
1134 ;; FIXME: this opens regions permanenly for now.
1135 ;; I also tried to force search-invisible 'open-all around
1136 ;; `isearch-range-invisible', but that somehow causes
1137 ;; infinite loop in `isearch-lazy-highlight'.
1138 (prog1 t
1139 ;; We still need to reveal the folded location
1140 (org-fold-core--isearch-show-temporary (cons beg end) nil)))
1141 (not (isearch-range-invisible beg end)))))
1142
1143 (defun org-fold-core--clear-isearch-state ()
1144 "Clear `org-fold-core--isearch-local-regions'."
1145 (clrhash org-fold-core--isearch-local-regions))
1146
1147 (defun org-fold-core--isearch-show (_)
1148 "Reveal text at point found by isearch."
1149 (funcall org-fold-core-isearch-open-function (point)))
1150
1151 (defun org-fold-core--isearch-show-temporary (region hide-p)
1152 "Temporarily reveal text in REGION.
1153 Hide text instead if HIDE-P is non-nil.
1154 REGION can also be an overlay in current buffer."
1155 (when (overlayp region)
1156 (setq region (cons (overlay-start region)
1157 (overlay-end region))))
1158 (if (not hide-p)
1159 (let ((pos (car region)))
1160 (while (< pos (cdr region))
1161 (let ((spec-no-open
1162 (catch :found
1163 (dolist (spec (org-fold-core-get-folding-spec 'all pos))
1164 (unless (org-fold-core-get-folding-spec-property spec :isearch-open)
1165 (throw :found spec))))))
1166 (if spec-no-open
1167 ;; Skip regions folded with folding specs that cannot be opened.
1168 (setq pos (org-fold-core-next-folding-state-change spec-no-open pos (cdr region)))
1169 (dolist (spec (org-fold-core-get-folding-spec 'all pos))
1170 (push (cons spec (org-fold-core-get-region-at-point spec pos)) (gethash region org-fold-core--isearch-local-regions)))
1171 (org-fold-core--isearch-show region)
1172 (setq pos (org-fold-core-next-folding-state-change nil pos (cdr region)))))))
1173 (mapc (lambda (val) (org-fold-core-region (cadr val) (cddr val) t (car val))) (gethash region org-fold-core--isearch-local-regions))
1174 (remhash region org-fold-core--isearch-local-regions)))
1175
1176 (defvar-local org-fold-core--isearch-special-specs nil
1177 "List of specs that can break visibility state when converted to overlays.
1178 This is a hack, but I do not see a better way around until isearch
1179 gets support of text properties.")
1180 (defun org-fold-core--create-isearch-overlays (beg end)
1181 "Replace text property invisibility spec by overlays between BEG and END.
1182 All the searchable folded regions will be changed to use overlays
1183 instead of text properties. The created overlays will be stored in
1184 `org-fold-core--isearch-overlays'."
1185 (let ((pos beg))
1186 (while (< pos end)
1187 ;; We need loop below to make sure that we clean all invisible
1188 ;; properties, which may be nested.
1189 (dolist (spec (org-fold-core-get-folding-spec 'all pos))
1190 (unless (org-fold-core-get-folding-spec-property spec :isearch-ignore)
1191 (let* ((region (org-fold-core-get-region-at-point spec pos)))
1192 (when (memq spec org-fold-core--isearch-special-specs)
1193 (setq pos (min pos (car region)))
1194 (setq end (max end (cdr region))))
1195 ;; Changing text properties is considered buffer modification.
1196 ;; We do not want it here.
1197 (with-silent-modifications
1198 (org-fold-core-region (car region) (cdr region) nil spec)
1199 ;; The overlay is modeled after `outline-flag-region'
1200 ;; [2020-05-09 Sat] overlay for 'outline blocks.
1201 (let ((o (make-overlay (car region) (cdr region) nil 'front-advance)))
1202 (overlay-put o 'evaporate t)
1203 (overlay-put o 'invisible spec)
1204 (overlay-put o 'org-invisible spec)
1205 ;; Make sure that overlays are applied in the same order
1206 ;; with the folding specs.
1207 ;; Note: `memq` returns cdr with car equal to the first
1208 ;; found matching element.
1209 (overlay-put o 'priority (length (memq spec (org-fold-core-folding-spec-list))))
1210 ;; `delete-overlay' here means that spec information will be lost
1211 ;; for the region. The region will remain visible.
1212 (if (org-fold-core-get-folding-spec-property spec :isearch-open)
1213 (overlay-put o 'isearch-open-invisible #'delete-overlay)
1214 (overlay-put o 'isearch-open-invisible #'ignore)
1215 (overlay-put o 'isearch-open-invisible-temporary #'ignore))
1216 (push o org-fold-core--isearch-overlays))))))
1217 (setq pos (org-fold-core-next-folding-state-change nil pos end)))))
1218
1219 (defun org-fold-core--isearch-filter-predicate-overlays (beg end)
1220 "Return non-nil if text between BEG and END is deemed visible by isearch.
1221 This function is intended to be used as `isearch-filter-predicate'."
1222 (org-fold-core--create-isearch-overlays beg end) ;; trick isearch by creating overlays in place of invisible text
1223 (isearch-filter-visible beg end))
1224
1225 (defun org-fold-core--clear-isearch-overlay (ov)
1226 "Convert OV region back into using text properties."
1227 (let ((spec (if isearch-mode-end-hook-quit
1228 ;; Restore all folds.
1229 (overlay-get ov 'org-invisible)
1230 ;; Leave opened folds open.
1231 (overlay-get ov 'invisible))))
1232 ;; Ignore deleted overlays.
1233 (when (and spec
1234 (overlay-buffer ov))
1235 ;; Changing text properties is considered buffer modification.
1236 ;; We do not want it here.
1237 (with-silent-modifications
1238 (when (<= (overlay-end ov) (point-max))
1239 (org-fold-core-region (overlay-start ov) (overlay-end ov) t spec)))))
1240 (when (member ov isearch-opened-overlays)
1241 (setq isearch-opened-overlays (delete ov isearch-opened-overlays)))
1242 (delete-overlay ov))
1243
1244 (defun org-fold-core--clear-isearch-overlays ()
1245 "Convert overlays from `org-fold-core--isearch-overlays' back to text properties."
1246 (when org-fold-core--isearch-overlays
1247 (mapc #'org-fold-core--clear-isearch-overlay org-fold-core--isearch-overlays)
1248 (setq org-fold-core--isearch-overlays nil)))
1249
1250 ;;; Handling changes in folded elements
1251
1252 (defvar org-fold-core--ignore-modifications nil
1253 "Non-nil: skip processing modifications in `org-fold-core--fix-folded-region'.")
1254 (defvar org-fold-core--ignore-fragility-checks nil
1255 "Non-nil: skip fragility checks in `org-fold-core--fix-folded-region'.")
1256
1257 (defmacro org-fold-core-ignore-modifications (&rest body)
1258 "Run BODY ignoring buffer modifications in `org-fold-core--fix-folded-region'."
1259 (declare (debug (form body)) (indent 0))
1260 `(let ((org-fold-core--ignore-modifications t))
1261 (unwind-protect (progn ,@body)
1262 (setq org-fold-core--last-buffer-chars-modified-tick (buffer-chars-modified-tick)))))
1263
1264 (defmacro org-fold-core-ignore-fragility-checks (&rest body)
1265 "Run BODY skipping :fragility checks in `org-fold-core--fix-folded-region'."
1266 (declare (debug (form body)) (indent 0))
1267 `(let ((org-fold-core--ignore-fragility-checks t))
1268 (progn ,@body)))
1269
1270 (defvar-local org-fold-core--last-buffer-chars-modified-tick nil
1271 "Variable storing the last return value of `buffer-chars-modified-tick'.")
1272
1273 (defun org-fold-core--fix-folded-region (from to _)
1274 "Process modifications in folded elements within FROM . TO region.
1275 This function intended to be used as one of `after-change-functions'.
1276
1277 This function does nothing if text the only modification was changing
1278 text properties (for the sake of reducing overheads).
1279
1280 If a text was inserted into invisible region, hide the inserted text.
1281 If a text was inserted in front/back of the region, hide it according
1282 to :front-sticky/:rear-sticky folding spec property.
1283
1284 If the folded region is folded with a spec with non-nil :fragile
1285 property, unfold the region if the :fragile function returns non-nil."
1286 ;; If no insertions or deletions in buffer, skip all the checks.
1287 (unless (or org-fold-core--ignore-modifications
1288 (eq org-fold-core--last-buffer-chars-modified-tick (buffer-chars-modified-tick))
1289 (memql 'ignore-modification-checks org-fold-core--optimise-for-huge-buffers))
1290 ;; Store the new buffer modification state.
1291 (setq org-fold-core--last-buffer-chars-modified-tick (buffer-chars-modified-tick))
1292 (save-match-data
1293 ;; Handle changes in all the indirect buffers and in the base
1294 ;; buffer. Work around Emacs bug#46982.
1295 ;; Re-hide text inserted in the middle/front/back of a folded
1296 ;; region.
1297 (unless (equal from to) ; Ignore deletions.
1298 (when (eq org-fold-core-style 'text-properties)
1299 (org-fold-core-cycle-over-indirect-buffers
1300 (dolist (spec (org-fold-core-folding-spec-list))
1301 ;; Reveal fully invisible text inserted in the middle
1302 ;; of visible portion of the buffer. This is needed,
1303 ;; for example, when there was a deletion in a folded
1304 ;; heading, the heading was unfolded, end `undo' was
1305 ;; called. The `undo' would insert the folded text.
1306 (when (and (or (eq from (point-min))
1307 (not (org-fold-core-folded-p (1- from) spec)))
1308 (or (eq to (point-max))
1309 (not (org-fold-core-folded-p to spec)))
1310 (org-fold-core-region-folded-p from to spec))
1311 (org-fold-core-region from to nil spec))
1312 ;; Look around and fold the new text if the nearby folds are
1313 ;; sticky.
1314 (unless (org-fold-core-region-folded-p from to spec)
1315 (let ((spec-to (org-fold-core-get-folding-spec spec (min to (1- (point-max)))))
1316 (spec-from (org-fold-core-get-folding-spec spec (max (point-min) (1- from)))))
1317 ;; Reveal folds around undone deletion.
1318 (when undo-in-progress
1319 (let ((lregion (org-fold-core-get-region-at-point spec (max (point-min) (1- from))))
1320 (rregion (org-fold-core-get-region-at-point spec (min to (1- (point-max))))))
1321 (if (and lregion rregion)
1322 (org-fold-core-region (car lregion) (cdr rregion) nil spec)
1323 (when lregion
1324 (org-fold-core-region (car lregion) (cdr lregion) nil spec))
1325 (when rregion
1326 (org-fold-core-region (car rregion) (cdr rregion) nil spec)))))
1327 ;; Hide text inserted in the middle of a fold.
1328 (when (and (or spec-from (eq from (point-min)))
1329 (or spec-to (eq to (point-max)))
1330 (or spec-from spec-to)
1331 (eq spec-to spec-from)
1332 (or (org-fold-core-get-folding-spec-property spec :front-sticky)
1333 (org-fold-core-get-folding-spec-property spec :rear-sticky)))
1334 (unless (and (eq from (point-min)) (eq to (point-max))) ; Buffer content replaced.
1335 (org-fold-core-region from to t (or spec-from spec-to))))
1336 ;; Hide text inserted at the end of a fold.
1337 (when (and spec-from (org-fold-core-get-folding-spec-property spec-from :rear-sticky))
1338 (org-fold-core-region from to t spec-from))
1339 ;; Hide text inserted in front of a fold.
1340 (when (and spec-to
1341 (not (eq to (point-max))) ; Text inserted at the end of buffer is not prepended anywhere.
1342 (org-fold-core-get-folding-spec-property spec-to :front-sticky))
1343 (org-fold-core-region from to t spec-to))))))))
1344 ;; Process all the folded text between `from' and `to'. Do it
1345 ;; only in current buffer to avoid verifying semantic structure
1346 ;; multiple times in indirect buffers that have exactly same
1347 ;; text anyway.
1348 (unless (or org-fold-core--ignore-fragility-checks
1349 (memql 'ignore-fragility-checks org-fold-core--optimise-for-huge-buffers))
1350 (dolist (func org-fold-core-extend-changed-region-functions)
1351 (let ((new-region (funcall func from to)))
1352 (setq from (car new-region))
1353 (setq to (cdr new-region))))
1354 (org-fold-core-cycle-over-indirect-buffers
1355 (dolist (spec (org-fold-core-folding-spec-list))
1356 ;; No action is needed when :fragile is nil for the spec.
1357 (when (org-fold-core-get-folding-spec-property spec :fragile)
1358 (org-with-wide-buffer
1359 ;; Expand the considered region to include partially present fold.
1360 ;; Note: It is important to do this inside loop over all
1361 ;; specs. Otherwise, the region may be expanded to huge
1362 ;; outline fold, potentially involving majority of the
1363 ;; buffer. That would cause the below code to loop over
1364 ;; almost all the folds in buffer, which would be too slow.
1365 (let ((local-from from)
1366 (local-to to)
1367 (region-from (org-fold-core-get-region-at-point spec (max (point-min) (1- from))))
1368 (region-to (org-fold-core-get-region-at-point spec (min to (1- (point-max))))))
1369 (when region-from (setq local-from (car region-from)))
1370 (when region-to (setq local-to (cdr region-to)))
1371 (let ((pos local-from))
1372 ;; Move to the first hidden region.
1373 (unless (org-fold-core-get-folding-spec spec pos)
1374 (setq pos (org-fold-core-next-folding-state-change spec pos local-to)))
1375 ;; Cycle over all the folds.
1376 (while (< pos local-to)
1377 (save-match-data ; we should not clobber match-data in after-change-functions
1378 (let ((fold-begin (and (org-fold-core-get-folding-spec spec pos)
1379 pos))
1380 (fold-end (org-fold-core-next-folding-state-change spec pos local-to)))
1381 (when (and fold-begin fold-end)
1382 (when (save-excursion
1383 (funcall (org-fold-core-get-folding-spec-property spec :fragile)
1384 (cons fold-begin fold-end)
1385 spec))
1386 ;; Reveal completely, not just from the SPEC.
1387 (org-fold-core-region fold-begin fold-end nil)))))
1388 ;; Move to next fold.
1389 (setq pos (org-fold-core-next-folding-state-change spec pos local-to)))))))))))))
1390
1391 ;;; Handling killing/yanking of folded text
1392
1393 ;; By default, all the text properties of the killed text are
1394 ;; preserved, including the folding text properties. This can be
1395 ;; awkward when we copy a text from an indirect buffer to another
1396 ;; indirect buffer (or the base buffer). The copied text might be
1397 ;; visible in the source buffer, but might disappear if we yank it in
1398 ;; another buffer. This happens in the following situation:
1399 ;; ---- base buffer ----
1400 ;; * Headline<begin fold>
1401 ;; Some text hidden in the base buffer, but revealed in the indirect
1402 ;; buffer.<end fold>
1403 ;; * Another headline
1404 ;;
1405 ;; ---- end of base buffer ----
1406 ;; ---- indirect buffer ----
1407 ;; * Headline
1408 ;; Some text hidden in the base buffer, but revealed in the indirect
1409 ;; buffer.
1410 ;; * Another headline
1411 ;;
1412 ;; ---- end of indirect buffer ----
1413 ;; If we copy the text under "Headline" from the indirect buffer and
1414 ;; insert it under "Another headline" in the base buffer, the inserted
1415 ;; text will be hidden since it's folding text properties are copied.
1416 ;; Basically, the copied text would have two sets of folding text
1417 ;; properties: (1) Properties for base buffer telling that the text is
1418 ;; hidden; (2) Properties for the indirect buffer telling that the
1419 ;; text is visible. The first set of the text properties in inactive
1420 ;; in the indirect buffer, but will become active once we yank the
1421 ;; text back into the base buffer.
1422 ;;
1423 ;; To avoid the above situation, we simply clear all the properties,
1424 ;; unrealated to current buffer when a text is copied.
1425 ;; FIXME: Ideally, we may want to carry the folding state of copied
1426 ;; text between buffer (probably via user customization).
1427 (defun org-fold-core--buffer-substring-filter (beg end &optional delete)
1428 "Clear folding state in killed text.
1429 This function is intended to be used as `filter-buffer-substring-function'.
1430 The arguments and return value are as specified for `filter-buffer-substring'."
1431 (let ((return-string (buffer-substring--filter beg end delete))
1432 ;; The list will be used as an argument to `remove-text-properties'.
1433 props-list)
1434 ;; There is no easy way to examine all the text properties of a
1435 ;; string, so we utilize the fact that printed string
1436 ;; representation lists all its properties.
1437 ;; Loop over the elements of string representation.
1438 (unless (or (string= "" return-string)
1439 (<= end beg)
1440 (eq org-fold-core-style 'overlays))
1441 ;; Collect all the text properties the string is completely
1442 ;; hidden with.
1443 (dolist (spec (org-fold-core-folding-spec-list))
1444 (when (and (org-fold-core-region-folded-p beg end spec)
1445 (org-region-invisible-p beg end))
1446 (push (org-fold-core--property-symbol-get-create spec nil t) props-list)))
1447 (dolist (plist
1448 (if (fboundp 'object-intervals)
1449 (object-intervals return-string)
1450 ;; Backward compatibility with Emacs <28.
1451 ;; FIXME: Is there any better way to do it?
1452 ;; Yes, it is a hack.
1453 ;; The below gives us string representation as a list.
1454 ;; Note that we need to remove unreadable values, like markers (#<...>).
1455 (seq-partition
1456 (cdr (let ((data (read (replace-regexp-in-string
1457 "^#(" "("
1458 (replace-regexp-in-string
1459 " #(" " ("
1460 (replace-regexp-in-string
1461 "#<[^>]+>" "dummy"
1462 ;; Get text representation of the string object.
1463 ;; Make sure to print everything (see `prin1' docstring).
1464 ;; `prin1' is used to print "%S" format.
1465 (let (print-level print-length)
1466 (format "%S" return-string))))))))
1467 (if (listp data) data (list data))))
1468 3)))
1469 (let* ((start (car plist))
1470 (fin (cadr plist))
1471 (plist (car (cddr plist))))
1472 ;; Only lists contain text properties.
1473 (when (listp plist)
1474 ;; Collect all the relevant text properties.
1475 (while plist
1476 (let* ((prop (car plist))
1477 (prop-name (symbol-name prop)))
1478 ;; Reveal hard-hidden text. See
1479 ;; `org-fold-core--optimise-for-huge-buffers'.
1480 (when (and (eq prop 'invisible)
1481 (member (cadr plist) (org-fold-core-folding-spec-list)))
1482 (remove-text-properties start fin '(invisible t) return-string))
1483 ;; We do not care about values now.
1484 (setq plist (cddr plist))
1485 (when (string-match-p org-fold-core--spec-property-prefix prop-name)
1486 ;; Leave folding specs from current buffer. See
1487 ;; comments in `org-fold-core--property-symbol-get-create' to
1488 ;; understand why it works.
1489 (unless (member prop (cdr (assq 'invisible char-property-alias-alist)))
1490 (push prop props-list))))))))
1491 (remove-text-properties 0 (length return-string) props-list return-string))
1492 return-string))
1493
1494 (defun org-fold-core-update-optimisation (beg end)
1495 "Update huge buffer optimization between BEG and END.
1496 See `org-fold-core--optimise-for-huge-buffers'."
1497 (when (and (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
1498 (eq org-fold-core-style 'text-properties))
1499 (let ((pos beg))
1500 (while (< pos end)
1501 (when (and (org-fold-core-folded-p pos (caar org-fold-core--specs))
1502 (not (eq (caar org-fold-core--specs) (get-text-property pos 'invisible))))
1503 (put-text-property pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end)
1504 'invisible (caar org-fold-core--specs)))
1505 (setq pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end))))))
1506
1507 (defun org-fold-core-remove-optimisation (beg end)
1508 "Remove huge buffer optimization between BEG and END.
1509 See `org-fold-core--optimise-for-huge-buffers'."
1510 (when (and (memql 'grab-invisible org-fold-core--optimise-for-huge-buffers)
1511 (eq org-fold-core-style 'text-properties))
1512 (let ((pos beg))
1513 (while (< pos end)
1514 (if (and (org-fold-core-folded-p pos (caar org-fold-core--specs))
1515 (eq (caar org-fold-core--specs) (get-text-property pos 'invisible)))
1516 (remove-text-properties pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end)
1517 '(invisible t)))
1518 (setq pos (org-fold-core-next-folding-state-change (caar org-fold-core--specs) pos end))))))
1519
1520 (provide 'org-fold-core)
1521
1522 ;;; org-fold-core.el ends here
0 ;;; org-fold.el --- Folding of Org entries -*- lexical-binding: t; -*-
1 ;;
2 ;; Copyright (C) 2020-2023 Free Software Foundation, Inc.
3 ;;
4 ;; Author: Ihor Radchenko <yantar92 at gmail dot com>
5 ;; Keywords: folding, invisible text
6 ;; URL: https://orgmode.org
7 ;;
8 ;; This file is part of GNU Emacs.
9 ;;
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
22 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
23 ;;
24 ;;; Commentary:
25
26 ;; This file contains code handling temporary invisibility (folding
27 ;; and unfolding) of text in org buffers.
28
29 ;; The folding is implemented using generic org-fold-core library. This file
30 ;; contains org-specific implementation of the folding. Also, various
31 ;; useful functions from org-fold-core are aliased under shorted `org-fold'
32 ;; prefix.
33
34 ;; The following features are implemented:
35 ;; - Folding/unfolding various Org mode elements and regions of Org buffers:
36 ;; + Region before first heading;
37 ;; + Org headings, their text, children (subtree), siblings, parents, etc;
38 ;; + Org blocks and drawers
39 ;; - Revealing Org structure around invisible point location
40 ;; - Revealing folded Org elements broken by user edits
41
42 ;;; Code:
43
44 (require 'org-macs)
45 (org-assert-version)
46
47 (require 'org-macs)
48 (require 'org-fold-core)
49
50 (defvar org-inlinetask-min-level)
51 (defvar org-link--link-folding-spec)
52 (defvar org-link--description-folding-spec)
53 (defvar org-odd-levels-only)
54 (defvar org-drawer-regexp)
55 (defvar org-property-end-re)
56 (defvar org-link-descriptive)
57 (defvar org-outline-regexp-bol)
58 (defvar org-archive-tag)
59 (defvar org-custom-properties-overlays)
60 (defvar org-element-headline-re)
61
62 (declare-function isearch-filter-visible "isearch" (beg end))
63 (declare-function org-element-type "org-element" (element))
64 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
65 (declare-function org-element-property "org-element" (property element))
66 (declare-function org-element--current-element "org-element" (limit &optional granularity mode structure))
67 (declare-function org-element--cache-active-p "org-element" ())
68 (declare-function org-toggle-custom-properties-visibility "org" ())
69 (declare-function org-item-re "org-list" ())
70 (declare-function org-up-heading-safe "org" ())
71 (declare-function org-get-tags "org" (&optional pos local fontify))
72 (declare-function org-get-valid-level "org" (level &optional change))
73 (declare-function org-before-first-heading-p "org" ())
74 (declare-function org-goto-sibling "org" (&optional previous))
75 (declare-function org-block-map "org" (function &optional start end))
76 (declare-function org-map-region "org" (fun beg end))
77 (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
78 (declare-function org-back-to-heading-or-point-min "org" (&optional invisible-ok))
79 (declare-function org-back-to-heading "org" (&optional invisible-ok))
80 (declare-function org-at-heading-p "org" (&optional invisible-not-ok))
81 (declare-function org-cycle-hide-drawers "org-cycle" (state))
82
83 (declare-function outline-show-branches "outline" ())
84 (declare-function outline-hide-sublevels "outline" (levels))
85 (declare-function outline-get-next-sibling "outline" ())
86 (declare-function outline-invisible-p "outline" (&optional pos))
87 (declare-function outline-next-heading "outline" ())
88
89 ;;; Customization
90
91 (defgroup org-fold-reveal-location nil
92 "Options about how to make context of a location visible."
93 :tag "Org Reveal Location"
94 :group 'org-structure)
95
96 (defcustom org-fold-show-context-detail '((agenda . local)
97 (bookmark-jump . lineage)
98 (isearch . lineage)
99 (default . ancestors))
100 "Alist between context and visibility span when revealing a location.
101
102 \\<org-mode-map>Some actions may move point into invisible
103 locations. As a consequence, Org always exposes a neighborhood
104 around point. How much is shown depends on the initial action,
105 or context. Valid contexts are
106
107 agenda when exposing an entry from the agenda
108 org-goto when using the command `org-goto' (`\\[org-goto]')
109 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
110 tags-tree when constructing a sparse tree based on tags matches
111 link-search when exposing search matches associated with a link
112 mark-goto when exposing the jump goal of a mark
113 bookmark-jump when exposing a bookmark location
114 isearch when exiting from an incremental search
115 default default for all contexts not set explicitly
116
117 Allowed visibility spans are
118
119 minimal show current headline; if point is not on headline,
120 also show entry
121
122 local show current headline, entry and next headline
123
124 ancestors show current headline and its direct ancestors; if
125 point is not on headline, also show entry
126
127 ancestors-full show current subtree and its direct ancestors
128
129 lineage show current headline, its direct ancestors and all
130 their children; if point is not on headline, also show
131 entry and first child
132
133 tree show current headline, its direct ancestors and all
134 their children; if point is not on headline, also show
135 entry and all children
136
137 canonical show current headline, its direct ancestors along with
138 their entries and children; if point is not located on
139 the headline, also show current entry and all children
140
141 As special cases, a nil or t value means show all contexts in
142 `minimal' or `canonical' view, respectively.
143
144 Some views can make displayed information very compact, but also
145 make it harder to edit the location of the match. In such
146 a case, use the command `org-fold-reveal' (`\\[org-fold-reveal]') to show
147 more context."
148 :group 'org-fold-reveal-location
149 :version "26.1"
150 :package-version '(Org . "9.0")
151 :type '(choice
152 (const :tag "Canonical" t)
153 (const :tag "Minimal" nil)
154 (repeat :greedy t :tag "Individual contexts"
155 (cons
156 (choice :tag "Context"
157 (const agenda)
158 (const org-goto)
159 (const occur-tree)
160 (const tags-tree)
161 (const link-search)
162 (const mark-goto)
163 (const bookmark-jump)
164 (const isearch)
165 (const default))
166 (choice :tag "Detail level"
167 (const minimal)
168 (const local)
169 (const ancestors)
170 (const ancestors-full)
171 (const lineage)
172 (const tree)
173 (const canonical))))))
174
175 (defvar org-fold-reveal-start-hook nil
176 "Hook run before revealing a location.")
177
178 (defcustom org-fold-catch-invisible-edits 'smart
179 "Check if in invisible region before inserting or deleting a character.
180 Valid values are:
181
182 nil Do not check, so just do invisible edits.
183 error Throw an error and do nothing.
184 show Make point visible, and do the requested edit.
185 show-and-error Make point visible, then throw an error and abort the edit.
186 smart Make point visible, and do insertion/deletion if it is
187 adjacent to visible text and the change feels predictable.
188 Never delete a previously invisible character or add in the
189 middle or right after an invisible region. Basically, this
190 allows insertion and backward-delete right before ellipses.
191 FIXME: maybe in this case we should not even show?"
192 :group 'org-edit-structure
193 :version "24.1"
194 :type '(choice
195 (const :tag "Do not check" nil)
196 (const :tag "Throw error when trying to edit" error)
197 (const :tag "Unhide, but do not do the edit" show-and-error)
198 (const :tag "Show invisible part and do the edit" show)
199 (const :tag "Be smart and do the right thing" smart)))
200
201 ;;; Core functionality
202
203 ;;; API
204
205 ;;;; Modifying folding specs
206
207 (defalias 'org-fold-folding-spec-p #'org-fold-core-folding-spec-p)
208 (defalias 'org-fold-add-folding-spec #'org-fold-core-add-folding-spec)
209 (defalias 'org-fold-remove-folding-spec #'org-fold-core-remove-folding-spec)
210
211 (defun org-fold-initialize (ellipsis)
212 "Setup folding in current Org buffer."
213 (setq-local org-fold-core-isearch-open-function #'org-fold--isearch-reveal)
214 (setq-local org-fold-core-extend-changed-region-functions (list #'org-fold--extend-changed-region))
215 ;; FIXME: Converting org-link + org-description to overlays when
216 ;; search matches hidden "[[" part of the link, reverses priority of
217 ;; link and description and hides the whole link. Working around
218 ;; this until there will be no need to convert text properties to
219 ;; overlays for isearch.
220 (setq-local org-fold-core--isearch-special-specs '(org-link))
221 (org-fold-core-initialize
222 `((,(if (eq org-fold-core-style 'text-properties) 'org-fold-outline 'outline)
223 (:ellipsis . ,ellipsis)
224 (:fragile . ,#'org-fold--reveal-outline-maybe)
225 (:isearch-open . t)
226 ;; This is needed to make sure that inserting a
227 ;; new planning line in folded heading is not
228 ;; revealed. Also, the below combination of :front-sticky and
229 ;; :rear-sticky conforms to the overlay properties in outline.el
230 ;; and the older Org versions as in `outline-flag-region'.
231 (:front-sticky . t)
232 (:rear-sticky . nil)
233 (:alias . (headline heading outline inlinetask plain-list)))
234 (,(if (eq org-fold-core-style 'text-properties) 'org-fold-block 'org-hide-block)
235 (:ellipsis . ,ellipsis)
236 (:fragile . ,#'org-fold--reveal-drawer-or-block-maybe)
237 (:isearch-open . t)
238 (:front-sticky . t)
239 (:alias . ( block center-block comment-block
240 dynamic-block example-block export-block
241 quote-block special-block src-block
242 verse-block)))
243 (,(if (eq org-fold-core-style 'text-properties) 'org-fold-drawer 'org-hide-drawer)
244 (:ellipsis . ,ellipsis)
245 (:fragile . ,#'org-fold--reveal-drawer-or-block-maybe)
246 (:isearch-open . t)
247 (:front-sticky . t)
248 (:alias . (drawer property-drawer)))
249 ,org-link--description-folding-spec
250 ,org-link--link-folding-spec)))
251
252 ;;;; Searching and examining folded text
253
254 (defalias 'org-fold-folded-p #'org-fold-core-folded-p)
255 (defalias 'org-fold-get-folding-spec #'org-fold-core-get-folding-spec)
256 (defalias 'org-fold-get-folding-specs-in-region #'org-fold-core-get-folding-specs-in-region)
257 (defalias 'org-fold-get-region-at-point #'org-fold-core-get-region-at-point)
258 (defalias 'org-fold-get-regions #'org-fold-core-get-regions)
259 (defalias 'org-fold-next-visibility-change #'org-fold-core-next-visibility-change)
260 (defalias 'org-fold-previous-visibility-change #'org-fold-core-previous-visibility-change)
261 (defalias 'org-fold-next-folding-state-change #'org-fold-core-next-folding-state-change)
262 (defalias 'org-fold-previous-folding-state-change #'org-fold-core-previous-folding-state-change)
263 (defalias 'org-fold-search-forward #'org-fold-core-search-forward)
264
265 ;;;;; Macros
266
267 (defalias 'org-fold-save-outline-visibility #'org-fold-core-save-visibility)
268
269 ;;;; Changing visibility (regions, blocks, drawers, headlines)
270
271 ;;;;; Region visibility
272
273 (defalias 'org-fold-region #'org-fold-core-region)
274 (defalias 'org-fold-regions #'org-fold-core-regions)
275
276 (defun org-fold-show-all (&optional types)
277 "Show all contents in the visible part of the buffer.
278 By default, the function expands headings, blocks and drawers.
279 When optional argument TYPES is a list of symbols among `blocks',
280 `drawers' and `headings', to only expand one specific type."
281 (interactive)
282 (dolist (type (or types '(blocks drawers headings)))
283 (org-fold-region (point-min) (point-max) nil
284 (pcase type
285 (`blocks 'block)
286 (`drawers 'drawer)
287 (`headings 'headline)
288 (_ (error "Invalid type: %S" type))))))
289
290 (defun org-fold-flag-above-first-heading (&optional arg)
291 "Hide from bob up to the first heading.
292 Move point to the beginning of first heading or end of buffer."
293 (goto-char (point-min))
294 (unless (org-at-heading-p)
295 (outline-next-heading))
296 (unless (bobp)
297 (org-fold-region 1 (1- (point)) (not arg) 'outline)))
298
299 ;;;;; Heading visibility
300
301 (defun org-fold-heading (flag &optional entry)
302 "Fold/unfold the current heading. FLAG non-nil means make invisible.
303 When ENTRY is non-nil, show the entire entry."
304 (save-excursion
305 (org-back-to-heading t)
306 ;; Check if we should show the entire entry
307 (if (not entry)
308 (org-fold-region
309 (line-end-position 0) (line-end-position) flag 'outline)
310 (org-fold-show-entry)
311 (save-excursion
312 ;; FIXME: potentially catches inlinetasks
313 (and (outline-next-heading)
314 (org-fold-heading nil))))))
315
316 (defun org-fold-hide-entry ()
317 "Hide the body directly following this heading."
318 (interactive)
319 (save-excursion
320 (org-back-to-heading-or-point-min t)
321 (when (org-at-heading-p) (forward-line))
322 (unless (or (eobp) (org-at-heading-p)) ; Current headline is empty.
323 (org-fold-region
324 (line-end-position 0)
325 (save-excursion
326 (if (re-search-forward
327 (concat "[\r\n]" (org-get-limited-outline-regexp)) nil t)
328 (line-end-position 0)
329 (point-max)))
330 t
331 'outline))))
332
333 (defun org-fold-subtree (flag)
334 "Hide (when FLAG) or reveal subtree at point."
335 (save-excursion
336 (org-back-to-heading t)
337 (org-fold-region
338 (line-end-position)
339 (progn (org-end-of-subtree t t) (if (eobp) (point) (1- (point))))
340 flag
341 'outline)))
342
343 ;; Replaces `outline-hide-subtree'.
344 (defun org-fold-hide-subtree ()
345 "Hide everything after this heading at deeper levels."
346 (interactive)
347 (org-fold-subtree t))
348
349 ;; Replaces `outline-hide-sublevels'
350 (defun org-fold-hide-sublevels (levels)
351 "Hide everything but the top LEVELS levels of headers, in whole buffer.
352 This also unhides the top heading-less body, if any.
353
354 Interactively, the prefix argument supplies the value of LEVELS.
355 When invoked without a prefix argument, LEVELS defaults to the level
356 of the current heading, or to 1 if the current line is not a heading."
357 (interactive (list
358 (cond
359 (current-prefix-arg (prefix-numeric-value current-prefix-arg))
360 ((save-excursion (beginning-of-line)
361 (looking-at outline-regexp))
362 (funcall outline-level))
363 (t 1))))
364 (if (< levels 1)
365 (error "Must keep at least one level of headers"))
366 (save-excursion
367 (let* ((beg (progn
368 (goto-char (point-min))
369 ;; Skip the prelude, if any.
370 (unless (org-at-heading-p) (outline-next-heading))
371 (point)))
372 (end (progn
373 (goto-char (point-max))
374 ;; Keep empty last line, if available.
375 (max (point-min) (if (bolp) (1- (point)) (point))))))
376 (if (< end beg)
377 (setq beg (prog1 end (setq end beg))))
378 ;; First hide everything.
379 (org-fold-region beg end t 'headline)
380 ;; Then unhide the top level headers.
381 (org-map-region
382 (lambda ()
383 (when (<= (funcall outline-level) levels)
384 (org-fold-heading nil)))
385 beg end)
386 ;; Finally unhide any trailing newline.
387 (goto-char (point-max))
388 (if (and (bolp) (not (bobp)) (outline-invisible-p (1- (point))))
389 (org-fold-region (max (point-min) (1- (point))) (point) nil)))))
390
391 (defun org-fold-show-entry (&optional hide-drawers)
392 "Show the body directly following its heading.
393 Show the heading too, if it is currently invisible."
394 (interactive)
395 (save-excursion
396 (org-back-to-heading-or-point-min t)
397 (org-fold-region
398 (line-end-position 0)
399 (save-excursion
400 (if (re-search-forward
401 (concat "[\r\n]\\(" (org-get-limited-outline-regexp) "\\)") nil t)
402 (match-beginning 1)
403 (point-max)))
404 nil
405 'outline)
406 (when hide-drawers (org-cycle-hide-drawers 'children))))
407
408 (defalias 'org-fold-show-hidden-entry #'org-fold-show-entry
409 "Show an entry where even the heading is hidden.")
410
411 (defun org-fold-show-siblings ()
412 "Show all siblings of the current headline."
413 (save-excursion
414 (while (org-goto-sibling) (org-fold-heading nil)))
415 (save-excursion
416 (while (org-goto-sibling 'previous)
417 (org-fold-heading nil))))
418
419 (defun org-fold-show-children (&optional level)
420 "Show all direct subheadings of this heading.
421 Prefix arg LEVEL is how many levels below the current level
422 should be shown. Default is enough to cause the following
423 heading to appear."
424 (interactive "p")
425 (unless (org-before-first-heading-p)
426 (save-excursion
427 (org-with-limited-levels (org-back-to-heading t))
428 (let* ((current-level (funcall outline-level))
429 (max-level (org-get-valid-level
430 current-level
431 (if level (prefix-numeric-value level) 1)))
432 (end (save-excursion (org-end-of-subtree t t)))
433 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
434 (past-first-child nil)
435 ;; Make sure to skip inlinetasks.
436 (re (format regexp-fmt
437 current-level
438 (cond
439 ((not (featurep 'org-inlinetask)) "")
440 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
441 3))
442 (t (1- org-inlinetask-min-level))))))
443 ;; Display parent heading.
444 (org-fold-heading nil)
445 (forward-line)
446 ;; Display children. First child may be deeper than expected
447 ;; MAX-LEVEL. Since we want to display it anyway, adjust
448 ;; MAX-LEVEL accordingly.
449 (while (re-search-forward re end t)
450 (unless past-first-child
451 (setq re (format regexp-fmt
452 current-level
453 (max (funcall outline-level) max-level)))
454 (setq past-first-child t))
455 (org-fold-heading nil))))))
456
457 (defun org-fold-show-subtree ()
458 "Show everything after this heading at deeper levels."
459 (interactive)
460 (org-fold-region
461 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
462
463 (defun org-fold-show-branches ()
464 "Show all subheadings of this heading, but not their bodies."
465 (interactive)
466 (org-fold-show-children 1000))
467
468 (defun org-fold-show-branches-buffer ()
469 "Show all branches in the buffer."
470 (org-fold-flag-above-first-heading)
471 (org-fold-hide-sublevels 1)
472 (unless (eobp)
473 (org-fold-show-branches)
474 (while (outline-get-next-sibling)
475 (org-fold-show-branches)))
476 (goto-char (point-min)))
477
478 ;;;;; Blocks and drawers visibility
479
480 (defun org-fold--hide-wrapper-toggle (element category force no-error)
481 "Toggle visibility for ELEMENT.
482
483 ELEMENT is a block or drawer type parsed element. CATEGORY is
484 either `block' or `drawer'. When FORCE is `off', show the block
485 or drawer. If it is non-nil, hide it unconditionally. Throw an
486 error when not at a block or drawer, unless NO-ERROR is non-nil.
487
488 Return a non-nil value when toggling is successful."
489 (let ((type (org-element-type element)))
490 (cond
491 ((memq type
492 (pcase category
493 (`drawer '(drawer property-drawer))
494 (`block '(center-block
495 comment-block dynamic-block example-block export-block
496 quote-block special-block src-block verse-block))
497 (_ (error "Unknown category: %S" category))))
498 (let* ((post (org-element-property :post-affiliated element))
499 (start (save-excursion
500 (goto-char post)
501 (line-end-position)))
502 (end (save-excursion
503 (goto-char (org-element-property :end element))
504 (skip-chars-backward " \t\n")
505 (line-end-position))))
506 ;; Do nothing when not before or at the block opening line or
507 ;; at the block closing line.
508 (unless (let ((eol (line-end-position)))
509 (and (> eol start) (/= eol end)))
510 (org-fold-region start end
511 (cond ((eq force 'off) nil)
512 (force t)
513 ((org-fold-folded-p start category) nil)
514 (t t))
515 category)
516 ;; When the block is hidden away, make sure point is left in
517 ;; a visible part of the buffer.
518 (when (invisible-p (max (1- (point)) (point-min)))
519 (goto-char post))
520 ;; Signal success.
521 t)))
522 (no-error nil)
523 (t
524 (user-error (format "%s@%s: %s"
525 (buffer-file-name (buffer-base-buffer))
526 (point)
527 (if (eq category 'drawer)
528 "Not at a drawer"
529 "Not at a block")))))))
530
531 (defun org-fold-hide-block-toggle (&optional force no-error element)
532 "Toggle the visibility of the current block.
533
534 When optional argument FORCE is `off', make block visible. If it
535 is non-nil, hide it unconditionally. Throw an error when not at
536 a block, unless NO-ERROR is non-nil. When optional argument
537 ELEMENT is provided, consider it instead of the current block.
538
539 Return a non-nil value when toggling is successful."
540 (interactive)
541 (org-fold--hide-wrapper-toggle
542 (or element (org-element-at-point)) 'block force no-error))
543
544 (defun org-fold-hide-drawer-toggle (&optional force no-error element)
545 "Toggle the visibility of the current drawer.
546
547 When optional argument FORCE is `off', make drawer visible. If
548 it is non-nil, hide it unconditionally. Throw an error when not
549 at a drawer, unless NO-ERROR is non-nil. When optional argument
550 ELEMENT is provided, consider it instead of the current drawer.
551
552 Return a non-nil value when toggling is successful."
553 (interactive)
554 (org-fold--hide-wrapper-toggle
555 (or element (org-element-at-point)) 'drawer force no-error))
556
557 (defun org-fold-hide-block-all ()
558 "Fold all blocks in the current buffer."
559 (interactive)
560 (org-block-map (apply-partially #'org-fold-hide-block-toggle 'hide)))
561
562 (defun org-fold-hide-drawer-all ()
563 "Fold all drawers in the current buffer."
564 (let ((begin (point-min))
565 (end (point-max)))
566 (org-fold--hide-drawers begin end)))
567
568 (defun org-fold--hide-drawers (begin end)
569 "Hide all drawers between BEGIN and END."
570 (save-excursion
571 (goto-char begin)
572 (while (and (< (point) end)
573 (re-search-forward org-drawer-regexp end t))
574 ;; Skip folded drawers
575 (if (org-fold-folded-p nil 'drawer)
576 (goto-char (org-fold-next-folding-state-change 'drawer nil end))
577 (let* ((drawer (org-element-at-point))
578 (type (org-element-type drawer)))
579 (when (memq type '(drawer property-drawer))
580 (org-fold-hide-drawer-toggle t nil drawer)
581 ;; Make sure to skip drawer entirely or we might flag it
582 ;; another time when matching its ending line with
583 ;; `org-drawer-regexp'.
584 (goto-char (org-element-property :end drawer))))))))
585
586 (defun org-fold-hide-archived-subtrees (beg end)
587 "Re-hide all archived subtrees after a visibility state change."
588 (org-with-wide-buffer
589 (let ((case-fold-search nil)
590 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
591 (goto-char beg)
592 ;; Include headline point is currently on.
593 (beginning-of-line)
594 (while (and (< (point) end) (re-search-forward re end t))
595 (when (member org-archive-tag (org-get-tags nil t))
596 (org-fold-subtree t)
597 (org-end-of-subtree t))))))
598
599 ;;;;; Reveal point location
600
601 (defun org-fold-show-context (&optional key)
602 "Make sure point and context are visible.
603 Optional argument KEY, when non-nil, is a symbol. See
604 `org-fold-show-context-detail' for allowed values and how much is to
605 be shown."
606 (org-fold-show-set-visibility
607 (cond ((symbolp org-fold-show-context-detail) org-fold-show-context-detail)
608 ((cdr (assq key org-fold-show-context-detail)))
609 (t (cdr (assq 'default org-fold-show-context-detail))))))
610
611
612 (defvar org-hide-emphasis-markers); Defined in org.el
613 (defvar org-pretty-entities); Defined in org.el
614 (defun org-fold-show-set-visibility (detail)
615 "Set visibility around point according to DETAIL.
616 DETAIL is either nil, `minimal', `local', `ancestors',
617 `ancestors-full', `lineage', `tree', `canonical' or t. See
618 `org-show-context-detail' for more information."
619 ;; Show current heading and possibly its entry, following headline
620 ;; or all children.
621 (if (and (org-at-heading-p) (not (eq detail 'local)))
622 (org-fold-heading nil)
623 (org-fold-show-entry)
624 ;; If point is hidden make sure to expose it.
625 (when (org-invisible-p)
626 ;; FIXME: No clue why, but otherwise the following might not work.
627 (redisplay)
628 (let ((region (org-fold-get-region-at-point)))
629 ;; Reveal emphasis markers.
630 (when (eq detail 'local)
631 (let (org-hide-emphasis-markers
632 org-link-descriptive
633 org-pretty-entities
634 (org-hide-macro-markers nil)
635 (region (or (org-find-text-property-region (point) 'org-emphasis)
636 (org-find-text-property-region (point) 'org-macro)
637 (org-find-text-property-region (point) 'invisible)
638 region)))
639 ;; Silence byte-compiler.
640 (ignore org-hide-macro-markers)
641 (when region
642 (org-with-point-at (car region)
643 (beginning-of-line)
644 (let (font-lock-extend-region-functions)
645 (font-lock-fontify-region (max (point-min) (1- (car region))) (cdr region))))))
646 ;; Unfold links.
647 (when region
648 (dolist (spec '(org-link org-link-description))
649 (org-fold-region (car region) (cdr region) nil spec))))
650 (when region
651 (dolist (spec (org-fold-core-folding-spec-list))
652 ;; Links are taken care by above.
653 (unless (memq spec '(org-link org-link-description))
654 (org-fold-region (car region) (cdr region) nil spec))))))
655 (unless (org-before-first-heading-p)
656 (org-with-limited-levels
657 (cl-case detail
658 ((tree canonical t) (org-fold-show-children))
659 ((nil minimal ancestors ancestors-full))
660 (t (save-excursion
661 (outline-next-heading)
662 (org-fold-heading nil)))))))
663 ;; Show whole subtree.
664 (when (eq detail 'ancestors-full) (org-fold-show-subtree))
665 ;; Show all siblings.
666 (when (eq detail 'lineage) (org-fold-show-siblings))
667 ;; Show ancestors, possibly with their children.
668 (when (memq detail '(ancestors ancestors-full lineage tree canonical t))
669 (save-excursion
670 (while (org-up-heading-safe)
671 (org-fold-heading nil)
672 (when (memq detail '(canonical t)) (org-fold-show-entry))
673 (when (memq detail '(tree canonical t)) (org-fold-show-children))))))
674
675 (defun org-fold-reveal (&optional siblings)
676 "Show current entry, hierarchy above it, and the following headline.
677
678 This can be used to show a consistent set of context around
679 locations exposed with `org-fold-show-context'.
680
681 With optional argument SIBLINGS, on each level of the hierarchy all
682 siblings are shown. This repairs the tree structure to what it would
683 look like when opened with hierarchical calls to `org-cycle'.
684
685 With a \\[universal-argument] \\[universal-argument] prefix, \
686 go to the parent and show the entire tree."
687 (interactive "P")
688 (run-hooks 'org-fold-reveal-start-hook)
689 (cond ((equal siblings '(4)) (org-fold-show-set-visibility 'canonical))
690 ((equal siblings '(16))
691 (save-excursion
692 (when (org-up-heading-safe)
693 (org-fold-show-subtree)
694 (run-hook-with-args 'org-cycle-hook 'subtree))))
695 (t (org-fold-show-set-visibility 'lineage))))
696
697 ;;; Make isearch search in some text hidden via text properties.
698
699 (defun org-fold--isearch-reveal (&rest _)
700 "Reveal text at POS found by isearch."
701 (org-fold-show-context 'isearch))
702
703 ;;; Handling changes in folded elements
704
705 (defun org-fold--extend-changed-region (from to)
706 "Consider folded regions in the next/previous line when fixing
707 region visibility.
708 This function is intended to be used as a member of
709 `org-fold-core-extend-changed-region-functions'."
710 ;; If the edit is done in the first line of a folded drawer/block,
711 ;; the folded text is only starting from the next line and needs to
712 ;; be checked.
713 (setq to (save-excursion (goto-char to) (line-beginning-position 2)))
714 ;; If the ":END:" line of the drawer is deleted, the folded text is
715 ;; only ending at the previous line and needs to be checked.
716 (setq from (save-excursion (goto-char from) (line-beginning-position 0)))
717 (cons from to))
718
719 (defun org-fold--reveal-headline-at-point ()
720 "Reveal header line and empty contents inside.
721 Reveal the header line and, if present, also reveal its contents, when
722 the contents consists of blank lines.
723
724 Assume that point is located at the header line."
725 (org-with-wide-buffer
726 (beginning-of-line)
727 (org-fold-region
728 (max (point-min) (1- (point)))
729 (let ((endl (line-end-position)))
730 (save-excursion
731 (goto-char endl)
732 (skip-chars-forward "\n\t\r ")
733 ;; Unfold blank lines after newly inserted headline.
734 (if (equal (point)
735 (save-excursion
736 (goto-char endl)
737 (org-end-of-subtree)
738 (skip-chars-forward "\n\t\r ")))
739 (point)
740 endl)))
741 nil 'headline)))
742
743 (defun org-fold--reveal-outline-maybe (region _)
744 "Reveal folded outline in REGION when needed.
745
746 This function is intended to be used as :fragile property of
747 `org-fold-outline' spec. See `org-fold-core--specs' for details."
748 (save-match-data
749 (org-with-wide-buffer
750 (goto-char (car region))
751 ;; The line before beginning of the fold should be either a
752 ;; headline or a list item.
753 (backward-char)
754 (beginning-of-line)
755 ;; Make sure that headline is not partially hidden.
756 (unless (org-fold-folded-p nil 'headline)
757 (org-fold--reveal-headline-at-point))
758 ;; Never hide level 1 headlines
759 (save-excursion
760 (goto-char (line-end-position))
761 (unless (>= (point) (cdr region))
762 (when (re-search-forward (rx bol "* ") (cdr region) t)
763 (org-fold--reveal-headline-at-point))))
764 ;; Make sure that headline after is not partially hidden.
765 (goto-char (cdr region))
766 (beginning-of-line)
767 (unless (org-fold-folded-p nil 'headline)
768 (when (looking-at-p org-element-headline-re)
769 (org-fold--reveal-headline-at-point)))
770 ;; Check the validity of headline
771 (goto-char (car region))
772 (backward-char)
773 (beginning-of-line)
774 (unless (let ((case-fold-search t))
775 (looking-at (rx-to-string
776 `(or (regex ,(org-item-re))
777 (regex ,org-outline-regexp-bol)))))
778 t))))
779
780 (defun org-fold--reveal-drawer-or-block-maybe (region spec)
781 "Reveal folded drawer/block (according to SPEC) in REGION when needed.
782
783 This function is intended to be used as :fragile property of
784 `org-fold-drawer' or `org-fold-block' spec."
785 (let ((begin-re (cond
786 ((eq spec (org-fold-core-get-folding-spec-from-alias 'drawer))
787 org-drawer-regexp)
788 ;; Group one below contains the type of the block.
789 ((eq spec (org-fold-core-get-folding-spec-from-alias 'block))
790 (rx bol (zero-or-more (any " " "\t"))
791 "#+begin"
792 (or ":"
793 (seq "_"
794 (group (one-or-more (not (syntax whitespace))))))))))
795 ;; To be determined later. May depend on `begin-re' match (i.e. for blocks).
796 end-re)
797 (save-match-data ; we should not clobber match-data in after-change-functions
798 (let ((fold-begin (car region))
799 (fold-end (cdr region)))
800 (let (unfold?)
801 (catch :exit
802 ;; The line before folded text should be beginning of
803 ;; the drawer/block.
804 (save-excursion
805 (goto-char fold-begin)
806 ;; The line before beginning of the fold should be the
807 ;; first line of the drawer/block.
808 (backward-char)
809 (beginning-of-line)
810 (unless (let ((case-fold-search t))
811 (looking-at begin-re)) ; the match-data will be used later
812 (throw :exit (setq unfold? t))))
813 ;; Set `end-re' for the current drawer/block.
814 (setq end-re
815 (cond
816 ((eq spec (org-fold-core-get-folding-spec-from-alias 'drawer))
817 org-property-end-re)
818 ((eq spec (org-fold-core-get-folding-spec-from-alias 'block))
819 (let ((block-type (match-string 1))) ; the last match is from `begin-re'
820 (concat (rx bol (zero-or-more (any " " "\t")) "#+end")
821 (if block-type
822 (concat "_"
823 (regexp-quote block-type)
824 (rx (zero-or-more (any " " "\t")) eol))
825 (rx (opt ":") (zero-or-more (any " " "\t")) eol)))))))
826 ;; The last line of the folded text should match `end-re'.
827 (save-excursion
828 (goto-char fold-end)
829 (beginning-of-line)
830 (unless (let ((case-fold-search t))
831 (looking-at end-re))
832 (throw :exit (setq unfold? t))))
833 ;; There should be no `end-re' or
834 ;; `org-outline-regexp-bol' anywhere in the
835 ;; drawer/block body.
836 (save-excursion
837 (goto-char fold-begin)
838 (when (save-excursion
839 (let ((case-fold-search t))
840 (re-search-forward (rx-to-string `(or (regex ,end-re)
841 (regex ,org-outline-regexp-bol)))
842 (max (point)
843 (1- (save-excursion
844 (goto-char fold-end)
845 (line-beginning-position))))
846 t)))
847 (throw :exit (setq unfold? t)))))
848 unfold?)))))
849
850 ;; Catching user edits inside invisible text
851 (defun org-fold-check-before-invisible-edit (kind)
852 "Check if editing KIND is dangerous with invisible text around.
853 The detailed reaction depends on the user option
854 `org-fold-catch-invisible-edits'."
855 ;; First, try to get out of here as quickly as possible, to reduce overhead
856 (when (and org-fold-catch-invisible-edits
857 (or (not (boundp 'visible-mode)) (not visible-mode))
858 (or (org-invisible-p)
859 (org-invisible-p (max (point-min) (1- (point))))))
860 ;; OK, we need to take a closer look. Only consider invisibility
861 ;; caused by folding of headlines, drawers, and blocks. Edits
862 ;; inside links will be handled by font-lock.
863 (let* ((invisible-at-point (org-fold-folded-p (point) '(headline drawer block)))
864 (invisible-before-point
865 (and (not (bobp))
866 (org-fold-folded-p (1- (point)) '(headline drawer block))))
867 (border-and-ok-direction
868 (or
869 ;; Check if we are acting predictably before invisible
870 ;; text.
871 (and invisible-at-point (not invisible-before-point)
872 (memq kind '(insert delete-backward)))
873 ;; Check if we are acting predictably after invisible text
874 ;; This works not well, and I have turned it off. It seems
875 ;; better to always show and stop after invisible text.
876 ;; (and (not invisible-at-point) invisible-before-point
877 ;; (memq kind '(insert delete)))
878 )))
879 (when (or invisible-at-point invisible-before-point)
880 (when (eq org-fold-catch-invisible-edits 'error)
881 (user-error "Editing in invisible areas is prohibited, make them visible first"))
882 (if (and org-custom-properties-overlays
883 (y-or-n-p "Display invisible properties in this buffer? "))
884 (org-toggle-custom-properties-visibility)
885 ;; Make the area visible
886 (save-excursion
887 (org-fold-show-set-visibility 'local))
888 (when invisible-before-point
889 (org-with-point-at (1- (point)) (org-fold-show-set-visibility 'local)))
890 (cond
891 ((eq org-fold-catch-invisible-edits 'show)
892 ;; That's it, we do the edit after showing
893 (message
894 "Unfolding invisible region around point before editing")
895 (sit-for 1))
896 ((and (eq org-fold-catch-invisible-edits 'smart)
897 border-and-ok-direction)
898 (message "Unfolding invisible region around point before editing"))
899 (t
900 ;; Don't do the edit, make the user repeat it in full visibility
901 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
902
903 (provide 'org-fold)
904
905 ;;; org-fold.el ends here
00 ;;; org-footnote.el --- Footnote support in Org -*- lexical-binding: t; -*-
11 ;;
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2727
2828 ;;; Code:
2929
30 (require 'org-macs)
31 (org-assert-version)
32
3033 ;;;; Declarations
3134
3235 (require 'cl-lib)
3841 (declare-function org-back-over-empty-lines "org" ())
3942 (declare-function org-end-of-meta-data "org" (&optional full))
4043 (declare-function org-edit-footnote-reference "org-src" ())
41 (declare-function org-element-at-point "org-element" ())
44 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
4245 (declare-function org-element-class "org-element" (datum &optional parent))
4346 (declare-function org-element-context "org-element" (&optional element))
4447 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
5154 (declare-function org-inside-LaTeX-fragment-p "org" ())
5255 (declare-function org-inside-latex-macro-p "org" ())
5356 (declare-function org-mark-ring-push "org" (&optional pos buffer))
54 (declare-function org-show-context "org" (&optional key))
57 (declare-function org-fold-show-context "org-fold" (&optional key))
5558 (declare-function outline-next-heading "outline")
5659
5760 (defvar electric-indent-mode)
9093 (defcustom org-footnote-section "Footnotes"
9194 "Outline heading containing footnote definitions.
9295
93 This can be nil, to place footnotes locally at the end of the
94 current outline node. If can also be the name of a special
95 outline heading under which footnotes should be put.
96 This can be nil, to place footnotes locally at the end of the current
97 outline node. It can also be a string representing the name of a
98 special outline heading under which footnotes should be put.
9699
97100 This variable defines the place where Org puts the definition
98101 automatically, i.e. when creating the footnote, and when sorting
99 the notes. However, by hand you may place definitions
102 the notes. However, by hand, you may place definitions
100103 *anywhere*.
101104
102105 If this is a string, during export, all subtrees starting with
109112 :group 'org-footnote
110113 :initialize 'custom-initialize-default
111114 :set (lambda (var val)
112 (set var val)
115 (set-default-toplevel-value var val)
113116 (when (fboundp 'org-element-cache-reset)
114117 (org-element-cache-reset 'all)))
115118 :type '(choice
554557 (goto-char def-start)
555558 (looking-at (format "\\[fn:%s[]:]" (regexp-quote label)))
556559 (goto-char (match-end 0))
557 (org-show-context 'link-search)
560 (org-fold-show-context 'link-search)
558561 (when (derived-mode-p 'org-mode)
559562 (message "%s" (substitute-command-keys
560563 "Edit definition and go back with \
580583 (user-error "Reference is outside narrowed part of buffer")))
581584 (org-mark-ring-push)
582585 (goto-char start)
583 (org-show-context 'link-search)))
586 (org-fold-show-context 'link-search)))
584587
585588
586589 ;;;; Getters
847850 (format "[fn:%s] DEFINITION NOT FOUND." label))
848851 "\n"))))
849852 ;; Insert un-referenced footnote definitions at the end.
850 (pcase-dolist (`(,label . ,definition) definitions)
851 (unless (member label inserted)
852 (insert "\n" definition "\n")))))))))
853 ;; Combine all insertions into one to create a single cache
854 ;; update call.
855 (org-combine-change-calls (point) (point)
856 (pcase-dolist (`(,label . ,definition) definitions)
857 (unless (member label inserted)
858 (insert "\n" definition "\n"))))))))))
853859
854860 (defun org-footnote-normalize ()
855861 "Turn every footnote in buffer into a numbered one."
00 ;;; org-goto.el --- Fast navigation in an Org buffer -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2012-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2012-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
2020 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
2121
2222 ;;; Code:
23
24 (require 'org-macs)
25 (org-assert-version)
2326
2427 (require 'org)
2528 (require 'org-refile)
109112 (org-defkey map [(down)] 'outline-next-visible-heading)
110113 (org-defkey map [(up)] 'outline-previous-visible-heading)
111114 (if org-goto-auto-isearch
112 (if (fboundp 'define-key-after)
113 (define-key-after map [t] 'org-goto-local-auto-isearch)
114 nil)
115 (org-defkey map "q" 'org-goto-quit)
115 (define-key-after map [t] 'org-goto-local-auto-isearch)
116 (org-defkey map "q" 'org-goto-quit)
116117 (org-defkey map "n" 'outline-next-visible-heading)
117118 (org-defkey map "p" 'outline-previous-visible-heading)
118119 (org-defkey map "f" 'outline-forward-same-level)
156157 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
157158 (isearch-mode t)
158159 (isearch-process-search-char (string-to-char keys))
159 (org-font-lock-ensure))))
160 (font-lock-ensure))))
160161
161162 (defun org-goto-ret (&optional _arg)
162163 "Finish `org-goto' by going to the new location."
221222 " Just type for auto-isearch."
222223 " n/p/f/b/u to navigate, q to quit.")))))
223224 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
224 (org-overview)
225 (org-cycle-overview)
225226 (setq buffer-read-only t)
226227 (if (and (boundp 'org-goto-start-pos)
227228 (integer-or-marker-p org-goto-start-pos))
228229 (progn (goto-char org-goto-start-pos)
229230 (when (org-invisible-p)
230 (org-show-set-visibility 'lineage)))
231 (org-fold-show-set-visibility 'lineage)))
231232 (goto-char (point-min)))
232233 (let (org-special-ctrl-a/e) (org-beginning-of-line))
233234 (message "Select location and press RET")
278279 (org-mark-ring-push org-goto-start-pos)
279280 (goto-char selected-point)
280281 (when (or (org-invisible-p) (org-invisible-p2))
281 (org-show-context 'org-goto)))
282 (org-fold-show-context 'org-goto)))
282283 (message "Quit"))))
283284
284285 (provide 'org-goto)
00 ;;; org-habit.el --- The habit tracking code for Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33
44 ;; Author: John Wiegley <johnw at gnu dot org>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
2626 ;; This file contains the habit tracking code for Org mode
2727
2828 ;;; Code:
29
30 (require 'org-macs)
31 (org-assert-version)
2932
3033 (require 'cl-lib)
3134 (require 'org)
422425 "Insert consistency graph for any habitual tasks."
423426 (let ((inhibit-read-only t)
424427 (buffer-invisibility-spec '(org-link))
425 (moment (org-time-subtract nil
426 (* 3600 org-extend-today-until))))
428 (moment (time-subtract nil (* 3600 org-extend-today-until))))
427429 (save-excursion
428 (goto-char (if line (point-at-bol) (point-min)))
430 (goto-char (if line (line-beginning-position) (point-min)))
429431 (while (not (eobp))
430432 (let ((habit (get-text-property (point) 'org-habit-p))
431433 (invisible-prop (get-text-property (point) 'invisible)))
00 ;;; org-id.el --- Global identifiers for Org entries -*- lexical-binding: t; -*-
11 ;;
2 ;; Copyright (C) 2008-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2008-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
6969
7070 ;;; Code:
7171
72 (require 'org-macs)
73 (org-assert-version)
74
7275 (require 'org)
7376 (require 'org-refile)
7477 (require 'ol)
7578
7679 (declare-function message-make-fqdn "message" ())
7780 (declare-function org-goto-location "org-goto" (&optional _buf help))
81 ;; Declared inside `org-element-with-disabled-cache' macro.
82 (declare-function org-element--cache-active-p "org-element.el" (&optional called-from-cache-change-func-p))
7883
7984 ;;; Customization
8085
195200 :group 'org-id
196201 :type 'boolean)
197202
198 (defcustom org-id-locations-file (convert-standard-filename
199 (concat user-emacs-directory ".org-id-locations"))
203 (defcustom org-id-locations-file (locate-user-emacs-file ".org-id-locations")
200204 "The file for remembering in which file an ID was defined.
201205 This variable is only relevant when `org-id-track-globally' is set."
202206 :group 'org-id
330334 (pop-to-buffer-same-window (marker-buffer m))
331335 (goto-char m)
332336 (move-marker m nil)
333 (org-show-context)))
337 (org-fold-show-context)))
334338
335339 ;;;###autoload
336340 (defun org-id-find (id &optional markerp)
488492 (defun org-id-update-id-locations (&optional files silent)
489493 "Scan relevant files for IDs.
490494 Store the relation between files and corresponding IDs.
491 This will scan all agenda files, all associated archives, and all
492 files currently mentioned in `org-id-locations'.
495 This will scan all agenda files, all associated archives, all open Org
496 files, and all files currently mentioned in `org-id-locations'.
493497 When FILES is given, scan also these files.
494498 If SILENT is non-nil, messages are suppressed."
495499 (interactive)
512516 org-id-extra-files)
513517 ;; All files known to have IDs.
514518 org-id-files
519 ;; All Org files open in Emacs.
520 (mapcar #'buffer-file-name (org-buffer-list 'files t))
515521 ;; Additional files from function call.
516522 files)))))
517523 (nfiles (length files))
521527 (ndup 0)
522528 (i 0))
523529 (with-temp-buffer
524 (delay-mode-hooks
525 (org-mode)
526 (dolist (file files)
527 (when (file-exists-p file)
528 (unless silent
529 (cl-incf i)
530 (message "Finding ID locations (%d/%d files): %s" i nfiles file))
531 (insert-file-contents file nil nil nil 'replace)
532 (let ((ids nil)
533 (case-fold-search t))
534 (org-with-point-at 1
535 (while (re-search-forward id-regexp nil t)
536 (when (org-at-property-p)
537 (push (org-entry-get (point) "ID") ids)))
538 (when ids
539 (push (cons (abbreviate-file-name file) ids)
540 org-id-locations)
541 (dolist (id ids)
542 (cond
543 ((not (member id seen-ids)) (push id seen-ids))
544 (silent nil)
545 (t
546 (message "Duplicate ID %S" id)
547 (cl-incf ndup)))))))))))
530 (org-element-with-disabled-cache
531 (delay-mode-hooks
532 (org-mode)
533 (dolist (file files)
534 (when (file-exists-p file)
535 (unless silent
536 (cl-incf i)
537 (message "Finding ID locations (%d/%d files): %s" i nfiles file))
538 (insert-file-contents file nil nil nil 'replace)
539 (let ((ids nil)
540 (case-fold-search t))
541 (org-with-point-at 1
542 (while (re-search-forward id-regexp nil t)
543 (when (org-at-property-p)
544 (push (org-entry-get (point) "ID") ids)))
545 (when ids
546 (push (cons (abbreviate-file-name file) ids)
547 org-id-locations)
548 (dolist (id ids)
549 (cond
550 ((not (member id seen-ids)) (push id seen-ids))
551 (silent nil)
552 (t
553 (message "Duplicate ID %S" id)
554 (cl-incf ndup))))))))))))
548555 (setq org-id-files (mapcar #'car org-id-locations))
549556 (org-id-locations-save)
550557 ;; Now convert to a hash table.
591598 (setf (car item) (expand-file-name (car item) loc))))
592599 org-id-locations)))
593600 (error
594 (message "Could not read `org-id-values' from %s, setting it to nil"
601 (message "Could not read `org-id-locations' from %s, setting it to nil"
595602 org-id-locations-file))))
596603 (setq org-id-files (mapcar 'car org-id-locations))
597604 (setq org-id-locations (org-id-alist-to-hash org-id-locations))))
741748 (funcall cmd (marker-buffer m)))
742749 (goto-char m)
743750 (move-marker m nil)
744 (org-show-context)))
751 (org-fold-show-context)))
745752
746753 (org-link-set-parameters "id" :follow #'org-id-open)
747754
00 ;;; org-indent.el --- Dynamic indentation for Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
3434 ;; idle time.
3535 ;;
3636 ;;; Code:
37
38 (require 'org-macs)
39 (org-assert-version)
3740
3841 (require 'org-macs)
3942 (require 'org-compat)
329332 (let* ((case-fold-search t)
330333 (limited-re (org-get-limited-outline-regexp))
331334 (level (or (org-current-level) 0))
332 (time-limit (and delay (org-time-add nil delay))))
335 (time-limit (and delay (time-add nil delay))))
333336 ;; For each line, set `line-prefix' and `wrap-prefix'
334337 ;; properties depending on the type of line (headline, inline
335338 ;; task, item or other).
342345 ;; In asynchronous mode, take a break of
343346 ;; `org-indent-agent-resume-delay' every DELAY to avoid
344347 ;; blocking any other idle timer or process output.
345 ((and delay (org-time-less-p time-limit nil))
348 ((and delay (time-less-p time-limit nil))
346349 (setq org-indent-agent-resume-timer
347350 (run-with-idle-timer
348351 (time-add (current-idle-time) org-indent-agent-resume-delay)
408411 (goto-char beg)
409412 (beginning-of-line)
410413 (re-search-forward
411 (org-with-limited-levels org-outline-regexp-bol) end t)))
414 (org-with-limited-levels org-outline-regexp-bol)
415 (save-excursion
416 (goto-char end)
417 ;; Extend to headline if END is within its
418 ;; headline stars.
419 (line-end-position))
420 t)))
412421 (let ((end (save-excursion
413422 (goto-char end)
414423 (org-with-limited-levels (outline-next-heading))
00 ;;; org-inlinetask.el --- Tasks Independent of Outline Hierarchy -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
7676 ;; C-c C-x t Insert a new inline task with END line
7777
7878 ;;; Code:
79
80 (require 'org-macs)
81 (org-assert-version)
7982
8083 (require 'org)
8184
237240 (setq beg (point))
238241 (replace-match down-task nil t nil 1)
239242 (org-inlinetask-goto-end)
240 (if (and (eobp) (looking-back "END\\s-*" (point-at-bol)))
243 (if (and (eobp) (looking-back "END\\s-*" (line-beginning-position)))
241244 (beginning-of-line)
242245 (forward-line -1))
243246 (unless (= (point) beg)
263266 (setq beg (point))
264267 (replace-match down-task nil t nil 1)
265268 (org-inlinetask-goto-end)
266 (if (and (eobp) (looking-back "END\\s-*" (point-at-bol)))
269 (if (and (eobp) (looking-back "END\\s-*" (line-beginning-position)))
267270 (beginning-of-line)
268271 (forward-line -1))
269272 (unless (= (point) beg)
304307 (add-text-properties (match-beginning 3) (match-end 3)
305308 '(face org-inlinetask font-lock-fontified t)))))
306309
307 (defun org-inlinetask-toggle-visibility ()
308 "Toggle visibility of inline task at point."
310 (defun org-inlinetask-toggle-visibility (&optional state)
311 "Toggle visibility of inline task at point.
312 When optional argument STATE is `fold', fold unconditionally.
313 When STATE is `unfold', unfold unconditionally."
309314 (let ((end (save-excursion
310315 (org-inlinetask-goto-end)
311316 (if (bolp) (1- (point)) (point))))
312317 (start (save-excursion
313318 (org-inlinetask-goto-beginning)
314 (point-at-eol))))
319 (line-end-position))))
315320 (cond
316321 ;; Nothing to show/hide.
317322 ((= end start))
318323 ;; Inlinetask was folded: expand it.
319 ((eq (get-char-property (1+ start) 'invisible) 'outline)
320 (org-flag-region start end nil 'outline))
321 (t (org-flag-region start end t 'outline)))))
324 ((and (not (eq state 'fold))
325 (or (eq state 'unfold)
326 (org-fold-get-folding-spec 'headline (1+ start))))
327 (org-fold-region start end nil 'headline))
328 (t (org-fold-region start end t 'headline)))))
322329
323330 (defun org-inlinetask-hide-tasks (state)
324331 "Hide inline tasks in buffer when STATE is `contents' or `children'.
329336 (save-excursion
330337 (goto-char (point-min))
331338 (while (re-search-forward regexp nil t)
332 (org-inlinetask-toggle-visibility)
339 (org-inlinetask-toggle-visibility 'fold)
333340 (org-inlinetask-goto-end)))))
334341 (`children
335342 (save-excursion
336343 (while
337344 (or (org-inlinetask-at-task-p)
338345 (and (outline-next-heading) (org-inlinetask-at-task-p)))
339 (org-inlinetask-toggle-visibility)
346 (org-inlinetask-toggle-visibility 'fold)
340347 (org-inlinetask-goto-end))))))
341348
342349 (defun org-inlinetask-remove-END-maybe ()
+0
-17
lisp/org-install.el less more
0 ;;; org-install.el --- backward compatibility file for obsolete configuration -*- lexical-binding: t -*-
1 ;;
2 ;;; Code:
3 ;;
4 ;; The file org-install is obsolete.
5 ;;
6 ;; It is provided here so that (require 'org-install) does not
7 ;; trigger an error for users with obsolete Emacs configuration.
8 ;; You can safely remove (require 'org-install) from your config."
9
10 (provide 'org-install)
11
12 ;; Local Variables:
13 ;; no-byte-compile: t
14 ;; coding: utf-8
15 ;; End:
16 ;;; org-install.el ends here
00 ;;; org-keys.el --- Key bindings for Org mode -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2018-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2018-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55
2525 ;; details.
2626
2727 ;;; Code:
28
29 (require 'org-macs)
30 (org-assert-version)
2831
2932 (require 'cl-lib)
3033
6669 (declare-function org-ctrl-c-tab "org" (&optional arg))
6770 (declare-function org-cut-special "org" ())
6871 (declare-function org-cut-subtree "org" (&optional n))
69 (declare-function org-cycle "org" (&optional arg))
70 (declare-function org-cycle-agenda-files "org" ())
72 (declare-function org-cycle "org-cycle" (&optional arg))
73 (declare-function org-cycle-agenda-files "org-cycle" ())
7174 (declare-function org-date-from-calendar "org" ())
7275 (declare-function org-dynamic-block-insert-dblock "org" (&optional arg))
7376 (declare-function org-dblock-update "org" (&optional arg))
8083 (declare-function org-display-outline-path "org" (&optional file current separator just-return-string))
8184 (declare-function org-down-element "org" ())
8285 (declare-function org-edit-special "org" (&optional arg))
83 (declare-function org-element-at-point "org-element" ())
86 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
8487 (declare-function org-element-type "org-element" (element))
8588 (declare-function org-emphasize "org" (&optional char))
8689 (declare-function org-end-of-line "org" (&optional n))
9396 (declare-function org-fill-paragraph "org" (&optional justify region))
9497 (declare-function org-find-file-at-mouse "org" (ev))
9598 (declare-function org-footnote-action "org" (&optional special))
96 (declare-function org-force-cycle-archived "org" ())
99 (declare-function org-cycle-force-archived "org-cycle" ())
97100 (declare-function org-force-self-insert "org" (n))
98101 (declare-function org-forward-element "org" ())
99102 (declare-function org-forward-heading-same-level "org" (arg &optional invisible-ok))
127130 (declare-function org-metaup "org" (&optional _arg))
128131 (declare-function org-narrow-to-block "org" ())
129132 (declare-function org-narrow-to-element "org" ())
130 (declare-function org-narrow-to-subtree "org" ())
133 (declare-function org-narrow-to-subtree "org" (&optional element))
131134 (declare-function org-next-block "org" (arg &optional backward block-regexp))
132135 (declare-function org-next-link "org" (&optional search-backward))
133136 (declare-function org-next-visible-heading "org" (arg))
142145 (declare-function org-priority "org" (&optional action show))
143146 (declare-function org-promote-subtree "org" ())
144147 (declare-function org-redisplay-inline-images "org" ())
145 (declare-function org-refile "org" (&optional arg1 default-buffer rfloc msg))
146 (declare-function org-refile-copy "org" ())
148 (declare-function org-refile "org-refile" (&optional arg1 default-buffer rfloc msg))
149 (declare-function org-refile-copy "org-refile" ())
147150 (declare-function org-refile-reverse "org-refile" (&optional arg default-buffer rfloc msg))
148151 (declare-function org-reftex-citation "org" ())
149152 (declare-function org-reload "org" (&optional arg1))
151154 (declare-function org-resolve-clocks "org" (&optional only-dangling-p prompt-fn last-valid))
152155 (declare-function org-return "org" (&optional indent))
153156 (declare-function org-return-and-maybe-indent "org" ())
154 (declare-function org-reveal "org" (&optional siblings))
157 (declare-function org-fold-reveal "org-fold" (&optional siblings))
155158 (declare-function org-schedule "org" (arg &optional time))
156159 (declare-function org-self-insert-command "org" (N))
157160 (declare-function org-set-effort "org" (&optional increment value))
171174 (declare-function org-shiftright "org" (&optional arg))
172175 (declare-function org-shifttab "org" (&optional arg))
173176 (declare-function org-shiftup "org" (&optional arg))
174 (declare-function org-show-all "org" (&optional types))
175 (declare-function org-show-children "org" (&optional level))
176 (declare-function org-show-subtree "org" ())
177 (declare-function org-fold-show-all "org-fold" (&optional types))
178 (declare-function org-fold-show-children "org-fold" (&optional level))
179 (declare-function org-fold-show-subtree "org-fold" ())
177180 (declare-function org-sort "org" (&optional with-case))
178181 (declare-function org-sparse-tree "org" (&optional arg type))
179182 (declare-function org-table-copy-down "org" (n))
200203 (declare-function org-toggle-radio-button "org" (&optional arg))
201204 (declare-function org-toggle-comment "org" ())
202205 (declare-function org-toggle-fixed-width "org" ())
203 (declare-function org-toggle-inline-images "org" (&optional include-linked))
206 (declare-function org-toggle-inline-images "org" (&optional include-linked beg end))
204207 (declare-function org-latex-preview "org" (&optional arg))
205208 (declare-function org-toggle-narrow-to-subtree "org" ())
206209 (declare-function org-toggle-ordered-property "org" ())
243246
244247 (defcustom org-use-extra-keys nil
245248 "Non-nil means use extra key sequence definitions for certain commands.
246 This happens automatically if `window-system' is nil. This
249 This happens automatically if `display-graphic-p' returns nil. This
247250 variable lets you do the same manually. You must set it before
248251 loading Org."
249252 :group 'org-startup
422425 (define-key org-mode-map [menu-bar show] 'undefined)
423426
424427 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
425 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
428 (define-key org-mode-map [remap outline-show-subtree] #'org-fold-show-subtree)
426429 (define-key org-mode-map [remap outline-forward-same-level]
427430 #'org-forward-heading-same-level)
428431 (define-key org-mode-map [remap outline-backward-same-level]
436439 #'org-next-visible-heading)
437440 (define-key org-mode-map [remap outline-previous-visible-heading]
438441 #'org-previous-visible-heading)
439 (define-key org-mode-map [remap show-children] #'org-show-children)
442 (define-key org-mode-map [remap outline-show-children] #'org-fold-show-children)
440443
441444 ;;;; Make `C-c C-x' a prefix key
442445 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
443446
444447 ;;;; TAB key with modifiers
445448 (org-defkey org-mode-map (kbd "TAB") #'org-cycle)
446 (org-defkey org-mode-map (kbd "C-c C-<tab>") #'org-force-cycle-archived)
449 (org-defkey org-mode-map (kbd "C-c C-<tab>") #'org-cycle-force-archived)
447450 ;; Override text-mode binding to expose `complete-symbol' for
448451 ;; pcomplete functionality.
449452 (org-defkey org-mode-map (kbd "M-TAB") nil)
461464
462465 ;;;; Cursor keys with modifiers
463466 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
467 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
464468 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
465469 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
466470 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
494498 ;; We only set them when really needed because otherwise the
495499 ;; menus don't show the simple keys
496500
497 (when (or org-use-extra-keys (not window-system))
501 (when (or org-use-extra-keys (not (display-graphic-p)))
498502 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
499503 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
500504 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
543547
544548 ;;;; All the other keys
545549 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
546 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
550 (org-defkey org-mode-map (kbd "C-c C-r") #'org-fold-reveal)
547551 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
548552 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
549553 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
803807 (interactive)
804808 (unless org-use-speed-commands
805809 (user-error "Speed commands are not activated, customize `org-use-speed-commands'"))
806 ;; FIXME: remove this warning for 9.6
807 (when (boundp 'org-speed-commands-user)
808 (message "`org-speed-command-user' is obsolete, please use `org-speed-commands'")
809 (sit-for 3))
810810 (with-output-to-temp-buffer "*Help*"
811811 (princ "Speed commands\n==============\n")
812812 (mapc #'org-print-speed-command
00 ;;; org-lint.el --- Linting for Org documents -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2015-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2015-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55 ;; Keywords: outlines, hypermedia, calendar, wp
2121
2222 ;;; Commentary:
2323
24 ;; This library implements linting for Org syntax. The sole public
25 ;; function is `org-lint', which see.
26
27 ;; Internally, the library defines a new structure:
28 ;; `org-lint-checker', with the following slots:
29
30 ;; - NAME: Unique check identifier, as a non-nil symbol that doesn't
31 ;; start with an hyphen.
32 ;;
33 ;; The check is done calling the function `org-lint-NAME' with one
34 ;; mandatory argument, the parse tree describing the current Org
35 ;; buffer. Such function calls are wrapped within
36 ;; a `save-excursion' and point is always at `point-min'. Its
37 ;; return value has to be an alist (POSITION MESSAGE) when
38 ;; POSITION refer to the buffer position of the error, as an
39 ;; integer, and MESSAGE is a string describing the error.
40
41 ;; - DESCRIPTION: Summary about the check, as a string.
42
43 ;; - CATEGORIES: Categories relative to the check, as a list of
44 ;; symbol. They are used for filtering when calling `org-lint'.
45 ;; Checkers not explicitly associated to a category are collected
46 ;; in the `default' one.
47
48 ;; - TRUST: The trust level one can have in the check. It is either
49 ;; `low' or `high', depending on the heuristics implemented and
50 ;; the nature of the check. This has an indicative value only and
51 ;; is displayed along reports.
52
53 ;; All checks have to be listed in `org-lint--checkers'.
24 ;; This library implements linting for Org syntax. The process is
25 ;; started by calling `org-lint' command, which see.
26
27 ;; New checkers are added by `org-lint-add-checker' function.
28 ;; Internally, all checks are listed in `org-lint--checkers'.
5429
5530 ;; Results are displayed in a special "*Org Lint*" buffer with
5631 ;; a dedicated major mode, derived from `tabulated-list-mode'.
57 ;;
5832 ;; In addition to the usual key-bindings inherited from it, "C-j" and
5933 ;; "TAB" display problematic line reported under point whereas "RET"
6034 ;; jumps to it. Also, "h" hides all reports similar to the current
6135 ;; one. Additionally, "i" removes them from subsequent reports.
6236
63 ;; Checks currently implemented are:
64
65 ;; - duplicate CUSTOM_ID properties
66 ;; - duplicate NAME values
67 ;; - duplicate targets
68 ;; - duplicate footnote definitions
69 ;; - orphaned affiliated keywords
70 ;; - obsolete affiliated keywords
71 ;; - missing language in source blocks
72 ;; - missing back-end in export blocks
73 ;; - invalid Babel call blocks
74 ;; - NAME values with a colon
75 ;; - deprecated export block syntax
76 ;; - deprecated Babel header properties
77 ;; - wrong header arguments in source blocks
78 ;; - misuse of CATEGORY keyword
79 ;; - "coderef" links with unknown destination
80 ;; - "custom-id" links with unknown destination
81 ;; - "fuzzy" links with unknown destination
82 ;; - "id" links with unknown destination
83 ;; - links to non-existent local files
84 ;; - SETUPFILE keywords with non-existent file parameter
85 ;; - INCLUDE keywords with wrong link parameter
86 ;; - obsolete markup in INCLUDE keyword
87 ;; - unknown items in OPTIONS keyword
88 ;; - spurious macro arguments or invalid macro templates
89 ;; - special properties in properties drawer
90 ;; - obsolete syntax for PROPERTIES drawers
91 ;; - Invalid EFFORT property value
92 ;; - missing definition for footnote references
93 ;; - missing reference for footnote definitions
94 ;; - non-footnote definitions in footnote section
95 ;; - probable invalid keywords
96 ;; - invalid blocks
97 ;; - misplaced planning info line
98 ;; - incomplete drawers
99 ;; - indented diary-sexps
100 ;; - obsolete QUOTE section
101 ;; - obsolete "file+application" link
102 ;; - spurious colons in tags
37 ;; Checks currently implemented report the following:
38
39 ;; - duplicates CUSTOM_ID properties,
40 ;; - duplicate NAME values,
41 ;; - duplicate targets,
42 ;; - duplicate footnote definitions,
43 ;; - orphaned affiliated keywords,
44 ;; - obsolete affiliated keywords,
45 ;; - deprecated export block syntax,
46 ;; - deprecated Babel header syntax,
47 ;; - missing language in source blocks,
48 ;; - missing back-end in export blocks,
49 ;; - invalid Babel call blocks,
50 ;; - NAME values with a colon,
51 ;; - wrong babel headers,
52 ;; - invalid value in babel headers,
53 ;; - misuse of CATEGORY keyword,
54 ;; - "coderef" links with unknown destination,
55 ;; - "custom-id" links with unknown destination,
56 ;; - "fuzzy" links with unknown destination,
57 ;; - "id" links with unknown destination,
58 ;; - links to non-existent local files,
59 ;; - SETUPFILE keywords with non-existent file parameter,
60 ;; - INCLUDE keywords with misleading link parameter,
61 ;; - obsolete markup in INCLUDE keyword,
62 ;; - unknown items in OPTIONS keyword,
63 ;; - spurious macro arguments or invalid macro templates,
64 ;; - special properties in properties drawers,
65 ;; - obsolete syntax for properties drawers,
66 ;; - invalid duration in EFFORT property,
67 ;; - missing definition for footnote references,
68 ;; - missing reference for footnote definitions,
69 ;; - non-footnote definitions in footnote section,
70 ;; - probable invalid keywords,
71 ;; - invalid blocks,
72 ;; - misplaced planning info line,
73 ;; - probable incomplete drawers,
74 ;; - probable indented diary-sexps,
75 ;; - obsolete QUOTE section,
76 ;; - obsolete "file+application" link,
77 ;; - obsolete escape syntax in links,
78 ;; - spurious colons in tags,
79 ;; - invalid bibliography file,
80 ;; - missing "print_bibliography" keyword,
81 ;; - invalid value for "cite_export" keyword,
82 ;; - incomplete citation object.
10383
10484
10585 ;;; Code:
10686
87 (require 'org-macs)
88 (org-assert-version)
89
10790 (require 'cl-lib)
10891 (require 'ob)
92 (require 'oc)
10993 (require 'ol)
11094 (require 'org-attach)
11195 (require 'org-macro)
96 (require 'org-fold)
11297 (require 'ox)
98 (require 'seq)
11399
114100
115 ;;; Checkers
101 ;;; Checkers structure
116102
117103 (cl-defstruct (org-lint-checker (:copier nil))
118 (name 'missing-checker-name)
119 (description "")
120 (categories '(default))
121 (trust 'high)) ; `low' or `high'
122
123 (defun org-lint-missing-checker-name (_)
124 (error
125 "`A checker has no `:name' property. Please verify `org-lint--checkers'"))
126
127 (defconst org-lint--checkers
128 (list
129 (make-org-lint-checker
130 :name 'duplicate-custom-id
131 :description "Report duplicates CUSTOM_ID properties"
132 :categories '(link))
133 (make-org-lint-checker
134 :name 'duplicate-name
135 :description "Report duplicate NAME values"
136 :categories '(babel link))
137 (make-org-lint-checker
138 :name 'duplicate-target
139 :description "Report duplicate targets"
140 :categories '(link))
141 (make-org-lint-checker
142 :name 'duplicate-footnote-definition
143 :description "Report duplicate footnote definitions"
144 :categories '(footnote))
145 (make-org-lint-checker
146 :name 'orphaned-affiliated-keywords
147 :description "Report orphaned affiliated keywords"
148 :trust 'low)
149 (make-org-lint-checker
150 :name 'obsolete-affiliated-keywords
151 :description "Report obsolete affiliated keywords"
152 :categories '(obsolete))
153 (make-org-lint-checker
154 :name 'deprecated-export-blocks
155 :description "Report deprecated export block syntax"
156 :categories '(obsolete export)
157 :trust 'low)
158 (make-org-lint-checker
159 :name 'deprecated-header-syntax
160 :description "Report deprecated Babel header syntax"
161 :categories '(obsolete babel)
162 :trust 'low)
163 (make-org-lint-checker
164 :name 'missing-language-in-src-block
165 :description "Report missing language in source blocks"
166 :categories '(babel))
167 (make-org-lint-checker
168 :name 'missing-backend-in-export-block
169 :description "Report missing back-end in export blocks"
170 :categories '(export))
171 (make-org-lint-checker
172 :name 'invalid-babel-call-block
173 :description "Report invalid Babel call blocks"
174 :categories '(babel))
175 (make-org-lint-checker
176 :name 'colon-in-name
177 :description "Report NAME values with a colon"
178 :categories '(babel))
179 (make-org-lint-checker
180 :name 'wrong-header-argument
181 :description "Report wrong babel headers"
182 :categories '(babel))
183 (make-org-lint-checker
184 :name 'wrong-header-value
185 :description "Report invalid value in babel headers"
186 :categories '(babel)
187 :trust 'low)
188 (make-org-lint-checker
189 :name 'deprecated-category-setup
190 :description "Report misuse of CATEGORY keyword"
191 :categories '(obsolete))
192 (make-org-lint-checker
193 :name 'invalid-coderef-link
194 :description "Report \"coderef\" links with unknown destination"
195 :categories '(link))
196 (make-org-lint-checker
197 :name 'invalid-custom-id-link
198 :description "Report \"custom-id\" links with unknown destination"
199 :categories '(link))
200 (make-org-lint-checker
201 :name 'invalid-fuzzy-link
202 :description "Report \"fuzzy\" links with unknown destination"
203 :categories '(link))
204 (make-org-lint-checker
205 :name 'invalid-id-link
206 :description "Report \"id\" links with unknown destination"
207 :categories '(link))
208 (make-org-lint-checker
209 :name 'link-to-local-file
210 :description "Report links to non-existent local files"
211 :categories '(link)
212 :trust 'low)
213 (make-org-lint-checker
214 :name 'non-existent-setupfile-parameter
215 :description "Report SETUPFILE keywords with non-existent file parameter"
216 :trust 'low)
217 (make-org-lint-checker
218 :name 'wrong-include-link-parameter
219 :description "Report INCLUDE keywords with misleading link parameter"
220 :categories '(export)
221 :trust 'low)
222 (make-org-lint-checker
223 :name 'obsolete-include-markup
224 :description "Report obsolete markup in INCLUDE keyword"
225 :categories '(obsolete export)
226 :trust 'low)
227 (make-org-lint-checker
228 :name 'unknown-options-item
229 :description "Report unknown items in OPTIONS keyword"
230 :categories '(export)
231 :trust 'low)
232 (make-org-lint-checker
233 :name 'invalid-macro-argument-and-template
234 :description "Report spurious macro arguments or invalid macro templates"
235 :categories '(export)
236 :trust 'low)
237 (make-org-lint-checker
238 :name 'special-property-in-properties-drawer
239 :description "Report special properties in properties drawers"
240 :categories '(properties))
241 (make-org-lint-checker
242 :name 'obsolete-properties-drawer
243 :description "Report obsolete syntax for properties drawers"
244 :categories '(obsolete properties))
245 (make-org-lint-checker
246 :name 'invalid-effort-property
247 :description "Report invalid duration in EFFORT property"
248 :categories '(properties))
249 (make-org-lint-checker
250 :name 'undefined-footnote-reference
251 :description "Report missing definition for footnote references"
252 :categories '(footnote))
253 (make-org-lint-checker
254 :name 'unreferenced-footnote-definition
255 :description "Report missing reference for footnote definitions"
256 :categories '(footnote))
257 (make-org-lint-checker
258 :name 'extraneous-element-in-footnote-section
259 :description "Report non-footnote definitions in footnote section"
260 :categories '(footnote))
261 (make-org-lint-checker
262 :name 'invalid-keyword-syntax
263 :description "Report probable invalid keywords"
264 :trust 'low)
265 (make-org-lint-checker
266 :name 'invalid-block
267 :description "Report invalid blocks"
268 :trust 'low)
269 (make-org-lint-checker
270 :name 'misplaced-planning-info
271 :description "Report misplaced planning info line"
272 :trust 'low)
273 (make-org-lint-checker
274 :name 'incomplete-drawer
275 :description "Report probable incomplete drawers"
276 :trust 'low)
277 (make-org-lint-checker
278 :name 'indented-diary-sexp
279 :description "Report probable indented diary-sexps"
280 :trust 'low)
281 (make-org-lint-checker
282 :name 'quote-section
283 :description "Report obsolete QUOTE section"
284 :categories '(obsolete)
285 :trust 'low)
286 (make-org-lint-checker
287 :name 'file-application
288 :description "Report obsolete \"file+application\" link"
289 :categories '(link obsolete))
290 (make-org-lint-checker
291 :name 'percent-encoding-link-escape
292 :description "Report obsolete escape syntax in links"
293 :categories '(link obsolete)
294 :trust 'low)
295 (make-org-lint-checker
296 :name 'spurious-colons
297 :description "Report spurious colons in tags"
298 :categories '(tags)))
299 "List of all available checkers.")
104 name summary function trust categories)
105
106 (defvar org-lint--checkers nil
107 "List of all available checkers.
108 This list is populated by `org-lint-add-checker' function.")
109
110 ;;;###autoload
111 (defun org-lint-add-checker (name summary fun &rest props)
112 "Add a new checker for linter.
113
114 NAME is a unique check identifier, as a non-nil symbol. SUMMARY
115 is a short description of the check, as a string.
116
117 The check is done calling the function FUN with one mandatory
118 argument, the parse tree describing the current Org buffer. Such
119 function calls are wrapped within a `save-excursion' and point is
120 always at `point-min'. Its return value has to be an
121 alist (POSITION MESSAGE) where POSITION refer to the buffer
122 position of the error, as an integer, and MESSAGE is a one-line
123 string describing the error.
124
125 Optional argument PROPS provides additional information about the
126 checker. Currently, two properties are supported:
127
128 `:categories'
129
130 Categories relative to the check, as a list of symbol. They
131 are used for filtering when calling `org-lint'. Checkers
132 not explicitly associated to a category are collected in the
133 `default' one.
134
135 `:trust'
136
137 The trust level one can have in the check. It is either
138 `low' or `high', depending on the heuristics implemented and
139 the nature of the check. This has an indicative value only
140 and is displayed along reports."
141 (declare (indent 1))
142 ;; Sanity checks.
143 (pcase name
144 (`nil (error "Name field is mandatory for checkers"))
145 ((pred symbolp) nil)
146 (_ (error "Invalid type for name field")))
147 (unless (functionp fun)
148 (error "Checker field is expected to be a valid function"))
149 ;; Install checker in `org-lint--checkers'; uniquify by name.
150 (setq org-lint--checkers
151 (cons (apply #'make-org-lint-checker
152 :name name
153 :summary summary
154 :function fun
155 props)
156 (seq-remove (lambda (c) (eq name (org-lint-checker-name c)))
157 org-lint--checkers))))
158
159
160 ;;; Reports UI
161
162 (defvar org-lint--report-mode-map
163 (let ((map (make-sparse-keymap)))
164 (set-keymap-parent map tabulated-list-mode-map)
165 (define-key map (kbd "RET") 'org-lint--jump-to-source)
166 (define-key map (kbd "TAB") 'org-lint--show-source)
167 (define-key map (kbd "C-j") 'org-lint--show-source)
168 (define-key map (kbd "h") 'org-lint--hide-checker)
169 (define-key map (kbd "i") 'org-lint--ignore-checker)
170 map)
171 "Local keymap for `org-lint--report-mode' buffers.")
172
173 (define-derived-mode org-lint--report-mode tabulated-list-mode "OrgLint"
174 "Major mode used to display reports emitted during linting.
175 \\{org-lint--report-mode-map}"
176 (setf tabulated-list-format
177 `[("Line" 6
178 (lambda (a b)
179 (< (string-to-number (aref (cadr a) 0))
180 (string-to-number (aref (cadr b) 0))))
181 :right-align t)
182 ("Trust" 5 t)
183 ("Warning" 0 t)])
184 (tabulated-list-init-header))
185
186 (defun org-lint--generate-reports (buffer checkers)
187 "Generate linting report for BUFFER.
188
189 CHECKERS is the list of checkers used.
190
191 Return an alist (ID [LINE TRUST DESCRIPTION CHECKER]), suitable
192 for `tabulated-list-printer'."
193 (with-current-buffer buffer
194 (save-excursion
195 (goto-char (point-min))
196 (let ((ast (org-element-parse-buffer))
197 (id 0)
198 (last-line 1)
199 (last-pos 1))
200 ;; Insert unique ID for each report. Replace buffer positions
201 ;; with line numbers.
202 (mapcar
203 (lambda (report)
204 (list
205 (cl-incf id)
206 (apply #'vector
207 (cons
208 (progn
209 (goto-char (car report))
210 (beginning-of-line)
211 (prog1 (number-to-string
212 (cl-incf last-line
213 (count-lines last-pos (point))))
214 (setf last-pos (point))))
215 (cdr report)))))
216 ;; Insert trust level in generated reports. Also sort them
217 ;; by buffer position in order to optimize lines computation.
218 (sort (cl-mapcan
219 (lambda (c)
220 (let ((trust (symbol-name (org-lint-checker-trust c))))
221 (mapcar
222 (lambda (report)
223 (list (car report) trust (nth 1 report) c))
224 (save-excursion
225 (funcall (org-lint-checker-function c)
226 ast)))))
227 checkers)
228 #'car-less-than-car))))))
229
230 (defvar-local org-lint--source-buffer nil
231 "Source buffer associated to current report buffer.")
232
233 (defvar-local org-lint--local-checkers nil
234 "List of checkers used to build current report.")
235
236 (defun org-lint--refresh-reports ()
237 (setq tabulated-list-entries
238 (org-lint--generate-reports org-lint--source-buffer
239 org-lint--local-checkers))
240 (tabulated-list-print))
241
242 (defun org-lint--current-line ()
243 "Return current report line, as a number."
244 (string-to-number (aref (tabulated-list-get-entry) 0)))
245
246 (defun org-lint--current-checker (&optional entry)
247 "Return current report checker.
248 When optional argument ENTRY is non-nil, use this entry instead
249 of current one."
250 (aref (if entry (nth 1 entry) (tabulated-list-get-entry)) 3))
251
252 (defun org-lint--display-reports (source checkers)
253 "Display linting reports for buffer SOURCE.
254 CHECKERS is the list of checkers used."
255 (let ((buffer (get-buffer-create "*Org Lint*")))
256 (with-current-buffer buffer
257 (org-lint--report-mode)
258 (setf org-lint--source-buffer source)
259 (setf org-lint--local-checkers checkers)
260 (org-lint--refresh-reports)
261 (add-hook 'tabulated-list-revert-hook #'org-lint--refresh-reports nil t))
262 (pop-to-buffer buffer)))
263
264 (defun org-lint--jump-to-source ()
265 "Move to source line that generated the report at point."
266 (interactive)
267 (let ((l (org-lint--current-line)))
268 (switch-to-buffer-other-window org-lint--source-buffer)
269 (org-goto-line l)
270 (org-fold-show-set-visibility 'local)
271 (recenter)))
272
273 (defun org-lint--show-source ()
274 "Show source line that generated the report at point."
275 (interactive)
276 (let ((buffer (current-buffer)))
277 (org-lint--jump-to-source)
278 (switch-to-buffer-other-window buffer)))
279
280 (defun org-lint--hide-checker ()
281 "Hide all reports from checker that generated the report at point."
282 (interactive)
283 (let ((c (org-lint--current-checker)))
284 (setf tabulated-list-entries
285 (cl-remove-if (lambda (e) (equal c (org-lint--current-checker e)))
286 tabulated-list-entries))
287 (tabulated-list-print)))
288
289 (defun org-lint--ignore-checker ()
290 "Ignore all reports from checker that generated the report at point.
291 Checker will also be ignored in all subsequent reports."
292 (interactive)
293 (setf org-lint--local-checkers
294 (remove (org-lint--current-checker) org-lint--local-checkers))
295 (org-lint--hide-checker))
296
297
298 ;;; Main function
299
300 ;;;###autoload
301 (defun org-lint (&optional arg)
302 "Check current Org buffer for syntax mistakes.
303
304 By default, run all checkers. With a `\\[universal-argument]' prefix ARG, \
305 select one
306 category of checkers only. With a `\\[universal-argument] \
307 \\[universal-argument]' prefix, run one precise
308 checker by its name.
309
310 ARG can also be a list of checker names, as symbols, to run."
311 (interactive "P")
312 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org buffer"))
313 (when (called-interactively-p 'any)
314 (message "Org linting process starting..."))
315 (let ((checkers
316 (pcase arg
317 (`nil org-lint--checkers)
318 (`(4)
319 (let ((category
320 (completing-read
321 "Checker category: "
322 (mapcar #'org-lint-checker-categories org-lint--checkers)
323 nil t)))
324 (cl-remove-if-not
325 (lambda (c)
326 (assoc-string category (org-lint-checker-categories c)))
327 org-lint--checkers)))
328 (`(16)
329 (list
330 (let ((name (completing-read
331 "Checker name: "
332 (mapcar #'org-lint-checker-name org-lint--checkers)
333 nil t)))
334 (catch 'exit
335 (dolist (c org-lint--checkers)
336 (when (string= (org-lint-checker-name c) name)
337 (throw 'exit c)))))))
338 ((pred consp)
339 (cl-remove-if-not (lambda (c) (memq (org-lint-checker-name c) arg))
340 org-lint--checkers))
341 (_ (user-error "Invalid argument `%S' for `org-lint'" arg)))))
342 (if (not (called-interactively-p 'any))
343 (org-lint--generate-reports (current-buffer) checkers)
344 (org-lint--display-reports (current-buffer) checkers)
345 (message "Org linting process completed"))))
346
347
348 ;;; Checker functions
300349
301350 (defun org-lint--collect-duplicates
302351 (ast type extract-key extract-position build-message)
333382 ast
334383 'node-property
335384 (lambda (property)
336 (and (eq (compare-strings "CUSTOM_ID" nil nil
337 (org-element-property :key property) nil nil
338 t)
339 t)
385 (and (org-string-equal-ignore-case
386 "CUSTOM_ID" (org-element-property :key property))
340387 (org-element-property :value property)))
341388 (lambda (property _) (org-element-property :begin property))
342389 (lambda (key) (format "Duplicate CUSTOM_ID property \"%s\"" key))))
602649 (org-element-map ast 'keyword
603650 (lambda (k)
604651 (when (equal (org-element-property :key k) "INCLUDE")
605 (let* ((value (org-element-property :value k))
606 (path
607 (and (string-match "^\\(\".+\"\\|\\S-+\\)[ \t]*" value)
608 (save-match-data
609 (org-strip-quotes (match-string 1 value))))))
610 (if (not path)
611 (list (org-element-property :post-affiliated k)
612 "Missing location argument in INCLUDE keyword")
613 (let* ((file (org-string-nw-p
614 (if (string-match "::\\(.*\\)\\'" path)
615 (substring path 0 (match-beginning 0))
616 path)))
617 (search (and (not (equal file path))
618 (org-string-nw-p (match-string 1 path)))))
619 (if (and file
620 (not (file-remote-p file))
621 (not (file-exists-p file)))
622 (list (org-element-property :post-affiliated k)
623 "Non-existent file argument in INCLUDE keyword")
624 (let* ((visiting (if file (find-buffer-visiting file)
625 (current-buffer)))
626 (buffer (or visiting (find-file-noselect file)))
627 (org-link-search-must-match-exact-headline t))
628 (unwind-protect
629 (with-current-buffer buffer
630 (when (and search
631 (not (ignore-errors
632 (org-link-search search nil t))))
633 (list (org-element-property :post-affiliated k)
634 (format
635 "Invalid search part \"%s\" in INCLUDE keyword"
636 search))))
637 (unless visiting (kill-buffer buffer))))))))))))
652 (let* ((value (org-element-property :value k))
653 (path
654 (and (string-match "^\\(\".+?\"\\|\\S-+\\)[ \t]*" value)
655 (save-match-data
656 (org-strip-quotes (match-string 1 value))))))
657 (if (not path)
658 (list (org-element-property :post-affiliated k)
659 "Missing location argument in INCLUDE keyword")
660 (let* ((file (org-string-nw-p
661 (if (string-match "::\\(.*\\)\\'" path)
662 (substring path 0 (match-beginning 0))
663 path)))
664 (search (and (not (equal file path))
665 (org-string-nw-p (match-string 1 path)))))
666 (unless (org-url-p file)
667 (if (and file
668 (not (file-remote-p file))
669 (not (file-exists-p file)))
670 (list (org-element-property :post-affiliated k)
671 "Non-existent file argument in INCLUDE keyword")
672 (let* ((visiting (if file (find-buffer-visiting file)
673 (current-buffer)))
674 (buffer (or visiting (find-file-noselect file)))
675 (org-link-search-must-match-exact-headline t))
676 (unwind-protect
677 (with-current-buffer buffer
678 (when (and search
679 (not (ignore-errors
680 (org-link-search search nil t))))
681 (list (org-element-property :post-affiliated k)
682 (format
683 "Invalid search part \"%s\" in INCLUDE keyword"
684 search))))
685 (unless visiting (kill-buffer buffer)))))))))))))
638686
639687 (defun org-lint-obsolete-include-markup (ast)
640688 (let ((regexp (format "\\`\\(?:\".+\"\\|\\S-+\\)[ \t]+%s"
783831 reports))
784832
785833 (defun org-lint-undefined-footnote-reference (ast)
786 (let ((definitions (org-element-map ast 'footnote-definition
787 (lambda (f) (org-element-property :label f)))))
834 (let ((definitions
835 (org-element-map ast '(footnote-definition footnote-reference)
836 (lambda (f)
837 (and (or (eq 'footnote-definition (org-element-type f))
838 (eq 'inline (org-element-property :type f)))
839 (org-element-property :label f))))))
788840 (org-element-map ast 'footnote-reference
789841 (lambda (f)
790842 (let ((label (org-element-property :label f)))
10131065 (`keyword
10141066 (when (string= (org-element-property :key datum) "PROPERTY")
10151067 (let ((value (org-element-property :value datum)))
1016 (when (string-match "\\`header-args\\(?::\\(\\S-+\\)\\)?\\+? *"
1017 value)
1068 (when (or (string-match "\\`header-args\\(?::\\(\\S-+\\)\\)?\\+ *"
1069 value)
1070 (string-match "\\`header-args\\(?::\\(\\S-+\\)\\)? *"
1071 value))
10181072 (funcall verify
10191073 datum
10201074 (match-string 1 value)
10231077 (`node-property
10241078 (let ((key (org-element-property :key datum)))
10251079 (when (let ((case-fold-search t))
1026 (string-match "\\`HEADER-ARGS\\(?::\\(\\S-+\\)\\)?\\+?"
1027 key))
1080 (or (string-match "\\`HEADER-ARGS\\(?::\\(\\S-+\\)\\)?\\+"
1081 key)
1082 (string-match "\\`HEADER-ARGS\\(?::\\(\\S-+\\)\\)?"
1083 key)))
10281084 (funcall verify
10291085 datum
10301086 (match-string 1 key)
11201176 (list (org-element-property :begin h)
11211177 "Tags contain a spurious colon")))))
11221178
1179 (defun org-lint-non-existent-bibliography (ast)
1180 (org-element-map ast 'keyword
1181 (lambda (k)
1182 (when (equal "BIBLIOGRAPHY" (org-element-property :key k))
1183 (let ((file (org-strip-quotes (org-element-property :value k))))
1184 (and (not (file-remote-p file))
1185 (not (file-exists-p file))
1186 (list (org-element-property :begin k)
1187 (format "Non-existent bibliography %S" file))))))))
1188
1189 (defun org-lint-missing-print-bibliography (ast)
1190 (and (org-element-map ast 'citation #'identity nil t)
1191 (not (org-element-map ast 'keyword
1192 (lambda (k)
1193 (equal "PRINT_BIBLIOGRAPHY" (org-element-property :key k)))
1194 nil t))
1195 (list
1196 (list (point-max) "Possibly missing \"PRINT_BIBLIOGRAPHY\" keyword"))))
1197
1198 (defun org-lint-invalid-cite-export-declaration (ast)
1199 (org-element-map ast 'keyword
1200 (lambda (k)
1201 (when (equal "CITE_EXPORT" (org-element-property :key k))
1202 (let ((value (org-element-property :value k))
1203 (source (org-element-property :begin k)))
1204 (if (equal value "")
1205 (list source "Missing export processor name")
1206 (condition-case _
1207 (pcase (org-cite-read-processor-declaration value)
1208 (`(,(and (pred symbolp) name)
1209 ,(pred string-or-null-p)
1210 ,(pred string-or-null-p))
1211 (unless (org-cite-get-processor name)
1212 (list source "Unknown cite export processor %S" name)))
1213 (_
1214 (list source "Invalid cite export processor declaration")))
1215 (error
1216 (list source "Invalid cite export processor declaration")))))))))
1217
1218 (defun org-lint-incomplete-citation (ast)
1219 (org-element-map ast 'plain-text
1220 (lambda (text)
1221 (and (string-match-p org-element-citation-prefix-re text)
1222 ;; XXX: The code below signals the error at the beginning
1223 ;; of the paragraph containing the faulty object. It is
1224 ;; not very accurate but may be enough for now.
1225 (list (org-element-property :contents-begin
1226 (org-element-property :parent text))
1227 "Possibly incomplete citation markup")))))
11231228
11241229
1125 ;;; Reports UI
1126
1127 (defvar org-lint--report-mode-map
1128 (let ((map (make-sparse-keymap)))
1129 (set-keymap-parent map tabulated-list-mode-map)
1130 (define-key map (kbd "RET") 'org-lint--jump-to-source)
1131 (define-key map (kbd "TAB") 'org-lint--show-source)
1132 (define-key map (kbd "C-j") 'org-lint--show-source)
1133 (define-key map (kbd "h") 'org-lint--hide-checker)
1134 (define-key map (kbd "i") 'org-lint--ignore-checker)
1135 map)
1136 "Local keymap for `org-lint--report-mode' buffers.")
1137
1138 (define-derived-mode org-lint--report-mode tabulated-list-mode "OrgLint"
1139 "Major mode used to display reports emitted during linting.
1140 \\{org-lint--report-mode-map}"
1141 (setf tabulated-list-format
1142 `[("Line" 6
1143 (lambda (a b)
1144 (< (string-to-number (aref (cadr a) 0))
1145 (string-to-number (aref (cadr b) 0))))
1146 :right-align t)
1147 ("Trust" 5 t)
1148 ("Warning" 0 t)])
1149 (tabulated-list-init-header))
1150
1151 (defun org-lint--generate-reports (buffer checkers)
1152 "Generate linting report for BUFFER.
1153
1154 CHECKERS is the list of checkers used.
1155
1156 Return an alist (ID [LINE TRUST DESCRIPTION CHECKER]), suitable
1157 for `tabulated-list-printer'."
1158 (with-current-buffer buffer
1159 (save-excursion
1160 (goto-char (point-min))
1161 (let ((ast (org-element-parse-buffer))
1162 (id 0)
1163 (last-line 1)
1164 (last-pos 1))
1165 ;; Insert unique ID for each report. Replace buffer positions
1166 ;; with line numbers.
1167 (mapcar
1168 (lambda (report)
1169 (list
1170 (cl-incf id)
1171 (apply #'vector
1172 (cons
1173 (progn
1174 (goto-char (car report))
1175 (beginning-of-line)
1176 (prog1 (number-to-string
1177 (cl-incf last-line
1178 (count-lines last-pos (point))))
1179 (setf last-pos (point))))
1180 (cdr report)))))
1181 ;; Insert trust level in generated reports. Also sort them
1182 ;; by buffer position in order to optimize lines computation.
1183 (sort (cl-mapcan
1184 (lambda (c)
1185 (let ((trust (symbol-name (org-lint-checker-trust c))))
1186 (mapcar
1187 (lambda (report)
1188 (list (car report) trust (nth 1 report) c))
1189 (save-excursion
1190 (funcall
1191 (intern (format "org-lint-%s"
1192 (org-lint-checker-name c)))
1193 ast)))))
1194 checkers)
1195 #'car-less-than-car))))))
1196
1197 (defvar-local org-lint--source-buffer nil
1198 "Source buffer associated to current report buffer.")
1199
1200 (defvar-local org-lint--local-checkers nil
1201 "List of checkers used to build current report.")
1202
1203 (defun org-lint--refresh-reports ()
1204 (setq tabulated-list-entries
1205 (org-lint--generate-reports org-lint--source-buffer
1206 org-lint--local-checkers))
1207 (tabulated-list-print))
1208
1209 (defun org-lint--current-line ()
1210 "Return current report line, as a number."
1211 (string-to-number (aref (tabulated-list-get-entry) 0)))
1212
1213 (defun org-lint--current-checker (&optional entry)
1214 "Return current report checker.
1215 When optional argument ENTRY is non-nil, use this entry instead
1216 of current one."
1217 (aref (if entry (nth 1 entry) (tabulated-list-get-entry)) 3))
1218
1219 (defun org-lint--display-reports (source checkers)
1220 "Display linting reports for buffer SOURCE.
1221 CHECKERS is the list of checkers used."
1222 (let ((buffer (get-buffer-create "*Org Lint*")))
1223 (with-current-buffer buffer
1224 (org-lint--report-mode)
1225 (setf org-lint--source-buffer source)
1226 (setf org-lint--local-checkers checkers)
1227 (org-lint--refresh-reports)
1228 (add-hook 'tabulated-list-revert-hook #'org-lint--refresh-reports nil t))
1229 (pop-to-buffer buffer)))
1230
1231 (defun org-lint--jump-to-source ()
1232 "Move to source line that generated the report at point."
1233 (interactive)
1234 (let ((l (org-lint--current-line)))
1235 (switch-to-buffer-other-window org-lint--source-buffer)
1236 (org-goto-line l)
1237 (org-show-set-visibility 'local)
1238 (recenter)))
1239
1240 (defun org-lint--show-source ()
1241 "Show source line that generated the report at point."
1242 (interactive)
1243 (let ((buffer (current-buffer)))
1244 (org-lint--jump-to-source)
1245 (switch-to-buffer-other-window buffer)))
1246
1247 (defun org-lint--hide-checker ()
1248 "Hide all reports from checker that generated the report at point."
1249 (interactive)
1250 (let ((c (org-lint--current-checker)))
1251 (setf tabulated-list-entries
1252 (cl-remove-if (lambda (e) (equal c (org-lint--current-checker e)))
1253 tabulated-list-entries))
1254 (tabulated-list-print)))
1255
1256 (defun org-lint--ignore-checker ()
1257 "Ignore all reports from checker that generated the report at point.
1258 Checker will also be ignored in all subsequent reports."
1259 (interactive)
1260 (setf org-lint--local-checkers
1261 (remove (org-lint--current-checker) org-lint--local-checkers))
1262 (org-lint--hide-checker))
1263
1264
1265 ;;; Public function
1266
1267 ;;;###autoload
1268 (defun org-lint (&optional arg)
1269 "Check current Org buffer for syntax mistakes.
1270
1271 By default, run all checkers. With a `\\[universal-argument]' prefix ARG, \
1272 select one
1273 category of checkers only. With a `\\[universal-argument] \
1274 \\[universal-argument]' prefix, run one precise
1275 checker by its name.
1276
1277 ARG can also be a list of checker names, as symbols, to run."
1278 (interactive "P")
1279 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org buffer"))
1280 (when (called-interactively-p 'any)
1281 (message "Org linting process starting..."))
1282 (let ((checkers
1283 (pcase arg
1284 (`nil org-lint--checkers)
1285 (`(4)
1286 (let ((category
1287 (completing-read
1288 "Checker category: "
1289 (mapcar #'org-lint-checker-categories org-lint--checkers)
1290 nil t)))
1291 (cl-remove-if-not
1292 (lambda (c)
1293 (assoc-string (org-lint-checker-categories c) category))
1294 org-lint--checkers)))
1295 (`(16)
1296 (list
1297 (let ((name (completing-read
1298 "Checker name: "
1299 (mapcar #'org-lint-checker-name org-lint--checkers)
1300 nil t)))
1301 (catch 'exit
1302 (dolist (c org-lint--checkers)
1303 (when (string= (org-lint-checker-name c) name)
1304 (throw 'exit c)))))))
1305 ((pred consp)
1306 (cl-remove-if-not (lambda (c) (memq (org-lint-checker-name c) arg))
1307 org-lint--checkers))
1308 (_ (user-error "Invalid argument `%S' for `org-lint'" arg)))))
1309 (if (not (called-interactively-p 'any))
1310 (org-lint--generate-reports (current-buffer) checkers)
1311 (org-lint--display-reports (current-buffer) checkers)
1312 (message "Org linting process completed"))))
1230 ;;; Checkers declaration
1231
1232 (org-lint-add-checker 'duplicate-custom-id
1233 "Report duplicates CUSTOM_ID properties"
1234 #'org-lint-duplicate-custom-id
1235 :categories '(link))
1236
1237 (org-lint-add-checker 'duplicate-name
1238 "Report duplicate NAME values"
1239 #'org-lint-duplicate-name
1240 :categories '(babel 'link))
1241
1242 (org-lint-add-checker 'duplicate-target
1243 "Report duplicate targets"
1244 #'org-lint-duplicate-target
1245 :categories '(link))
1246
1247 (org-lint-add-checker 'duplicate-footnote-definition
1248 "Report duplicate footnote definitions"
1249 #'org-lint-duplicate-footnote-definition
1250 :categories '(footnote))
1251
1252 (org-lint-add-checker 'orphaned-affiliated-keywords
1253 "Report orphaned affiliated keywords"
1254 #'org-lint-orphaned-affiliated-keywords
1255 :trust 'low)
1256
1257 (org-lint-add-checker 'obsolete-affiliated-keywords
1258 "Report obsolete affiliated keywords"
1259 #'org-lint-obsolete-affiliated-keywords
1260 :categories '(obsolete))
1261
1262 (org-lint-add-checker 'deprecated-export-blocks
1263 "Report deprecated export block syntax"
1264 #'org-lint-deprecated-export-blocks
1265 :trust 'low :categories '(obsolete export))
1266
1267 (org-lint-add-checker 'deprecated-header-syntax
1268 "Report deprecated Babel header syntax"
1269 #'org-lint-deprecated-header-syntax
1270 :trust 'low :categories '(obsolete babel))
1271
1272 (org-lint-add-checker 'missing-language-in-src-block
1273 "Report missing language in source blocks"
1274 #'org-lint-missing-language-in-src-block
1275 :categories '(babel))
1276
1277 (org-lint-add-checker 'missing-backend-in-export-block
1278 "Report missing back-end in export blocks"
1279 #'org-lint-missing-backend-in-export-block
1280 :categories '(export))
1281
1282 (org-lint-add-checker 'invalid-babel-call-block
1283 "Report invalid Babel call blocks"
1284 #'org-lint-invalid-babel-call-block
1285 :categories '(babel))
1286
1287 (org-lint-add-checker 'colon-in-name
1288 "Report NAME values with a colon"
1289 #'org-lint-colon-in-name
1290 :categories '(babel))
1291
1292 (org-lint-add-checker 'wrong-header-argument
1293 "Report wrong babel headers"
1294 #'org-lint-wrong-header-argument
1295 :categories '(babel))
1296
1297 (org-lint-add-checker 'wrong-header-value
1298 "Report invalid value in babel headers"
1299 #'org-lint-wrong-header-value
1300 :categories '(babel) :trust 'low)
1301
1302 (org-lint-add-checker 'deprecated-category-setup
1303 "Report misuse of CATEGORY keyword"
1304 #'org-lint-deprecated-category-setup
1305 :categories '(obsolete))
1306
1307 (org-lint-add-checker 'invalid-coderef-link
1308 "Report \"coderef\" links with unknown destination"
1309 #'org-lint-invalid-coderef-link
1310 :categories '(link))
1311
1312 (org-lint-add-checker 'invalid-custom-id-link
1313 "Report \"custom-id\" links with unknown destination"
1314 #'org-lint-invalid-custom-id-link
1315 :categories '(link))
1316
1317 (org-lint-add-checker 'invalid-fuzzy-link
1318 "Report \"fuzzy\" links with unknown destination"
1319 #'org-lint-invalid-fuzzy-link
1320 :categories '(link))
1321
1322 (org-lint-add-checker 'invalid-id-link
1323 "Report \"id\" links with unknown destination"
1324 #'org-lint-invalid-id-link
1325 :categories '(link))
1326
1327 (org-lint-add-checker 'link-to-local-file
1328 "Report links to non-existent local files"
1329 #'org-lint-link-to-local-file
1330 :categories '(link) :trust 'low)
1331
1332 (org-lint-add-checker 'non-existent-setupfile-parameter
1333 "Report SETUPFILE keywords with non-existent file parameter"
1334 #'org-lint-non-existent-setupfile-parameter
1335 :trust 'low)
1336
1337 (org-lint-add-checker 'wrong-include-link-parameter
1338 "Report INCLUDE keywords with misleading link parameter"
1339 #'org-lint-wrong-include-link-parameter
1340 :categories '(export) :trust 'low)
1341
1342 (org-lint-add-checker 'obsolete-include-markup
1343 "Report obsolete markup in INCLUDE keyword"
1344 #'org-lint-obsolete-include-markup
1345 :categories '(obsolete export) :trust 'low)
1346
1347 (org-lint-add-checker 'unknown-options-item
1348 "Report unknown items in OPTIONS keyword"
1349 #'org-lint-unknown-options-item
1350 :categories '(export) :trust 'low)
1351
1352 (org-lint-add-checker 'invalid-macro-argument-and-template
1353 "Report spurious macro arguments or invalid macro templates"
1354 #'org-lint-invalid-macro-argument-and-template
1355 :categories '(export) :trust 'low)
1356
1357 (org-lint-add-checker 'special-property-in-properties-drawer
1358 "Report special properties in properties drawers"
1359 #'org-lint-special-property-in-properties-drawer
1360 :categories '(properties))
1361
1362 (org-lint-add-checker 'obsolete-properties-drawer
1363 "Report obsolete syntax for properties drawers"
1364 #'org-lint-obsolete-properties-drawer
1365 :categories '(obsolete properties))
1366
1367 (org-lint-add-checker 'invalid-effort-property
1368 "Report invalid duration in EFFORT property"
1369 #'org-lint-invalid-effort-property
1370 :categories '(properties))
1371
1372 (org-lint-add-checker 'undefined-footnote-reference
1373 "Report missing definition for footnote references"
1374 #'org-lint-undefined-footnote-reference
1375 :categories '(footnote))
1376
1377 (org-lint-add-checker 'unreferenced-footnote-definition
1378 "Report missing reference for footnote definitions"
1379 #'org-lint-unreferenced-footnote-definition
1380 :categories '(footnote))
1381
1382 (org-lint-add-checker 'extraneous-element-in-footnote-section
1383 "Report non-footnote definitions in footnote section"
1384 #'org-lint-extraneous-element-in-footnote-section
1385 :categories '(footnote))
1386
1387 (org-lint-add-checker 'invalid-keyword-syntax
1388 "Report probable invalid keywords"
1389 #'org-lint-invalid-keyword-syntax
1390 :trust 'low)
1391
1392 (org-lint-add-checker 'invalid-block
1393 "Report invalid blocks"
1394 #'org-lint-invalid-block
1395 :trust 'low)
1396
1397 (org-lint-add-checker 'misplaced-planning-info
1398 "Report misplaced planning info line"
1399 #'org-lint-misplaced-planning-info
1400 :trust 'low)
1401
1402 (org-lint-add-checker 'incomplete-drawer
1403 "Report probable incomplete drawers"
1404 #'org-lint-incomplete-drawer
1405 :trust 'low)
1406
1407 (org-lint-add-checker 'indented-diary-sexp
1408 "Report probable indented diary-sexps"
1409 #'org-lint-indented-diary-sexp
1410 :trust 'low)
1411
1412 (org-lint-add-checker 'quote-section
1413 "Report obsolete QUOTE section"
1414 #'org-lint-quote-section
1415 :categories '(obsolete) :trust 'low)
1416
1417 (org-lint-add-checker 'file-application
1418 "Report obsolete \"file+application\" link"
1419 #'org-lint-file-application
1420 :categories '(link obsolete))
1421
1422 (org-lint-add-checker 'percent-encoding-link-escape
1423 "Report obsolete escape syntax in links"
1424 #'org-lint-percent-encoding-link-escape
1425 :categories '(link obsolete) :trust 'low)
1426
1427 (org-lint-add-checker 'spurious-colons
1428 "Report spurious colons in tags"
1429 #'org-lint-spurious-colons
1430 :categories '(tags))
1431
1432 (org-lint-add-checker 'non-existent-bibliography
1433 "Report invalid bibliography file"
1434 #'org-lint-non-existent-bibliography
1435 :categories '(cite))
1436
1437 (org-lint-add-checker 'missing-print-bibliography
1438 "Report missing \"print_bibliography\" keyword"
1439 #'org-lint-missing-print-bibliography
1440 :categories '(cite))
1441
1442 (org-lint-add-checker 'invalid-cite-export-declaration
1443 "Report invalid value for \"cite_export\" keyword"
1444 #'org-lint-invalid-cite-export-declaration
1445 :categories '(cite))
1446
1447 (org-lint-add-checker 'incomplete-citation
1448 "Report incomplete citation object"
1449 #'org-lint-incomplete-citation
1450 :categories '(cite) :trust 'low)
13131451
13141452 (provide 'org-lint)
13151453
00 ;;; org-list.el --- Plain lists for Org -*- lexical-binding: t; -*-
11 ;;
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Bastien Guerry <bzg@gnu.org>
66 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88 ;;
99 ;; This file is part of GNU Emacs.
1010 ;;
7575
7676 ;;; Code:
7777
78 (require 'org-macs)
79 (org-assert-version)
80
7881 (require 'cl-lib)
7982 (require 'org-macs)
8083 (require 'org-compat)
84 (require 'org-fold-core)
85 (require 'org-footnote)
8186
8287 (defvar org-M-RET-may-split-line)
8388 (defvar org-adapt-indentation)
102107 (declare-function org-back-to-heading "org" (&optional invisible-ok))
103108 (declare-function org-before-first-heading-p "org" ())
104109 (declare-function org-current-level "org" ())
105 (declare-function org-element-at-point "org-element" ())
110 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
106111 (declare-function org-element-context "org-element" (&optional element))
107112 (declare-function org-element-interpret-data "org-element" (data))
108113 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
132137 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
133138 (declare-function org-level-increment "org" ())
134139 (declare-function org-mode "org" ())
135 (declare-function org-narrow-to-subtree "org" ())
140 (declare-function org-narrow-to-subtree "org" (&optional element))
136141 (declare-function org-outline-level "org" ())
137142 (declare-function org-previous-line-empty-p "org" ())
138143 (declare-function org-reduced-level "org" (L))
139144 (declare-function org-set-tags "org" (tags))
140 (declare-function org-show-subtree "org" ())
145 (declare-function org-fold-show-subtree "org-fold" ())
146 (declare-function org-fold-region "org-fold" (from to flag &optional spec))
141147 (declare-function org-sort-remove-invisible "org" (S))
142148 (declare-function org-time-string-to-seconds "org" (s))
143149 (declare-function org-timer-hms-to-secs "org-timer" (hms))
232238 :type '(choice (const :tag "dot like in \"2.\"" ?.)
233239 (const :tag "paren like in \"2)\"" ?\))
234240 (const :tag "both" t))
235 :set (lambda (var val) (set var val)
241 :set (lambda (var val) (set-default-toplevel-value var val)
236242 (when (featurep 'org-element) (org-element-update-syntax))))
237243
238244 (defcustom org-list-allow-alphabetical nil
250256 :group 'org-plain-lists
251257 :version "24.1"
252258 :type 'boolean
253 :set (lambda (var val) (set var val)
259 :set (lambda (var val) (set-default-toplevel-value var val)
254260 (when (featurep 'org-element) (org-element-update-syntax))))
255261
256262 (defcustom org-list-two-spaces-after-bullet-regexp nil
405411 (ind-ref (if (or (looking-at "^[ \t]*$")
406412 (and inlinetask-re (looking-at inlinetask-re)))
407413 10000
408 (current-indentation))))
414 (org-current-text-indentation))))
409415 (cond
410416 ((eq (nth 2 context) 'invalid) nil)
411417 ((looking-at item-re) (point))
427433 ;; Look for an item, less indented that reference line.
428434 (catch 'exit
429435 (while t
430 (let ((ind (current-indentation)))
436 (let ((ind (org-current-text-indentation)))
431437 (cond
432438 ;; This is exactly what we want.
433439 ((and (looking-at item-re) (< ind ind-ref))
516522 (and (not (looking-at beg-re))
517523 (not (looking-at end-re))
518524 (setq beg (and (re-search-backward beg-re lim-up t)
519 (1+ (point-at-eol))))
525 (1+ (line-end-position))))
520526 (setq end (or (and (re-search-forward end-re lim-down t)
521527 (1- (match-beginning 0)))
522528 lim-down))
527533 (when (save-excursion
528534 (and (not (looking-at block-re))
529535 (setq beg (and (re-search-backward block-re lim-up t)
530 (1+ (point-at-eol))))
536 (1+ (line-end-position))))
531537 (looking-at "^[ \t]*#\\+begin_\\(\\S-+\\)")
532538 (setq type (downcase (match-string 1)))
533539 (goto-char beg)
534540 (setq end (or (and (re-search-forward block-re lim-down t)
535 (1- (point-at-bol)))
541 (1- (line-beginning-position)))
536542 lim-down))
537543 (>= end pos)
538544 (equal (downcase (match-string 1)) "end")))
546552 (end-re (concat beg-re "END[ \t]*$")))
547553 (and (not (looking-at "^\\*+"))
548554 (setq beg (and (re-search-backward beg-re lim-up t)
549 (1+ (point-at-eol))))
555 (1+ (line-end-position))))
550556 (not (looking-at end-re))
551557 (setq end (and (re-search-forward end-re lim-down t)
552558 (1- (match-beginning 0))))
568574 6. position at item end.
569575
570576 Thus the following list, where numbers in parens are
571 point-at-bol:
577 line-beginning-position:
572578
573579 - [X] first item (1)
574580 1. sub-item 1 (18)
597603 (item-re (org-item-re))
598604 (inlinetask-re (and (featurep 'org-inlinetask)
599605 (org-inlinetask-outline-regexp)))
600 (beg-cell (cons (point) (current-indentation)))
606 (beg-cell (cons (point) (org-current-text-indentation)))
601607 itm-lst itm-lst-2 end-lst end-lst-2 struct
602608 (assoc-at-point
603609 ;; Return association at point.
616622 ;; Ensure list ends at the first blank line.
617623 (lambda ()
618624 (skip-chars-backward " \r\t\n")
619 (min (1+ (point-at-eol)) lim-down))))
625 (min (1+ (line-end-position)) lim-down))))
620626 ;; 1. Read list from starting item to its beginning, and save
621627 ;; top item position and indentation in BEG-CELL. Also store
622628 ;; ending position of items in END-LST.
623629 (save-excursion
624630 (catch 'exit
625631 (while t
626 (let ((ind (current-indentation)))
632 (let ((ind (org-current-text-indentation)))
627633 (cond
628634 ((<= (point) lim-up)
629635 ;; At upward limit: if we ended at an item, store it,
683689 ;; position of items in END-LST-2.
684690 (catch 'exit
685691 (while t
686 (let ((ind (current-indentation)))
692 (let ((ind (org-current-text-indentation)))
687693 (cond
688694 ((>= (point) lim-down)
689695 ;; At downward limit: this is de facto the end of the
871877 (save-excursion
872878 (goto-char (org-list-get-item-end item struct))
873879 (skip-chars-backward " \r\t\n")
874 (point-at-eol)))
880 (line-end-position)))
875881
876882 (defun org-list-get-parent (item struct parents)
877883 "Return parent of ITEM or nil.
10881094
10891095 This function modifies STRUCT."
10901096 (save-excursion
1091 (let* ((end-A-no-blank (org-list-get-item-end-before-blank beg-A struct))
1092 (end-B-no-blank (org-list-get-item-end-before-blank beg-B struct))
1093 (end-A (org-list-get-item-end beg-A struct))
1094 (end-B (org-list-get-item-end beg-B struct))
1095 (size-A (- end-A-no-blank beg-A))
1096 (size-B (- end-B-no-blank beg-B))
1097 (body-A (buffer-substring beg-A end-A-no-blank))
1098 (body-B (buffer-substring beg-B end-B-no-blank))
1099 (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B))
1100 (sub-A (cons beg-A (org-list-get-subtree beg-A struct)))
1101 (sub-B (cons beg-B (org-list-get-subtree beg-B struct)))
1102 ;; Store overlays responsible for visibility status. We
1103 ;; also need to store their boundaries as they will be
1104 ;; removed from buffer.
1105 (overlays
1106 (cons
1107 (delq nil
1108 (mapcar (lambda (o)
1109 (and (>= (overlay-start o) beg-A)
1110 (<= (overlay-end o) end-A)
1111 (list o (overlay-start o) (overlay-end o))))
1112 (overlays-in beg-A end-A)))
1113 (delq nil
1114 (mapcar (lambda (o)
1115 (and (>= (overlay-start o) beg-B)
1116 (<= (overlay-end o) end-B)
1117 (list o (overlay-start o) (overlay-end o))))
1118 (overlays-in beg-B end-B))))))
1119 ;; 1. Move effectively items in buffer.
1120 (goto-char beg-A)
1121 (delete-region beg-A end-B-no-blank)
1122 (insert (concat body-B between-A-no-blank-and-B body-A))
1123 ;; 2. Now modify struct. No need to re-read the list, the
1124 ;; transformation is just a shift of positions. Some special
1125 ;; attention is required for items ending at END-A and END-B
1126 ;; as empty spaces are not moved there. In others words,
1127 ;; item BEG-A will end with whitespaces that were at the end
1128 ;; of BEG-B and the same applies to BEG-B.
1129 (dolist (e struct)
1130 (let ((pos (car e)))
1131 (cond
1132 ((< pos beg-A))
1133 ((memq pos sub-A)
1134 (let ((end-e (nth 6 e)))
1135 (setcar e (+ pos (- end-B-no-blank end-A-no-blank)))
1136 (setcar (nthcdr 6 e)
1137 (+ end-e (- end-B-no-blank end-A-no-blank)))
1138 (when (= end-e end-A) (setcar (nthcdr 6 e) end-B))))
1139 ((memq pos sub-B)
1140 (let ((end-e (nth 6 e)))
1141 (setcar e (- (+ pos beg-A) beg-B))
1142 (setcar (nthcdr 6 e) (+ end-e (- beg-A beg-B)))
1143 (when (= end-e end-B)
1144 (setcar (nthcdr 6 e)
1145 (+ beg-A size-B (- end-A end-A-no-blank))))))
1146 ((< pos beg-B)
1147 (let ((end-e (nth 6 e)))
1148 (setcar e (+ pos (- size-B size-A)))
1149 (setcar (nthcdr 6 e) (+ end-e (- size-B size-A))))))))
1150 (setq struct (sort struct #'car-less-than-car))
1151 ;; Restore visibility status, by moving overlays to their new
1152 ;; position.
1153 (dolist (ov (car overlays))
1154 (move-overlay
1155 (car ov)
1156 (+ (nth 1 ov) (- (+ beg-B (- size-B size-A)) beg-A))
1157 (+ (nth 2 ov) (- (+ beg-B (- size-B size-A)) beg-A))))
1158 (dolist (ov (cdr overlays))
1159 (move-overlay (car ov)
1160 (+ (nth 1 ov) (- beg-A beg-B))
1161 (+ (nth 2 ov) (- beg-A beg-B))))
1162 ;; Return structure.
1163 struct)))
1097 (org-fold-core-ignore-modifications
1098 (let* ((end-A-no-blank (org-list-get-item-end-before-blank beg-A struct))
1099 (end-B-no-blank (org-list-get-item-end-before-blank beg-B struct))
1100 (end-A (org-list-get-item-end beg-A struct))
1101 (end-B (org-list-get-item-end beg-B struct))
1102 (size-A (- end-A-no-blank beg-A))
1103 (size-B (- end-B-no-blank beg-B))
1104 (body-A (buffer-substring beg-A end-A-no-blank))
1105 (body-B (buffer-substring beg-B end-B-no-blank))
1106 (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B))
1107 (sub-A (cons beg-A (org-list-get-subtree beg-A struct)))
1108 (sub-B (cons beg-B (org-list-get-subtree beg-B struct)))
1109 ;; Store inner folds responsible for visibility status.
1110 (folds
1111 (cons
1112 (org-fold-core-get-regions :from beg-A :to end-A :relative t)
1113 (org-fold-core-get-regions :from beg-B :to end-B :relative t))))
1114 ;; Clear up the folds.
1115 (org-fold-region beg-A end-B-no-blank nil)
1116 ;; 1. Move effectively items in buffer.
1117 (goto-char beg-A)
1118 (delete-region beg-A end-B-no-blank)
1119 (insert (concat body-B between-A-no-blank-and-B body-A))
1120 ;; Restore visibility status.
1121 (org-fold-core-regions (cdr folds) :relative beg-A)
1122 (org-fold-core-regions
1123 (car folds)
1124 :relative (+ beg-B (- size-B size-A (length between-A-no-blank-and-B))))
1125 ;; 2. Now modify struct. No need to re-read the list, the
1126 ;; transformation is just a shift of positions. Some special
1127 ;; attention is required for items ending at END-A and END-B
1128 ;; as empty spaces are not moved there. In others words,
1129 ;; item BEG-A will end with whitespaces that were at the end
1130 ;; of BEG-B and the same applies to BEG-B.
1131 (dolist (e struct)
1132 (let ((pos (car e)))
1133 (cond
1134 ((< pos beg-A))
1135 ((memq pos sub-A)
1136 (let ((end-e (nth 6 e)))
1137 (setcar e (+ pos (- end-B-no-blank end-A-no-blank)))
1138 (setcar (nthcdr 6 e)
1139 (+ end-e (- end-B-no-blank end-A-no-blank)))
1140 (when (= end-e end-A) (setcar (nthcdr 6 e) end-B))))
1141 ((memq pos sub-B)
1142 (let ((end-e (nth 6 e)))
1143 (setcar e (- (+ pos beg-A) beg-B))
1144 (setcar (nthcdr 6 e) (+ end-e (- beg-A beg-B)))
1145 (when (= end-e end-B)
1146 (setcar (nthcdr 6 e)
1147 (+ beg-A size-B (- end-A end-A-no-blank))))))
1148 ((< pos beg-B)
1149 (let ((end-e (nth 6 e)))
1150 (setcar e (+ pos (- size-B size-A)))
1151 (setcar (nthcdr 6 e) (+ end-e (- size-B size-A))))))))
1152 (setq struct (sort struct #'car-less-than-car))
1153 ;; Return structure.
1154 struct))))
11641155
11651156 (defun org-list-separating-blank-lines-number (pos struct prevs)
11661157 "Return number of blank lines that should separate items in list.
11811172 (lambda ()
11821173 ;; Count blank lines above beginning of line.
11831174 (save-excursion
1184 (count-lines (goto-char (point-at-bol))
1175 (count-lines (goto-char (line-beginning-position))
11851176 (progn (skip-chars-backward " \r\t\n")
11861177 (forward-line)
11871178 (point)))))))
12861277 ;; must be removed, or they will be left, stacking up
12871278 ;; after the list.
12881279 (when (< item-end pos)
1289 (delete-region (1- item-end) (point-at-eol)))
1280 (delete-region (1- item-end) (line-end-position)))
12901281 (skip-chars-backward " \r\t\n")
12911282 ;; Cut position is after any blank on the line.
12921283 (save-excursion
13631354 (save-excursion
13641355 (goto-char item)
13651356 (skip-chars-backward " \r\t\n")
1366 (min (1+ (point-at-eol)) (point-max)))
1357 (min (1+ (line-end-position)) (point-max)))
13671358 item)))
13681359 ;; Remove item from buffer.
13691360 (delete-region beg end)
14401431 (setq dest (org-list-get-list-end item struct prevs))
14411432 (save-excursion
14421433 (goto-char (org-list-get-last-item item struct prevs))
1443 (point-at-eol)))
1444 ((string-match-p "\\`[0-9]+\\'" dest)
1434 (line-end-position)))
1435 ((and (stringp dest) (string-match-p "\\`[0-9]+\\'" dest))
14451436 (let* ((all (org-list-get-all-items item struct prevs))
14461437 (len (length all))
14471438 (index (mod (string-to-number dest) len)))
14521443 (save-excursion
14531444 (goto-char
14541445 (org-list-get-last-item item struct prevs))
1455 (point-at-eol)))))
1446 (line-end-position)))))
14561447 (t dest)))
14571448 (org-M-RET-may-split-line nil)
14581449 ;; Store inner overlays (to preserve visibility).
18491840 (org-inlinetask-goto-beginning))
18501841 ;; Shift only non-empty lines.
18511842 ((looking-at-p "^[ \t]*\\S-")
1852 (indent-line-to (+ (current-indentation) delta))))
1843 (indent-line-to (+ (org-current-text-indentation) delta))))
18531844 (forward-line -1))))
18541845 (modify-item
18551846 ;; Replace ITEM first line elements with new elements from
18571848 (lambda (item)
18581849 (goto-char item)
18591850 (let* ((new-ind (org-list-get-ind item struct))
1860 (old-ind (current-indentation))
1851 (old-ind (org-current-text-indentation))
18611852 (new-bul (org-list-bullet-string
18621853 (org-list-get-bullet item struct)))
18631854 (old-bul (org-list-get-bullet item old-struct))
18651856 (looking-at org-list-full-item-re)
18661857 ;; a. Replace bullet
18671858 (unless (equal old-bul new-bul)
1868 (replace-match new-bul nil nil nil 1))
1859 (let ((keep-space ""))
1860 (save-excursion
1861 ;; If origin is inside the bullet, preserve the
1862 ;; spaces after origin.
1863 (when (<= (match-beginning 1) origin (match-end 1))
1864 (org-with-point-at origin
1865 (save-match-data
1866 (when (looking-at "[ \t]+")
1867 (setq keep-space (match-string 0))))))
1868 (replace-match "" nil nil nil 1)
1869 (goto-char (match-end 1))
1870 (insert-before-markers new-bul)
1871 (insert keep-space))))
1872 ;; Refresh potentially shifted match markers.
1873 (goto-char item)
1874 (looking-at org-list-full-item-re)
18691875 ;; b. Replace checkbox.
18701876 (cond
18711877 ((equal (match-string 3) new-box))
18791885 (insert (concat new-box (unless counterp " "))))))
18801886 ;; c. Indent item to appropriate column.
18811887 (unless (= new-ind old-ind)
1882 (delete-region (goto-char (point-at-bol))
1888 (delete-region (goto-char (line-beginning-position))
18831889 (progn (skip-chars-forward " \t") (point)))
18841890 (indent-to new-ind))))))
18851891 ;; 1. First get list of items and position endings. We maintain
19321938 ;; Ignore empty lines. Also ignore blocks and
19331939 ;; drawers contents.
19341940 (unless (looking-at-p "[ \t]*$")
1935 (setq min-ind (min (current-indentation) min-ind))
1941 (setq min-ind (min (org-current-text-indentation) min-ind))
19361942 (cond
19371943 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
19381944 (re-search-forward
20092015 beginning of the item."
20102016 (let* ((struct (org-list-struct))
20112017 (prevs (org-list-prevs-alist struct))
2012 (item (copy-marker (point-at-bol)))
2018 (item (copy-marker (line-beginning-position)))
20132019 (all (org-list-get-all-items (marker-position item) struct prevs))
20142020 (value init-value))
20152021 (dolist (e (nreverse all))
20282034 ((eq view 'folded)
20292035 (let ((item-end (org-list-get-item-end-before-blank item struct)))
20302036 ;; Hide from eol
2031 (org-flag-region (save-excursion (goto-char item) (line-end-position))
2037 (org-fold-region (save-excursion (goto-char item) (line-end-position))
20322038 item-end t 'outline)))
20332039 ((eq view 'children)
20342040 ;; First show everything.
20412047 ((eq view 'subtree)
20422048 ;; Show everything
20432049 (let ((item-end (org-list-get-item-end item struct)))
2044 (org-flag-region item item-end nil 'outline)))))
2050 (org-fold-region item item-end nil 'outline)))))
20452051
20462052 (defun org-list-item-body-column (item)
20472053 "Return column at which body of ITEM should start."
21462152 (interactive)
21472153 (unless (org-at-item-p) (error "Not at an item"))
21482154 (let* ((col (current-column))
2149 (item (point-at-bol))
2155 (item (line-beginning-position))
21502156 (struct (org-list-struct))
21512157 (prevs (org-list-prevs-alist struct))
2152 (next-item (org-list-get-next-item (point-at-bol) struct prevs)))
2158 (next-item (org-list-get-next-item (line-beginning-position) struct prevs)))
21532159 (unless (or next-item org-list-use-circular-motion)
21542160 (user-error "Cannot move this item further down"))
21552161 (if (not next-item)
21672173 (interactive)
21682174 (unless (org-at-item-p) (error "Not at an item"))
21692175 (let* ((col (current-column))
2170 (item (point-at-bol))
2176 (item (line-beginning-position))
21712177 (struct (org-list-struct))
21722178 (prevs (org-list-prevs-alist struct))
2173 (prev-item (org-list-get-prev-item (point-at-bol) struct prevs)))
2179 (prev-item (org-list-get-prev-item (line-beginning-position) struct prevs)))
21742180 (unless (or prev-item org-list-use-circular-motion)
21752181 (user-error "Cannot move this item further up"))
21762182 (if (not prev-item)
22112217 (setq struct (org-list-insert-item pos struct prevs checkbox desc))
22122218 (org-list-write-struct struct (org-list-parents-alist struct))
22132219 (when checkbox (org-update-checkbox-count-maybe))
2220 (beginning-of-line)
22142221 (looking-at org-list-full-item-re)
22152222 (goto-char (if (and (match-beginning 4)
22162223 (save-match-data
22392246 `previous', cycle backwards."
22402247 (interactive "P")
22412248 (unless (org-at-item-p) (error "Not at an item"))
2242 (save-excursion
2249 (let ((origin (point-marker)))
22432250 (beginning-of-line)
22442251 (let* ((struct (org-list-struct))
22452252 (parents (org-list-parents-alist struct))
22462253 (prevs (org-list-prevs-alist struct))
22472254 (list-beg (org-list-get-first-item (point) struct prevs))
2255 ;; Record relative point position to bullet beginning.
2256 (origin-offset (- origin
2257 (+ (point) (org-list-get-ind (point) struct))))
2258 ;; Record relative point position to bullet end.
2259 (origin-offset2 (- origin
2260 (+ (point) (org-list-get-ind (point) struct)
2261 (length (org-list-get-bullet (point) struct)))))
22482262 (bullet (org-list-get-bullet list-beg struct))
22492263 (alpha-p (org-list-use-alpha-bul-p list-beg struct prevs))
22502264 (case-fold-search nil)
22902304 (org-list-set-bullet list-beg struct (org-list-bullet-string new))
22912305 (org-list-struct-fix-bul struct prevs)
22922306 (org-list-struct-fix-ind struct parents)
2293 (org-list-struct-apply-struct struct old-struct)))))
2307 (org-list-struct-apply-struct struct old-struct))
2308 (goto-char origin)
2309 (setq struct (org-list-struct))
2310 (cond
2311 ((>= origin-offset2 0)
2312 (beginning-of-line)
2313 (move-marker origin (+ (point)
2314 (org-list-get-ind (point) struct)
2315 (length (org-list-get-bullet (point) struct))
2316 origin-offset2))
2317 (goto-char origin))
2318 ((>= origin-offset 0)
2319 (beginning-of-line)
2320 (move-marker origin (+ (point)
2321 (org-list-get-ind (point) struct)
2322 origin-offset))
2323 (goto-char origin)))
2324 (move-marker origin nil))))
22942325
22952326 ;;;###autoload
22962327 (define-minor-mode org-list-checkbox-radio-mode
23112342 (old-struct (copy-tree struct))
23122343 (cbox (org-list-get-checkbox cpos struct))
23132344 (prevs (org-list-prevs-alist struct))
2314 (start (org-list-get-list-begin (point-at-bol) struct prevs))
2345 (start (org-list-get-list-begin (line-beginning-position) struct prevs))
23152346 (new (unless (and cbox (equal arg '(4)) (equal start cpos))
23162347 "[ ]")))
23172348 (dolist (pos (org-list-get-all-items
23712402 (let ((limit (region-end)))
23722403 (goto-char (region-beginning))
23732404 (if (org-list-search-forward (org-item-beginning-re) limit t)
2374 (setq lim-up (point-at-bol))
2405 (setq lim-up (line-beginning-position))
23752406 (error "No item in region"))
23762407 (setq lim-down (copy-marker limit))))
23772408 ((org-at-heading-p)
23802411 (let ((limit (save-excursion (outline-next-heading) (point))))
23812412 (org-end-of-meta-data t)
23822413 (if (org-list-search-forward (org-item-beginning-re) limit t)
2383 (setq lim-up (point-at-bol))
2414 (setq lim-up (line-beginning-position))
23842415 (error "No item in subtree"))
23852416 (setq lim-down (copy-marker limit))))
23862417 ;; Just one item: set SINGLEP flag.
23872418 ((org-at-item-p)
23882419 (setq singlep t)
2389 (setq lim-up (point-at-bol)
2390 lim-down (copy-marker (point-at-eol))))
2420 (setq lim-up (line-beginning-position)
2421 lim-down (copy-marker (line-end-position))))
23912422 (t (error "Not at an item or heading, and no active region"))))
23922423 ;; Determine the checkbox going to be applied to all items
23932424 ;; within bounds.
24542485 (save-restriction
24552486 (save-excursion
24562487 (org-narrow-to-subtree)
2457 (org-show-subtree)
2488 (org-fold-show-subtree)
24582489 (goto-char (point-min))
24592490 (let ((end (point-max)))
24602491 (while (< (point) end)
26352666 ;; Are we going to move the whole list?
26362667 (specialp
26372668 (and (not regionp)
2638 (= top (point-at-bol))
2669 (= top (line-beginning-position))
26392670 (cdr (assq 'indent org-list-automatic-rules))
26402671 (if no-subtree
26412672 (user-error
26492680 (progn
26502681 (set-marker org-last-indent-begin-marker rbeg)
26512682 (set-marker org-last-indent-end-marker rend))
2652 (set-marker org-last-indent-begin-marker (point-at-bol))
2683 (set-marker org-last-indent-begin-marker (line-beginning-position))
26532684 (set-marker org-last-indent-end-marker
26542685 (cond
26552686 (specialp (org-list-get-bottom-point struct))
2656 (no-subtree (1+ (point-at-bol)))
2657 (t (org-list-get-item-end (point-at-bol) struct))))))
2687 (no-subtree (1+ (line-beginning-position)))
2688 (t (org-list-get-item-end (line-beginning-position) struct))))))
26582689 (let* ((beg (marker-position org-last-indent-begin-marker))
26592690 (end (marker-position org-last-indent-end-marker)))
26602691 (cond
28922923 (let* ((case-func (if with-case 'identity 'downcase))
28932924 (struct (org-list-struct))
28942925 (prevs (org-list-prevs-alist struct))
2895 (start (org-list-get-list-begin (point-at-bol) struct prevs))
2896 (end (org-list-get-list-end (point-at-bol) struct prevs))
2926 (start (org-list-get-list-begin (line-beginning-position) struct prevs))
2927 (end (org-list-get-list-end (line-beginning-position) struct prevs))
28972928 (sorting-type
28982929 (or sorting-type
28992930 (progn
29092940 (error "Missing key extractor"))))
29102941 (sort-func
29112942 (cond
2912 ((= dcst ?a) #'org-string-collate-lessp)
2943 ((= dcst ?a) #'string-collate-lessp)
29132944 ((= dcst ?f)
29142945 (or compare-func
29152946 (and interactive?
29382969 ((= dcst ?n)
29392970 (string-to-number
29402971 (org-sort-remove-invisible
2941 (buffer-substring (match-end 0) (point-at-eol)))))
2972 (buffer-substring (match-end 0) (line-end-position)))))
29422973 ((= dcst ?a)
29432974 (funcall case-func
29442975 (org-sort-remove-invisible
29452976 (buffer-substring
2946 (match-end 0) (point-at-eol)))))
2977 (match-end 0) (line-end-position)))))
29472978 ((= dcst ?t)
29482979 (cond
29492980 ;; If it is a timer list, convert timer to seconds
29502981 ((org-at-item-timer-p)
29512982 (org-timer-hms-to-secs (match-string 1)))
29522983 ((or (save-excursion
2953 (re-search-forward org-ts-regexp (point-at-eol) t))
2984 (re-search-forward org-ts-regexp (line-end-position) t))
29542985 (save-excursion (re-search-forward org-ts-regexp-both
2955 (point-at-eol) t)))
2986 (line-end-position) t)))
29562987 (org-time-string-to-seconds (match-string 0)))
29572988 (t (float-time now))))
29582989 ((= dcst ?x) (or (and (stringp (match-string 1))
29903021 If it is normal text, change region into a list of items.
29913022 With a prefix argument ARG, change the region in a single item."
29923023 (interactive "P")
2993 (let ((shift-text
3024 (let ((extract-footnote-definitions
3025 (lambda (end)
3026 ;; Remove footnote definitions from point to END.
3027 ;; Return the list of the extracted definitions.
3028 (let (definitions element)
3029 (save-excursion
3030 (while (re-search-forward org-footnote-definition-re end t)
3031 (setq element (org-element-at-point))
3032 (when (eq 'footnote-definition
3033 (org-element-type element))
3034 (push (buffer-substring-no-properties
3035 (org-element-property :begin element)
3036 (org-element-property :end element))
3037 definitions)
3038 ;; Ensure at least 2 blank lines after the last
3039 ;; footnote definition, thus not slurping the
3040 ;; following element.
3041 (unless (<= 2 (org-element-property
3042 :post-blank
3043 (org-element-at-point)))
3044 (setf (car definitions)
3045 (concat (car definitions)
3046 (make-string
3047 (- 2 (org-element-property
3048 :post-blank
3049 (org-element-at-point)))
3050 ?\n))))
3051 (delete-region
3052 (org-element-property :begin element)
3053 (org-element-property :end element))))
3054 definitions))))
3055 (shift-text
29943056 (lambda (ind end)
29953057 ;; Shift text in current section to IND, from point to END.
29963058 ;; The function leaves point to END line.
30003062 (save-excursion
30013063 (catch 'exit
30023064 (while (< (point) end)
3003 (let ((i (current-indentation)))
3065 (let ((i (org-current-text-indentation)))
30043066 (cond
30053067 ;; Skip blank lines and inline tasks.
30063068 ((looking-at "^[ \t]*$"))
30163078 (while (< (point) end)
30173079 (unless (or (looking-at "^[ \t]*$")
30183080 (looking-at org-outline-regexp-bol))
3019 (indent-line-to (+ (current-indentation) delta)))
3081 (indent-line-to (+ (org-current-text-indentation) delta)))
30203082 (forward-line))))))
30213083 (skip-blanks
30223084 (lambda (pos)
30253087 (save-excursion
30263088 (goto-char pos)
30273089 (skip-chars-forward " \r\t\n")
3028 (point-at-bol))))
3090 (line-beginning-position))))
30293091 beg end)
30303092 ;; Determine boundaries of changes.
30313093 (if (org-region-active-p)
30323094 (setq beg (funcall skip-blanks (region-beginning))
30333095 end (copy-marker (region-end)))
3034 (setq beg (point-at-bol)
3035 end (copy-marker (point-at-eol))))
3096 (setq beg (line-beginning-position)
3097 end (copy-marker (line-end-position))))
30363098 ;; Depending on the starting line, choose an action on the text
30373099 ;; between BEG and END.
30383100 (org-with-limited-levels
30483110 (skip-chars-forward " \t")
30493111 (delete-region (point) (match-end 0)))
30503112 (forward-line)))
3051 ;; Case 2. Start at an heading: convert to items.
3113 ;; Case 2. Start at a heading: convert to items.
30523114 ((org-at-heading-p)
30533115 ;; Remove metadata
30543116 (let (org-loop-over-headlines-in-active-region)
30643126 (t (length (match-string 0))))))
30653127 ;; Level of first heading. Further headings will be
30663128 ;; compared to it to determine hierarchy in the list.
3067 (ref-level (org-reduced-level (org-outline-level))))
3129 (ref-level (org-reduced-level (org-outline-level)))
3130 (footnote-definitions
3131 (funcall extract-footnote-definitions end)))
30683132 (while (< (point) end)
30693133 (let* ((level (org-reduced-level (org-outline-level)))
30703134 (delta (max 0 (- level ref-level)))
30933157 "[X]"
30943158 "[ ]"))
30953159 (org-list-write-struct struct
3096 (org-list-parents-alist struct)
3097 old)))
3160 (org-list-parents-alist struct)
3161 old)))
30983162 ;; Ensure all text down to END (or SECTION-END) belongs
30993163 ;; to the newly created item.
31003164 (let ((section-end (save-excursion
31023166 (forward-line)
31033167 (funcall shift-text
31043168 (+ start-ind (* (1+ delta) bul-len))
3105 (min end section-end)))))))
3169 (min end section-end)))))
3170 (when footnote-definitions
3171 (goto-char end)
3172 ;; Insert footnote definitions after the list.
3173 (unless (bolp) (beginning-of-line 2))
3174 ;; At (point-max).
3175 (unless (bolp) (insert "\n"))
3176 (dolist (def footnote-definitions)
3177 (insert def)))))
31063178 ;; Case 3. Normal line with ARG: make the first line of region
31073179 ;; an item, and shift indentation of others lines to
31083180 ;; set them as item's body.
31093181 (arg (let* ((bul (org-list-bullet-string "-"))
31103182 (bul-len (length bul))
3111 (ref-ind (current-indentation)))
3183 (ref-ind (org-current-text-indentation))
3184 (footnote-definitions
3185 (funcall extract-footnote-definitions end)))
31123186 (skip-chars-forward " \t")
31133187 (insert bul)
31143188 (forward-line)
31193193 (+ ref-ind bul-len)
31203194 (min end (save-excursion (or (outline-next-heading)
31213195 (point)))))
3122 (forward-line))))
3196 (forward-line))
3197 (when footnote-definitions
3198 ;; If the new list is followed by same-level items,
3199 ;; move past them as well.
3200 (goto-char (org-element-property
3201 :end
3202 (org-element-lineage
3203 (org-element-at-point (1- end))
3204 '(plain-list) t)))
3205 ;; Insert footnote definitions after the list.
3206 (unless (bolp) (beginning-of-line 2))
3207 ;; At (point-max).
3208 (unless (bolp) (insert "\n"))
3209 (dolist (def footnote-definitions)
3210 (insert def)))))
31233211 ;; Case 4. Normal line without ARG: turn each non-item line
31243212 ;; into an item.
31253213 (t
00 ;;; org-macro.el --- Macro Replacement Code for Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2013-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2013-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
4545 ;; {{{email}}} and {{{title}}} macros.
4646
4747 ;;; Code:
48
49 (require 'org-macs)
50 (org-assert-version)
51
4852 (require 'cl-lib)
4953 (require 'org-macs)
5054 (require 'org-compat)
5155
5256 (declare-function org-collect-keywords "org" (keywords &optional unique directory))
53 (declare-function org-element-at-point "org-element" ())
57 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
5458 (declare-function org-element-context "org-element" (&optional element))
5559 (declare-function org-element-copy "org-element" (datum))
5660 (declare-function org-element-macro-parser "org-element" ())
61 (declare-function org-element-keyword-parser "org-element" (limit affiliated))
62 (declare-function org-element-put-property "org-element" (element property value))
5763 (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
5864 (declare-function org-element-property "org-element" (property element))
5965 (declare-function org-element-restriction "org-element" (element))
6066 (declare-function org-element-type "org-element" (element))
6167 (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
6268 (declare-function org-file-contents "org" (file &optional noerror nocache))
63 (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
69 (declare-function org-in-commented-heading-p "org" (&optional no-inheritance element))
6470 (declare-function org-link-search "ol" (s &optional avoid-pos stealth))
6571 (declare-function org-mode "org" ())
6672 (declare-function vc-backend "vc-hooks" (f))
6773 (declare-function vc-call "vc-hooks" (fun file &rest args) t)
68 (declare-function vc-exec-after "vc-dispatcher" (code))
74 (declare-function vc-exec-after "vc-dispatcher" (code &optional success))
6975
7076 (defvar org-link-search-must-match-exact-headline)
7177
238244 (goto-char (match-beginning 0))
239245 (org-element-macro-parser))))))
240246 (when macro
247 ;; `:parent' property might change as we modify buffer.
248 ;; We do not care about it when checking for circular
249 ;; dependencies. So, setting `:parent' to nil making sure
250 ;; that actual macro element (if org-element-cache is
251 ;; active) is unchanged.
252 (setq macro (cl-copy-list macro))
253 (org-element-put-property macro :parent nil)
241254 (let* ((key (org-element-property :key macro))
242255 (value (org-macro-expand macro templates))
243256 (begin (org-element-property :begin macro))
337350 (result nil))
338351 (catch :exit
339352 (while (re-search-forward regexp nil t)
340 (let ((element (org-element-at-point)))
353 (let ((element (org-with-point-at (match-beginning 0) (org-element-keyword-parser (line-end-position) (list (match-beginning 0))))))
341354 (when (eq 'keyword (org-element-type element))
342355 (let ((value (org-element-property :value element)))
343356 (if (not collect) (throw :exit value)
354367 (not (cdr date))
355368 (eq 'timestamp (org-element-type (car date))))
356369 (format "(eval (if (org-string-nw-p $1) %s %S))"
357 (format "(org-timestamp-format '%S $1)"
370 (format "(org-format-timestamp '%S $1)"
358371 (org-element-copy (car date)))
359372 value)
360373 value)))
361374
362375 (defun org-macro--vc-modified-time (file)
376 (require 'vc) ; Not everything we need is autoloaded.
363377 (save-window-excursion
364378 (when (vc-backend file)
365379 (let ((buf (get-buffer-create " *org-vc*"))
377391 (buffer-substring
378392 (point) (line-end-position)))))
379393 (when (cl-some #'identity time)
380 (setq date (apply #'encode-time time))))))))
394 (setq date (org-encode-time time))))))))
381395 (let ((proc (get-buffer-process buf)))
382396 (while (and proc (accept-process-output proc .5 nil t)))))
383397 (kill-buffer buf))
00 ;;; org-macs.el --- Top-level Definitions for Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
3333 (require 'cl-lib)
3434 (require 'format-spec)
3535
36 ;;; Org version verification.
37
38 (defvar org--inhibit-version-check nil
39 "When non-nil, skip the detection of mixed-versions situations.
40 For internal use only. See Emacs bug #62762.
41 This variable is only supposed to be changed by Emacs build scripts.
42 When nil, Org tries to detect when Org source files were compiled with
43 a different version of Org (which tends to lead to incorrect `.elc' files),
44 or when the current Emacs session has loaded a mix of files from different
45 Org versions (typically the one bundled with Emacs and another one installed
46 from GNU ELPA), which can happen if some parts of Org were loaded before
47 `load-path' was changed (e.g. before the GNU-ELPA-installed Org is activated
48 by `package-activate-all').")
49 (defmacro org-assert-version ()
50 "Assert compile time and runtime version match."
51 ;; We intentionally use a more permissive `org-release' instead of
52 ;; `org-git-version' to work around deficiencies in Elisp
53 ;; compilation after pulling latest changes. Unchanged files will
54 ;; not be re-compiled and thus their macro-expanded
55 ;; `org-assert-version' calls would fail using strict
56 ;; `org-git-version' check because the generated Org version strings
57 ;; will not match.
58 `(unless (or org--inhibit-version-check (equal (org-release) ,(org-release)))
59 (warn "Org version mismatch. Org loading aborted.
60 This warning usually appears when a built-in Org version is loaded
61 prior to the more recent Org version.
62
63 Version mismatch is commonly encountered in the following situations:
64
65 1. Emacs is loaded using literate Org config and more recent Org
66 version is loaded inside the file loaded by `org-babel-load-file'.
67 `org-babel-load-file' triggers the built-in Org version clashing
68 the newer Org version attempt to be loaded later.
69
70 It is recommended to move the Org loading code before the
71 `org-babel-load-file' call.
72
73 2. New Org version is loaded manually by setting `load-path', but some
74 other package depending on Org is loaded before the `load-path' is
75 configured.
76 This \"other package\" is triggering built-in Org version, again
77 causing the version mismatch.
78
79 It is recommended to set `load-path' as early in the config as
80 possible.
81
82 3. New Org version is loaded using straight.el package manager and
83 other package depending on Org is loaded before straight triggers
84 loading of the newer Org version.
85
86 It is recommended to put
87
88 %s
89
90 early in the config. Ideally, right after the straight.el
91 bootstrap. Moving `use-package' :straight declaration may not be
92 sufficient if the corresponding `use-package' statement is
93 deferring the loading."
94 ;; Avoid `warn' replacing "'" with "’" (see `format-message').
95 "(straight-use-package 'org)")
96 (error "Org version mismatch. Make sure that correct `load-path' is set early in init.el")))
97
98 ;; We rely on org-macs when generating Org version. Checking Org
99 ;; version here will interfere with Org build process.
100 ;; (org-assert-version)
101
36102 (declare-function org-mode "org" ())
37 (declare-function org-show-context "org" (&optional key))
38 (declare-function org-string-collate-lessp "org-compat" (s1 s2 &optional locale ignore-case))
103 (declare-function org-agenda-files "org" (&optional unrestricted archives))
104 (declare-function org-time-string-to-seconds "org" (s))
105 (declare-function org-fold-show-context "org-fold" (&optional key))
106 (declare-function org-fold-save-outline-visibility "org-fold" (use-markers &rest body))
107 (declare-function org-fold-next-visibility-change "org-fold" (&optional pos limit ignore-hidden-p previous-p))
108 (declare-function org-fold-core-with-forced-fontification "org-fold" (&rest body))
109 (declare-function org-fold-folded-p "org-fold" (&optional pos limit ignore-hidden-p previous-p))
110 (declare-function string-collate-lessp "org-compat" (s1 s2 &optional locale ignore-case))
111 (declare-function org-time-convert-to-integer "org-compat" (time))
39112
40113 (defvar org-ts-regexp0)
41114 (defvar ffap-url-regexp)
115 (defvar org-fold-core-style)
42116
43117
44118 ;;; Macros
63137 ,@body)
64138 (set-buffer-modified-p ,was-modified)))))
65139
66 (defmacro org-without-partial-completion (&rest body)
67 (declare (debug (body)))
68 `(if (and (boundp 'partial-completion-mode)
69 partial-completion-mode
70 (fboundp 'partial-completion-mode))
71 (unwind-protect
72 (progn
73 (partial-completion-mode -1)
74 ,@body)
75 (partial-completion-mode 1))
140 (defmacro org-with-base-buffer (buffer &rest body)
141 "Run BODY in base buffer for BUFFER.
142 If BUFFER is nil, use base buffer for `current-buffer'."
143 (declare (debug (body)) (indent 1))
144 `(with-current-buffer (or (buffer-base-buffer ,buffer)
145 (or ,buffer (current-buffer)))
76146 ,@body))
77147
78148 (defmacro org-with-point-at (pom &rest body)
116186 (declare (debug (body)))
117187 `(let ((inhibit-read-only t)) ,@body))
118188
119 (defmacro org-save-outline-visibility (use-markers &rest body)
120 "Save and restore outline visibility around BODY.
121 If USE-MARKERS is non-nil, use markers for the positions. This
122 means that the buffer may change while running BODY, but it also
123 means that the buffer should stay alive during the operation,
124 because otherwise all these markers will point to nowhere."
125 (declare (debug (form body)) (indent 1))
126 (org-with-gensyms (data invisible-types markers?)
127 `(let* ((,invisible-types '(org-hide-block outline))
128 (,markers? ,use-markers)
129 (,data
130 (mapcar (lambda (o)
131 (let ((beg (overlay-start o))
132 (end (overlay-end o))
133 (type (overlay-get o 'invisible)))
134 (and beg end
135 (> end beg)
136 (memq type ,invisible-types)
137 (list (if ,markers? (copy-marker beg) beg)
138 (if ,markers? (copy-marker end t) end)
139 type))))
140 (org-with-wide-buffer
141 (overlays-in (point-min) (point-max))))))
142 (unwind-protect (progn ,@body)
143 (org-with-wide-buffer
144 (dolist (type ,invisible-types)
145 (remove-overlays (point-min) (point-max) 'invisible type))
146 (pcase-dolist (`(,beg ,end ,type) (delq nil ,data))
147 (org-flag-region beg end t type)
148 (when ,markers?
149 (set-marker beg nil)
150 (set-marker end nil))))))))
189 (defalias 'org-save-outline-visibility #'org-fold-save-outline-visibility)
151190
152191 (defmacro org-with-wide-buffer (&rest body)
153192 "Execute body while temporarily widening the buffer."
190229 (and (re-search-backward "^[ \t]*# +Local Variables:"
191230 (max (- (point) 3000) 1)
192231 t)
193 (delete-and-extract-region (point) (point-max)))))))
232 (let ((buffer-undo-list t))
233 (delete-and-extract-region (point) (point-max)))))))
234 (tick-counter-before (buffer-modified-tick)))
194235 (unwind-protect (progn ,@body)
195236 (when local-variables
196237 (org-with-wide-buffer
197238 (goto-char (point-max))
198 ;; If last section is folded, make sure to also hide file
199 ;; local variables after inserting them back.
200 (let ((overlay
201 (cl-find-if (lambda (o)
202 (eq 'outline (overlay-get o 'invisible)))
203 (overlays-at (1- (point))))))
204 (unless (bolp) (insert "\n"))
239 (unless (bolp) (insert "\n"))
240 (let ((modified (< tick-counter-before (buffer-modified-tick)))
241 (buffer-undo-list t))
205242 (insert local-variables)
206 (when overlay
207 (move-overlay overlay (overlay-start overlay) (point-max)))))))))
243 (unless modified
244 (restore-buffer-modified-p nil))))))))
208245
209246 (defmacro org-no-popups (&rest body)
210247 "Suppress popup windows and evaluate BODY."
211248 `(let (pop-up-frames pop-up-windows)
249 ,@body))
250
251 (defmacro org-element-with-disabled-cache (&rest body)
252 "Run BODY without active org-element-cache."
253 (declare (debug (form body)) (indent 0))
254 `(cl-letf (((symbol-function #'org-element--cache-active-p) (lambda (&rest _) nil)))
212255 ,@body))
213256
214257
240283 passed through to `fit-window-to-buffer'. If SHRINK-ONLY is set, call
241284 `shrink-window-if-larger-than-buffer' instead, the height limit is
242285 ignored in this case."
243 (cond ((if (fboundp 'window-full-width-p)
244 (not (window-full-width-p window))
245 ;; Do nothing if another window would suffer.
246 (> (frame-width) (window-width window))))
247 ((and (fboundp 'fit-window-to-buffer) (not shrink-only))
286 (cond ((not (window-full-width-p window))
287 ;; Do nothing if another window would suffer.
288 )
289 ((not shrink-only)
248290 (fit-window-to-buffer window max-height min-height))
249 ((fboundp 'shrink-window-if-larger-than-buffer)
250 (shrink-window-if-larger-than-buffer window)))
291 (t (shrink-window-if-larger-than-buffer window)))
251292 (or window (selected-window)))
293
294 (defun org-buffer-list (&optional predicate exclude-tmp)
295 "Return a list of Org buffers.
296 PREDICATE can be `export', `files' or `agenda'.
297
298 export restrict the list to Export buffers.
299 files restrict the list to buffers visiting Org files.
300 agenda restrict the list to buffers visiting agenda files.
301
302 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
303 (let* ((bfn nil)
304 (agenda-files (and (eq predicate 'agenda)
305 (mapcar 'file-truename (org-agenda-files t))))
306 (filter
307 (cond
308 ((eq predicate 'files)
309 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
310 ((eq predicate 'export)
311 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
312 ((eq predicate 'agenda)
313 (lambda (b)
314 (with-current-buffer b
315 (and (derived-mode-p 'org-mode)
316 (setq bfn (buffer-file-name b))
317 (member (file-truename bfn) agenda-files)))))
318 (t (lambda (b) (with-current-buffer b
319 (or (derived-mode-p 'org-mode)
320 (string-match "\\*Org .*Export"
321 (buffer-name b)))))))))
322 (delq nil
323 (mapcar
324 (lambda(b)
325 (if (and (funcall filter b)
326 (or (not exclude-tmp)
327 (not (string-match "tmp" (buffer-name b)))))
328 b
329 nil))
330 (buffer-list)))))
252331
253332
254333
255334 ;;; File
256335
257336 (defun org-file-newer-than-p (file time)
258 "Non-nil if FILE is newer than TIME.
259 FILE is a filename, as a string, TIME is a list of integers, as
260 returned by, e.g., `current-time'."
261 (and (file-exists-p file)
262 ;; Only compare times up to whole seconds as some file-systems
263 ;; (e.g. HFS+) do not retain any finer granularity. As
264 ;; a consequence, make sure we return non-nil when the two
265 ;; times are equal.
266 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
267 (cl-subseq time 0 2)))))
337 "Non-nil if FILE modification time is greater than TIME.
338 TIME should be obtained earlier for the same FILE name using
339
340 \(file-attribute-modification-time (file-attributes file))
341
342 If TIME is nil (file did not exist) then any existing FILE
343 is considered as a newer one. Some file systems have coarse
344 timestamp resolution, for example 1 second on HFS+ or 2 seconds on FAT,
345 so nil may be returned when file is updated twice within a short period
346 of time. File timestamp and system clock `current-time' may have
347 different resolution, so attempts to compare them may give unexpected
348 results.
349
350 Consider `file-newer-than-file-p' to check up to date state
351 in target-prerequisite files relation."
352 (let ((mtime (file-attribute-modification-time (file-attributes file))))
353 (and mtime (or (not time) (time-less-p time mtime)))))
268354
269355 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
270356 "Compile a SOURCE file using PROCESS.
296382 it for output."
297383 (let* ((base-name (file-name-base source))
298384 (full-name (file-truename source))
299 (out-dir (or (file-name-directory source) "./"))
385 (relative-name (file-relative-name source))
386 (out-dir (if (file-name-directory source)
387 ;; Expand "~". Shell expansion will be disabled
388 ;; in the shell command call.
389 (file-name-directory full-name)
390 "./"))
300391 (output (expand-file-name (concat base-name "." ext) out-dir))
301 (time (current-time))
392 (time (file-attribute-modification-time (file-attributes output)))
302393 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
303394 (save-window-excursion
304395 (pcase process
305 ((pred functionp) (funcall process (shell-quote-argument source)))
396 ((pred functionp) (funcall process (shell-quote-argument relative-name)))
306397 ((pred consp)
307398 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
308399 (spec (append spec
309400 `((?b . ,(shell-quote-argument base-name))
310 (?f . ,(shell-quote-argument source))
401 (?f . ,(shell-quote-argument relative-name))
311402 (?F . ,(shell-quote-argument full-name))
312403 (?o . ,(shell-quote-argument out-dir))
313404 (?O . ,(shell-quote-argument output))))))
314 (dolist (command process)
315 (shell-command (format-spec command spec) log-buf))
405 ;; Combine output of all commands in PROCESS.
406 (with-current-buffer log-buf
407 (let (buffer-read-only)
408 (erase-buffer)))
409 (let ((shell-command-dont-erase-buffer t))
410 (dolist (command process)
411 (shell-command (format-spec command spec) log-buf)))
316412 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
317413 (_ (error "No valid command to process %S%s" source err-msg))))
318414 ;; Check for process failure. Output file is expected to be
324420
325421
326422 ;;; Indentation
423
424 (defmacro org-current-text-indentation ()
425 "Like `current-indentation', but ignore display/invisible properties."
426 `(let ((buffer-invisibility-spec nil))
427 (current-indentation)))
327428
328429 (defun org-do-remove-indentation (&optional n skip-fl)
329430 "Remove the maximum common indentation from the buffer.
339440 (save-excursion
340441 (when skip-fl (forward-line))
341442 (while (re-search-forward "^[ \t]*\\S-" nil t)
342 (let ((ind (current-indentation)))
443 (let ((ind (org-current-text-indentation)))
343444 (if (zerop ind) (throw :exit nil)
344445 (setq min-ind (min min-ind ind))))))
345446 min-ind))))
518619 For example, in this alist:
519620
520621 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
521 => \\='((a 1 3) (b 2))
622 => ((a 1 3) (b 2))
522623
523624 merge (a 1) and (a 3) into (a 1 3).
524625
575676
576677 (defconst org-unique-local-variables
577678 '(org-element--cache
578 org-element--cache-objects
679 org-element--headline-cache
680 org-element--cache-change-tic
681 org-element--cache-last-buffer-size
682 org-element--cache-change-warning
683 org-element--cache-gapless
684 org-element--cache-hash-left
685 org-element--cache-hash-right
686 org-element--cache-size
687 org-element--headline-cache-size
688 org-element--cache-sync-keys-value
689 org-element--cache-diagnostics-ring
690 org-element--cache-diagnostics-ring-size
579691 org-element--cache-sync-keys
580692 org-element--cache-sync-requests
581693 org-element--cache-sync-timer)
721833
722834
723835
724 ;;; Overlays
836 ;;; Overlays and text properties
725837
726838 (defun org-overlay-display (ovl text &optional face evap)
727839 "Make overlay OVL display TEXT with face FACE."
744856 (delete (delete-overlay ov))
745857 (t (push ov found))))))
746858
747 (defun org-flag-region (from to flag spec)
748 "Hide or show lines from FROM to TO, according to FLAG.
749 SPEC is the invisibility spec, as a symbol."
750 (remove-overlays from to 'invisible spec)
751 ;; Use `front-advance' since text right before to the beginning of
752 ;; the overlay belongs to the visible line than to the contents.
753 (when flag
754 (let ((o (make-overlay from to nil 'front-advance)))
755 (overlay-put o 'evaporate t)
756 (overlay-put o 'invisible spec)
757 (overlay-put o
758 'isearch-open-invisible
759 (lambda (&rest _) (org-show-context 'isearch))))))
760
859 (defun org-find-text-property-region (pos prop)
860 "Find a region around POS containing same non-nil value of PROP text property.
861 Return nil when PROP is not set at POS."
862 (let* ((beg (and (get-text-property pos prop) pos))
863 (end beg))
864 (when beg
865 (unless (or (equal beg (point-min))
866 (not (eq (get-text-property beg prop)
867 (get-text-property (1- beg) prop))))
868 (setq beg (previous-single-property-change pos prop nil (point-min))))
869 (unless (or (equal end (point-max))
870 ;; (not (eq (get-text-property end prop)
871 ;; (get-text-property (1+ end) prop)))
872 )
873 (setq end (next-single-property-change pos prop nil (point-max))))
874 (cons beg end))))
761875
762876
763877 ;;; Regexp matching
824938 ;;; String manipulation
825939
826940 (defun org-string< (a b)
827 (org-string-collate-lessp a b))
941 (string-collate-lessp a b))
828942
829943 (defun org-string<= (a b)
830 (or (string= a b) (org-string-collate-lessp a b)))
944 (or (string= a b) (string-collate-lessp a b)))
831945
832946 (defun org-string>= (a b)
833 (not (org-string-collate-lessp a b)))
947 (not (string-collate-lessp a b)))
834948
835949 (defun org-string> (a b)
836950 (and (not (string= a b))
837 (not (org-string-collate-lessp a b))))
951 (not (string-collate-lessp a b))))
838952
839953 (defun org-string<> (a b)
840954 (not (string= a b)))
8891003 (cursor beg))
8901004 (while (setq beg (text-property-not-all beg end property nil s))
8911005 (let* ((next (next-single-property-change beg property s end))
892 (props (text-properties-at beg s))
893 (spec (plist-get props property))
1006 (spec (get-text-property beg property s))
8941007 (value
8951008 (pcase property
8961009 (`invisible
897 ;; If `invisible' property in PROPS means text is to
898 ;; be invisible, return 0. Otherwise return nil so
899 ;; as to resume search.
1010 ;; If `invisible' property means text is to be
1011 ;; invisible, return 0. Otherwise return nil so as
1012 ;; to resume search.
9001013 (and (or (eq t buffer-invisibility-spec)
9011014 (assoc-string spec buffer-invisibility-spec))
9021015 0))
9371050 ((= cursor end) 0)
9381051 (t (string-width (substring s cursor end)))))))
9391052
940 (defun org-string-width (string)
1053 (defun org--string-width-1 (string)
9411054 "Return width of STRING when displayed in the current buffer.
9421055 Unlike `string-width', this function takes into consideration
9431056 `invisible' and `display' text properties. It supports the
9451058 Results may be off sometimes if it cannot handle a given
9461059 `display' value."
9471060 (org--string-from-props string 'display 0 (length string)))
1061
1062 (defun org-string-width (string &optional pixels)
1063 "Return width of STRING when displayed in the current buffer.
1064 Return width in pixels when PIXELS is non-nil."
1065 (if (and (version< emacs-version "28") (not pixels))
1066 ;; FIXME: Fallback to old limited version, because
1067 ;; `window-pixel-width' is buggy in older Emacs.
1068 (org--string-width-1 string)
1069 ;; Wrap/line prefix will make `window-text-pizel-size' return too
1070 ;; large value including the prefix.
1071 (remove-text-properties 0 (length string)
1072 '(wrap-prefix t line-prefix t)
1073 string)
1074 ;; Face should be removed to make sure that all the string symbols
1075 ;; are using default face with constant width. Constant char width
1076 ;; is critical to get right string width from pixel width (not needed
1077 ;; when PIXELS are requested though).
1078 (unless pixels
1079 (remove-text-properties 0 (length string) '(face t) string))
1080 (let (;; We need to remove the folds to make sure that folded table
1081 ;; alignment is not messed up.
1082 (current-invisibility-spec
1083 (or (and (not (listp buffer-invisibility-spec))
1084 buffer-invisibility-spec)
1085 (let (result)
1086 (dolist (el buffer-invisibility-spec)
1087 (unless (or (memq el
1088 '(org-fold-drawer
1089 org-fold-block
1090 org-fold-outline))
1091 (and (listp el)
1092 (memq (car el)
1093 '(org-fold-drawer
1094 org-fold-block
1095 org-fold-outline))))
1096 (push el result)))
1097 result)))
1098 (current-char-property-alias-alist char-property-alias-alist))
1099 (with-temp-buffer
1100 (setq-local display-line-numbers nil)
1101 (setq-local buffer-invisibility-spec
1102 (if (listp current-invisibility-spec)
1103 (mapcar (lambda (el)
1104 ;; Consider ellipsis to have 0 width.
1105 ;; It is what Emacs 28+ does, but we have
1106 ;; to force it in earlier Emacs versions.
1107 (if (and (consp el) (cdr el))
1108 (list (car el))
1109 el))
1110 current-invisibility-spec)
1111 current-invisibility-spec))
1112 (setq-local char-property-alias-alist
1113 current-char-property-alias-alist)
1114 (let (pixel-width symbol-width)
1115 (with-silent-modifications
1116 (erase-buffer)
1117 (insert string)
1118 (setq pixel-width
1119 (if (get-buffer-window (current-buffer))
1120 (car (window-text-pixel-size
1121 nil (line-beginning-position) (point-max)))
1122 (let ((dedicatedp (window-dedicated-p))
1123 (oldbuffer (window-buffer)))
1124 (unwind-protect
1125 (progn
1126 ;; Do not throw error in dedicated windows.
1127 (set-window-dedicated-p nil nil)
1128 (set-window-buffer nil (current-buffer))
1129 (car (window-text-pixel-size
1130 nil (line-beginning-position) (point-max))))
1131 (set-window-buffer nil oldbuffer)
1132 (set-window-dedicated-p nil dedicatedp)))))
1133 (unless pixels
1134 (erase-buffer)
1135 (insert "a")
1136 (setq symbol-width
1137 (if (get-buffer-window (current-buffer))
1138 (car (window-text-pixel-size
1139 nil (line-beginning-position) (point-max)))
1140 (let ((dedicatedp (window-dedicated-p))
1141 (oldbuffer (window-buffer)))
1142 (unwind-protect
1143 (progn
1144 ;; Do not throw error in dedicated windows.
1145 (set-window-dedicated-p nil nil)
1146 (set-window-buffer nil (current-buffer))
1147 (car (window-text-pixel-size
1148 nil (line-beginning-position) (point-max))))
1149 (set-window-buffer nil oldbuffer)
1150 (set-window-dedicated-p nil dedicatedp)))))))
1151 (if pixels
1152 pixel-width
1153 (/ pixel-width symbol-width)))))))
1154
1155 (defmacro org-current-text-column ()
1156 "Like `current-column' but ignore display properties."
1157 `(string-width (buffer-substring-no-properties
1158 (line-beginning-position) (point))))
9481159
9491160 (defun org-not-nil (v)
9501161 "If V not nil, and also not the string \"nil\", then return V.
9591170 (and string
9601171 (if (and (string-prefix-p pre string)
9611172 (string-suffix-p post string))
962 (substring string (length pre) (- (length post)))
1173 (substring string (length pre)
1174 (and (not (string-equal "" post)) (- (length post))))
9631175 string)))
9641176
9651177 (defun org-strip-quotes (string)
10511263 "Find each %key of ALIST in TEMPLATE and replace it."
10521264 (let ((case-fold-search nil))
10531265 (dolist (entry (sort (copy-sequence alist)
1054 (lambda (a b) (< (length (car a)) (length (car b))))))
1266 ; Sort from longest key to shortest, so that
1267 ; "noweb-ref" and "tangle-mode" get processed
1268 ; before "noweb" and "tangle", respectively.
1269 (lambda (a b) (< (length (car b)) (length (car a))))))
10551270 (setq template
10561271 (replace-regexp-in-string
10571272 (concat "%" (regexp-quote (car entry)))
10721287 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
10731288 (when (and (cdr e) (string-match re (cdr e)))
10741289 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
1075 (safe "SREF"))
1290 (safe (copy-sequence "SREF")))
10761291 (add-text-properties 0 3 (list 'sref sref) safe)
10771292 (setcdr e (replace-match safe t t (cdr e)))))
10781293 (while (string-match re string)
10921307 rear-nonsticky t mouse-map t fontified t
10931308 org-emphasis t)
10941309 "Properties to remove when a string without properties is wanted.")
1310
1311 (defun org-buffer-substring-fontified (beg end)
1312 "Return fontified region between BEG and END."
1313 (when (bound-and-true-p jit-lock-mode)
1314 (when (text-property-not-all beg end 'fontified t)
1315 (save-excursion (save-match-data (font-lock-fontify-region beg end)))))
1316 (buffer-substring beg end))
1317
1318 (defun org-looking-at-fontified (re)
1319 "Call `looking-at' RE and make sure that the match is fontified."
1320 (prog1 (looking-at re)
1321 (when (bound-and-true-p jit-lock-mode)
1322 (when (text-property-not-all
1323 (match-beginning 0) (match-end 0)
1324 'fontified t)
1325 (save-excursion
1326 (save-match-data
1327 (font-lock-fontify-region (match-beginning 0)
1328 (match-end 0))))))))
10951329
10961330 (defsubst org-no-properties (s &optional restricted)
10971331 "Remove all text properties from string S.
11091343 0 (length string) (if props (append plist props) plist) string)
11101344 string)
11111345
1112 (defun org-make-parameter-alist (flat)
1113 ;; FIXME: "flat" is called a "plist"!
1114 "Return alist based on FLAT.
1115 FLAT is a list with alternating symbol names and values. The
1116 returned alist is a list of lists with the symbol name in car and
1117 the value in cadr."
1118 (when flat
1119 (cons (list (car flat) (cadr flat))
1120 (org-make-parameter-alist (cddr flat)))))
1346 (defun org-make-parameter-alist (plist)
1347 "Return alist based on PLIST.
1348 PLIST is a property list with alternating symbol names and values.
1349 The returned alist is a list of lists with the symbol name in `car'
1350 and the value in `cadr'."
1351 (when plist
1352 (cons (list (car plist) (cadr plist))
1353 (org-make-parameter-alist (cddr plist)))))
11211354
11221355 (defsubst org-get-at-bol (property)
11231356 "Get text property PROPERTY at the beginning of line."
1124 (get-text-property (point-at-bol) property))
1357 (get-text-property (line-beginning-position) property))
11251358
11261359 (defun org-get-at-eol (property n)
11271360 "Get text property PROPERTY at the end of line less N characters."
1128 (get-text-property (- (point-at-eol) n) property))
1361 (get-text-property (- (line-end-position) n) property))
11291362
11301363 (defun org-find-text-property-in-string (prop s)
11311364 "Return the first non-nil value of property PROP in string S."
11331366 (get-text-property (or (next-single-property-change 0 prop s) 0)
11341367 prop s)))
11351368
1369 ;; FIXME: move to org-fold?
11361370 (defun org-invisible-p (&optional pos folding-only)
11371371 "Non-nil if the character after POS is invisible.
11381372 If POS is nil, use `point' instead. When optional argument
11391373 FOLDING-ONLY is non-nil, only consider invisible parts due to
11401374 folding of a headline, a block or a drawer, i.e., not because of
11411375 fontification."
1142 (let ((value (get-char-property (or pos (point)) 'invisible)))
1376 (let ((value (invisible-p (or pos (point)))))
11431377 (cond ((not value) nil)
1144 (folding-only (memq value '(org-hide-block outline)))
1378 (folding-only (org-fold-folded-p (or pos (point))))
11451379 (t value))))
11461380
1147 (defun org-truely-invisible-p ()
1381 (defun org-truly-invisible-p ()
11481382 "Check if point is at a character currently not visible.
11491383 This version does not only check the character property, but also
11501384 `visible-mode'."
11601394 (backward-char 1))
11611395 (org-invisible-p)))
11621396
1397 (defun org-region-invisible-p (beg end)
1398 "Check if region if completely hidden."
1399 (org-with-wide-buffer
1400 (and (org-invisible-p beg)
1401 (org-invisible-p (org-fold-next-visibility-change beg end)))))
1402
11631403 (defun org-find-visible ()
11641404 "Return closest visible buffer position, or `point-max'."
11651405 (if (org-invisible-p)
1166 (next-single-char-property-change (point) 'invisible)
1406 (org-fold-next-visibility-change (point))
11671407 (point)))
11681408
11691409 (defun org-find-invisible ()
11701410 "Return closest invisible buffer position, or `point-max'."
11711411 (if (org-invisible-p)
11721412 (point)
1173 (next-single-char-property-change (point) 'invisible)))
1413 (org-fold-next-visibility-change (point))))
11741414
11751415
11761416 ;;; Time
11841424 ((numberp s) s)
11851425 ((stringp s)
11861426 (condition-case nil
1187 (float-time (apply #'encode-time (org-parse-time-string s)))
1427 (org-time-string-to-seconds s)
11881428 (error 0)))
11891429 (t 0)))
11901430
12171457 (let ((a (org-2ft a))
12181458 (b (org-2ft b)))
12191459 (and (> a 0) (> b 0) (\= a b))))
1460
1461 (defmacro org-encode-time (&rest time)
1462 "Compatibility and convenience helper for `encode-time'.
1463 TIME may be a 9 components list (SECONDS ... YEAR IGNORED DST ZONE)
1464 as the recommended way since Emacs-27 or 6 or 9 separate arguments
1465 similar to the only possible variant for Emacs-26 and earlier.
1466 6 elements list as the only argument causes wrong type argument till
1467 Emacs-29.
1468
1469 Warning: use -1 for DST to guess the actual value, nil means no
1470 daylight saving time and may be wrong at particular time.
1471
1472 DST value is ignored prior to Emacs-27. Since Emacs-27 DST value matters
1473 even when multiple arguments is passed to this macro and such
1474 behavior is different from `encode-time'. See
1475 Info node `(elisp)Time Conversion' for details and caveats,
1476 preferably the latest version."
1477 (if (version< emacs-version "27.1")
1478 (if (cdr time)
1479 `(encode-time ,@time)
1480 `(apply #'encode-time ,@time))
1481 (if (ignore-errors (with-no-warnings (encode-time '(0 0 0 1 1 1971))))
1482 (pcase (length time) ; Emacs-29 since d75e2c12eb
1483 (1 `(encode-time ,@time))
1484 ((or 6 9) `(encode-time (list ,@time)))
1485 (_ (error "`org-encode-time' may be called with 1, 6, or 9 arguments but %d given"
1486 (length time))))
1487 (pcase (length time)
1488 (1 `(encode-time ,@time))
1489 (6 `(encode-time (list ,@time nil -1 nil)))
1490 (9 `(encode-time (list ,@time)))
1491 (_ (error "`org-encode-time' may be called with 1, 6, or 9 arguments but %d given"
1492 (length time)))))))
12201493
12211494 (defun org-parse-time-string (s &optional nodefault)
12221495 "Parse Org time string S.
12411514 (string-to-number (match-string 4 s))
12421515 (string-to-number (match-string 3 s))
12431516 (string-to-number (match-string 2 s))
1244 nil nil nil))
1517 nil -1 nil))
12451518
12461519 (defun org-matcher-time (s)
12471520 "Interpret a time comparison value S as a floating point time.
12511524 \"<tomorrow>\", and \"<yesterday>\".
12521525
12531526 Return 0. if S is not recognized as a valid value."
1254 (let ((today (float-time (apply #'encode-time
1255 (append '(0 0 0) (nthcdr 3 (decode-time)))))))
1527 (let ((today (float-time (org-encode-time
1528 (append '(0 0 0) (nthcdr 3 (decode-time)))))))
12561529 (save-match-data
12571530 (cond
12581531 ((string= s "<now>") (float-time))
12981571 (message "Beginning of buffer")
12991572 (sit-for 1))))))
13001573
1574 (cl-defun org-knuth-hash (number &optional (base 32))
1575 "Calculate Knuth's multiplicative hash for NUMBER.
1576 BASE is the maximum bitcount.
1577 Credit: https://stackoverflow.com/questions/11871245/knuth-multiplicative-hash#41537995"
1578 (cl-assert (and (<= 0 base 32)))
1579 (ash (* number 2654435769) (- base 32)))
1580
13011581 (provide 'org-macs)
13021582
13031583 ;; Local variables:
00 ;;; org-mobile.el --- Code for Asymmetric Sync With a Mobile Device -*- lexical-binding: t; -*-
1 ;; Copyright (C) 2009-2021 Free Software Foundation, Inc.
1 ;; Copyright (C) 2009-2023 Free Software Foundation, Inc.
22 ;;
33 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
44 ;; Keywords: outlines, hypermedia, calendar, wp
5 ;; Homepage: https://orgmode.org
5 ;; URL: https://orgmode.org
66 ;;
77 ;; This file is part of GNU Emacs.
88 ;;
2929 ;; Appendix B of the Org manual. The code is not specific for the
3030 ;; iPhone and Android - any external viewer/flagging/editing
3131 ;; application that uses the same conventions could be used.
32
33 (require 'org-macs)
34 (org-assert-version)
3235
3336 (require 'cl-lib)
3437 (require 'org)
616619 ((looking-at "[ \t]*$")) ; keep empty lines
617620 ((looking-at "=+$")
618621 ;; remove underlining
619 (delete-region (point) (point-at-eol)))
622 (delete-region (point) (line-end-position)))
620623 ((get-text-property (point) 'org-agenda-structural-header)
621624 (setq in-date nil)
622625 (setq app (get-text-property (point) 'org-agenda-title-append))
636639 (get-text-property (point) 'org-marker)))
637640 (setq sexp (member (get-text-property (point) 'type)
638641 '("diary" "sexp")))
639 (if (setq pl (text-property-any (point) (point-at-eol) 'org-heading t))
642 (if (setq pl (text-property-any (point) (line-end-position) 'org-heading t))
640643 (progn
641644 (setq prefix (org-trim (buffer-substring
642645 (point) pl))
643646 line (org-trim (buffer-substring
644647 pl
645 (point-at-eol))))
646 (delete-region (point-at-bol) (point-at-eol))
648 (line-end-position))))
649 (delete-region (line-beginning-position) (line-end-position))
647650 (insert line "<before>" prefix "</before>")
648651 (beginning-of-line 1))
649652 (and (looking-at "[ \t]+") (replace-match "")))
856859 (org-mobile-timestamp-buffer (marker-buffer id-pos))
857860 (push (marker-buffer id-pos) buf-list))
858861 (unless (markerp id-pos)
859 (goto-char (+ 2 (point-at-bol)))
862 (goto-char (+ 2 (line-beginning-position)))
860863 (if (stringp id-pos)
861864 (insert id-pos " ")
862865 (insert "BAD REFERENCE "))
10631066 (progn
10641067 ;; Workaround a `org-insert-heading-respect-content' bug
10651068 ;; which prevents correct insertion when point is invisible
1066 (org-show-subtree)
1069 (org-fold-show-subtree)
10671070 (end-of-line 1)
10681071 (org-insert-heading-respect-content t)
10691072 (org-demote))
10921095 (org-archive-to-archive-sibling))
10931096
10941097 ((eq what 'body)
1095 (setq current (buffer-substring (min (1+ (point-at-eol)) (point-max))
1098 (setq current (buffer-substring (min (1+ (line-end-position)) (point-max))
10961099 (save-excursion (outline-next-heading)
10971100 (point))))
10981101 (if (not (string-match "\\S-" current)) (setq current nil))
00 ;;; org-mouse.el --- Better mouse support for Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2006-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2006-2023 Free Software Foundation, Inc.
33
44 ;; Author: Piotr Zielinski <piotr dot zielinski at gmail dot com>
55 ;; Maintainer: Carsten Dominik <carsten.dominik@gmail.com>
135135
136136 ;;; Code:
137137
138 (require 'org-macs)
139 (org-assert-version)
140
138141 (require 'org)
139142 (require 'cl-lib)
140143
183186 (defun org-mouse-re-search-line (regexp)
184187 "Search the current line for a given regular expression."
185188 (beginning-of-line)
186 (re-search-forward regexp (point-at-eol) t))
189 (re-search-forward regexp (line-end-position) t))
187190
188191 (defun org-mouse-end-headline ()
189192 "Go to the end of current headline (ignoring tags)."
207210 (interactive "@e \nP")
208211 (if (and (= (event-click-count event) 1)
209212 (or (not mark-active)
210 (sit-for (/ double-click-time 1000.0))))
213 (sit-for
214 (/ (if (fboundp 'mouse-double-click-time) ; Emacs >= 29
215 (mouse-double-click-time)
216 double-click-time)
217 1000.0))))
211218 (progn
212219 (select-window (posn-window (event-start event)))
213220 (when (not (org-mouse-mark-active))
216223 (sit-for 0))
217224 (if (functionp org-mouse-context-menu-function)
218225 (funcall org-mouse-context-menu-function event)
219 (if (fboundp 'mouse-menu-major-mode-map)
220 (popup-menu (mouse-menu-major-mode-map) event prefix)
221 (with-no-warnings ; don't warn about fallback, obsolete since 23.1
222 (mouse-major-mode-menu event prefix)))))
226 (popup-menu (mouse-menu-major-mode-map) event prefix)))
223227 (setq this-command 'mouse-save-then-kill)
224228 (mouse-save-then-kill event)))
225229
236240 (t :middle)))
237241
238242 (defun org-mouse-empty-line ()
239 "Return non-nil iff the line contains only white space."
243 "Return non-nil if the line contains only white space."
240244 (save-excursion (beginning-of-line) (looking-at "[ \t]*$")))
241245
242246 (defun org-mouse-next-heading ()
278282
279283 If SELECTED is nil, then all items are normal menu items. If
280284 SELECTED is a function, then each item is a checkbox, which is
281 enabled for a given keyword iff (funcall SELECTED keyword) return
285 enabled for a given keyword if (funcall SELECTED keyword) return
282286 non-nil. If SELECTED is neither nil nor a function, then the
283287 items are radio buttons. A radio button is enabled for the
284288 keyword `equal' to SELECTED.
294298 ((functionp itemformat) (funcall itemformat keyword))
295299 ((stringp itemformat) (format itemformat keyword))
296300 (t keyword))
297 (list 'funcall function keyword)
301 `(funcall #',function ,keyword)
298302 :style (cond
299303 ((null selected) t)
300304 ((functionp selected) 'toggle)
573577 (insert "+ "))
574578 (:end ; insert text here
575579 (skip-chars-backward " \t")
576 (kill-region (point) (point-at-eol))
580 (kill-region (point) (line-end-position))
577581 (unless (looking-back org-mouse-punctuation (line-beginning-position))
578582 (insert (concat org-mouse-punctuation " ")))))
579583 (insert text)
580584 (beginning-of-line))
581585
582 (defadvice dnd-insert-text (around org-mouse-dnd-insert-text activate)
586 (advice-add 'dnd-insert-text :around #'org--mouse-dnd-insert-text)
587 (defun org--mouse-dnd-insert-text (orig-fun window action text &rest args)
583588 (if (derived-mode-p 'org-mode)
584589 (org-mouse-insert-item text)
585 ad-do-it))
586
587 (defadvice dnd-open-file (around org-mouse-dnd-open-file activate)
590 (apply orig-fun window action text args)))
591
592 (advice-add 'dnd-open-file :around #'org--mouse-dnd-open-file)
593 (defun org--mouse-dnd-open-file (orig-fun uri &rest args)
588594 (if (derived-mode-p 'org-mode)
589595 (org-mouse-insert-item uri)
590 ad-do-it))
596 (apply orig-fun uri args)))
591597
592598 (defun org-mouse-match-closure (function)
593599 (let ((match (match-data t)))
893899 (1 `(face nil keymap ,org-mouse-map mouse-face highlight) prepend)))
894900 t))
895901
896 (defadvice org-open-at-point (around org-mouse-open-at-point activate)
897 (let ((context (org-context)))
898 (cond
899 ((assq :headline-stars context) (org-cycle))
900 ((assq :checkbox context) (org-toggle-checkbox))
901 ((assq :item-bullet context)
902 (let ((org-cycle-include-plain-lists t)) (org-cycle)))
903 ((org-footnote-at-reference-p) nil)
904 (t ad-do-it))))))
902 (advice-add 'org-open-at-point :around #'org--mouse-open-at-point)))
903
904 (defun org--mouse-open-at-point (orig-fun &rest args)
905 (let ((context (org-context)))
906 (cond
907 ((assq :headline-stars context) (org-cycle))
908 ((assq :checkbox context) (org-toggle-checkbox))
909 ((assq :item-bullet context)
910 (let ((org-cycle-include-plain-lists t)) (org-cycle)))
911 ((org-footnote-at-reference-p) nil)
912 (t (apply orig-fun args)))))
905913
906914 (defun org-mouse-move-tree-start (_event)
907915 (interactive "e")
966974 (interactive)
967975 (org-back-to-heading)
968976 (let ((minlevel 1000)
969 (replace-text (concat (match-string 0) "* ")))
977 (replace-text (concat (make-string (org-current-level) ?*) "* ")))
970978 (beginning-of-line 2)
971979 (save-excursion
972980 (while (not (or (eobp) (looking-at org-outline-regexp)))
984992 (defun org-mouse-do-remotely (command)
985993 ;; (org-agenda-check-no-diary)
986994 (when (get-text-property (point) 'org-marker)
987 (let* ((anticol (- (point-at-eol) (point)))
995 (let* ((anticol (- (line-end-position) (point)))
988996 (marker (get-text-property (point) 'org-marker))
989997 (buffer (marker-buffer marker))
990998 (pos (marker-position marker))
10021010 (with-current-buffer buffer
10031011 (widen)
10041012 (goto-char pos)
1005 (org-show-hidden-entry)
1013 (org-fold-show-hidden-entry)
10061014 (save-excursion
10071015 (and (outline-next-heading)
1008 (org-flag-heading nil))) ; show the next heading
1016 (org-fold-heading nil))) ; show the next heading
10091017 (org-back-to-heading)
10101018 (setq marker (point-marker))
1011 (goto-char (max (point-at-bol) (- (point-at-eol) anticol)))
1019 (goto-char (max (line-beginning-position) (- (line-end-position) anticol)))
10121020 (funcall command)
10131021 (message "_cmd: %S" org-mouse-cmd)
10141022 (message "this-command: %S" this-command)
00 ;;; org-num.el --- Dynamic Headlines Numbering -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2018-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2018-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6060
6161 ;;; Code:
6262
63 (require 'org-macs)
64 (org-assert-version)
65
6366 (require 'cl-lib)
6467 (require 'org-macs)
6568 (require 'org) ;Otherwise `org-num--comment-re' burps on `org-comment-string'
152155
153156 (defvar-local org-num--overlays nil
154157 "Ordered list of overlays used for numbering outlines.")
158 (put 'org-num--overlays 'permanent-local t)
155159
156160 (defvar-local org-num--skip-level nil
157161 "Level below which headlines from current tree are not numbered.
457461 (org-num-mode
458462 (unless (derived-mode-p 'org-mode)
459463 (user-error "Cannot activate headline numbering outside Org mode"))
464 (org-num--clear)
460465 (setq org-num--numbering nil)
461466 (setq org-num--overlays (nreverse (org-num--number-region nil nil)))
462467 (add-hook 'after-change-functions #'org-num--verify nil t)
00 ;;; org-pcomplete.el --- In-buffer Completion Code -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; John Wiegley <johnw at gnu dot org>
66 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88 ;;
99 ;; This file is part of GNU Emacs.
1010 ;;
2626 ;;;; Require other packages
2727
2828 (require 'org-macs)
29 (org-assert-version)
30
31 (require 'org-macs)
2932 (require 'org-compat)
3033 (require 'pcomplete)
3134
3235 (declare-function org-at-heading-p "org" (&optional ignored))
3336 (declare-function org-babel-combine-header-arg-lists "ob-core" (original &rest others))
34 (declare-function org-babel-get-src-block-info "ob-core" (&optional light datum))
37 (declare-function org-babel-get-src-block-info "ob-core" (&optional no-eval datum))
3538 (declare-function org-before-first-heading-p "org" ())
3639 (declare-function org-buffer-property-keys "org" (&optional specials defaults columns))
37 (declare-function org-element-at-point "org-element" ())
40 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
3841 (declare-function org-element-property "org-element" property element)
3942 (declare-function org-element-type "org-element" (element))
4043 (declare-function org-end-of-meta-data "org" (&optional full))
4649 (declare-function org-get-tags "org" (&optional pos local))
4750 (declare-function org-link-heading-search-string "ol" (&optional string))
4851 (declare-function org-tag-alist-to-string "org" (alist &optional skip-key))
52 (declare-function org-time-stamp-format "org" (&optional with-time inactive custom))
4953
5054 (defvar org-babel-common-header-args-w-values)
5155 (defvar org-current-tag-alist)
6670 (defvar org-property-re)
6771 (defvar org-startup-options)
6872 (defvar org-tag-re)
69 (defvar org-time-stamp-formats)
7073 (defvar org-todo-keywords-1)
7174 (defvar org-todo-line-regexp)
7275
226229
227230 (defun pcomplete/org-mode/file-option/date ()
228231 "Complete arguments for the #+DATE file option."
229 (pcomplete-here (list (format-time-string (car org-time-stamp-formats)))))
232 (pcomplete-here (list (format-time-string (org-time-stamp-format)))))
230233
231234 (defun pcomplete/org-mode/file-option/email ()
232235 "Complete arguments for the #+EMAIL file option."
360363 (pcomplete-uniquify-list tbl)))
361364 ;; When completing a bracketed link, i.e., "[[*", argument
362365 ;; starts at the star, so remove this character.
363 (substring pcomplete-stub 1))))
366 ;; Also, if the completion is done inside [[*head<point>]],
367 ;; drop the closing parentheses.
368 (replace-regexp-in-string
369 "\\]+$" ""
370 (substring pcomplete-stub 1)))))
364371
365372 (defun pcomplete/org-mode/tag ()
366373 "Complete a tag name. Omit tags already set."
420427 (symbol-plist
421428 'org-babel-load-languages)
422429 'custom-type)))))))
423 (let* ((info (org-babel-get-src-block-info 'light))
430 (let* ((info (org-babel-get-src-block-info 'no-eval))
424431 (lang (car info))
425432 (lang-headers (intern (concat "org-babel-header-args:" lang)))
426433 (headers (org-babel-combine-header-arg-lists
0 ;;; org-persist.el --- Persist cached data across Emacs sessions -*- lexical-binding: t; -*-
1
2 ;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
3
4 ;; Author: Ihor Radchenko <yantar92 at gmail dot com>
5 ;; Keywords: cache, storage
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23 ;;
24 ;; This file implements persistent cache storage across Emacs sessions.
25 ;; Both global and buffer-local data can be stored. This
26 ;; implementation is not meant to be used to store important data -
27 ;; all the caches should be safe to remove at any time.
28 ;;
29 ;; Example usage:
30 ;;
31 ;; 1. Temporarily cache Elisp symbol value to disk. Remove upon
32 ;; closing Emacs:
33 ;; (org-persist-write 'variable-symbol)
34 ;; (org-persist-read 'variable-symbol) ;; read the data later
35 ;; 2. Temporarily cache a remote URL file to disk. Remove upon
36 ;; closing Emacs:
37 ;; (org-persist-write 'url "https://static.fsf.org/common/img/logo-new.png")
38 ;; (org-persist-read 'url "https://static.fsf.org/common/img/logo-new.png")
39 ;; `org-persist-read' will return the cached file location or nil if cached file
40 ;; has been removed.
41 ;; 3. Temporarily cache a file, including TRAMP path to disk:
42 ;; (org-persist-write 'file "/path/to/file")
43 ;; 4. Cache file or URL while some other file exists.
44 ;; (org-persist-register '(url "https://static.fsf.org/common/img/logo-new.png") '(:file "/path to the other file") :expiry 'never :write-immediately t)
45 ;; or, if the other file is current buffer file
46 ;; (org-persist-register '(url "https://static.fsf.org/common/img/logo-new.png") (current-buffer) :expiry 'never :write-immediately t)
47 ;; 5. Cache value of a Elisp variable to disk. The value will be
48 ;; saved and restored automatically (except buffer-local
49 ;; variables).
50 ;; ;; Until `org-persist-default-expiry'
51 ;; (org-persist-register 'variable-symbol)
52 ;; ;; Specify expiry explicitly
53 ;; (org-persist-register 'variable-symbol :expiry 'never)
54 ;; ;; Save buffer-local variable (buffer-local will not be
55 ;; ;; autoloaded!)
56 ;; (org-persist-register 'org-element--cache (current-buffer))
57 ;; ;; Save buffer-local variable preserving circular links:
58 ;; (org-persist-register 'org-element--headline-cache (current-buffer)
59 ;; :inherit 'org-element--cache)
60 ;; 6. Load variable by side effects assigning variable symbol:
61 ;; (org-persist-load 'variable-symbol (current-buffer))
62 ;; 7. Version variable value:
63 ;; (org-persist-register '((elisp variable-symbol) (version "2.0")))
64 ;; 8. Cancel variable persistence:
65 ;; (org-persist-unregister 'variable-symbol 'all) ; in all buffers
66 ;; (org-persist-unregister 'variable-symbol) ;; global variable
67 ;; (org-persist-unregister 'variable-symbol (current-buffer)) ;; buffer-local
68 ;;
69 ;; Most common data type is variable data. However, other data types
70 ;; can also be stored.
71 ;;
72 ;; Persistent data is stored in individual files. Each of the files
73 ;; can contain a collection of related data, which is particularly
74 ;; useful when, say, several variables cross-reference each-other's
75 ;; data-cells and we want to preserve their circular structure.
76 ;;
77 ;; Each data collection can be associated with a local or remote file,
78 ;; its inode number, or contents hash. The persistent data collection
79 ;; can later be accessed using either file buffer, file, inode, or
80 ;; contents hash.
81 ;;
82 ;; The data collections can be versioned and removed upon expiry.
83 ;;
84 ;; In the code below I will use the following naming conventions:
85 ;; 1. Container :: a type of data to be stored
86 ;; Containers can store elisp variables, files, and version
87 ;; numbers. Each container can be customized with container
88 ;; options. For example, `elisp' container is customized with
89 ;; variable symbol. (elisp variable) is a container storing
90 ;; Lisp variable value. Similarly, (version "2.0") container
91 ;; will store version number.
92 ;; 2. Associated :: an object the container is associated with. The
93 ;; object can be a buffer, file, inode number, file contents hash,
94 ;; a generic key, or multiple of them. Associated can also be nil.
95 ;; 3. Data collection :: a list of containers linked to an associated
96 ;; object/objects. Each data collection can also have auxiliary
97 ;; records. Their only purpose is readability of the collection
98 ;; index.
99 ;; 4. Index file :: a file listing all the stored data collections.
100 ;; 5. Persist file :: a file holding data values or references to
101 ;; actual data values for a single data collection. This file
102 ;; contains an alist associating each data container in data
103 ;; collection with its value or a reference to the actual value.
104 ;;
105 ;; All the persistent data is stored in `org-persist-directory'. The data
106 ;; collections are listed in `org-persist-index-file' and the actual data is
107 ;; stored in UID-style subfolders.
108 ;;
109 ;; The `org-persist-index-file' stores the value of `org-persist--index'.
110 ;;
111 ;; Each collection is represented as a plist containing the following
112 ;; properties:
113 ;; - `:container' : list of data continers to be stored in single
114 ;; file;
115 ;; - `:persist-file': data file name;
116 ;; - `:associated' : list of associated objects;
117 ;; - `:last-access' : last date when the container has been accessed;
118 ;; - `:expiry' : list of expiry conditions.
119 ;; - all other keywords are ignored
120 ;;
121 ;; The available types of data containers are:
122 ;; 1. (file variable-symbol) or just variable-symbol :: Storing
123 ;; elisp variable data.
124 ;; 2. (file) :: Store a copy of the associated file preserving the
125 ;; extension.
126 ;; (file "/path/to/a/file") :: Store a copy of the file in path.
127 ;; 3. (version "version number") :: Version the data collection.
128 ;; If the stored collection has different version than "version
129 ;; number", disregard it.
130 ;; 4. (url) :: Store a downloaded copy of URL object.
131 ;;
132 ;; The data collections can expire, in which case they will be removed
133 ;; from the persistent storage at the end of Emacs session. The
134 ;; expiry condition can be set when saving/registering data
135 ;; containers. The expirty condition can be `never' - data will never
136 ;; expire; nil - data will expire at the end of current Emacs session;
137 ;; a number - data will expire after the number days from last access;
138 ;; a function - data will expire if the function, called with a single
139 ;; argument - collection, returns non-nil.
140 ;;
141 ;;
142 ;; Data collections associated with files will automatically expire
143 ;; when the file is removed. If the associated file is remote, the
144 ;; expiry is controlled by `org-persist-remote-files' instead.
145 ;;
146 ;; Data loading/writing can be more accurately controlled using
147 ;; `org-persist-before-write-hook', `org-persist-before-read-hook', and `org-persist-after-read-hook'.
148
149 ;;; Code:
150
151 (require 'org-macs)
152 (org-assert-version)
153
154 (require 'org-compat)
155 (require 'org-id)
156 (require 'xdg nil t)
157
158 (declare-function org-back-to-heading "org" (&optional invisible-ok))
159 (declare-function org-next-visible-heading "org" (arg))
160 (declare-function org-at-heading-p "org" (&optional invisible-not-ok))
161
162 ;; Silence byte-compiler (used in `org-persist--write-elisp-file').
163 (defvar pp-use-max-width)
164
165 (defconst org-persist--storage-version "3.1"
166 "Persistent storage layout version.")
167
168 (defgroup org-persist nil
169 "Persistent cache for Org mode."
170 :tag "Org persist"
171 :group 'org)
172
173 (defcustom org-persist-directory (expand-file-name
174 (org-file-name-concat
175 (let ((cache-dir (when (fboundp 'xdg-cache-home)
176 (xdg-cache-home))))
177 (if (or (seq-empty-p cache-dir)
178 (not (file-exists-p cache-dir))
179 (file-exists-p (org-file-name-concat
180 user-emacs-directory
181 "org-persist")))
182 user-emacs-directory
183 cache-dir))
184 "org-persist/"))
185 "Directory where the data is stored."
186 :group 'org-persist
187 :package-version '(Org . "9.6")
188 :type 'directory)
189
190 (defcustom org-persist-remote-files 100
191 "Whether to keep persistent data for remote files.
192
193 When this variable is nil, never save persistent data associated with
194 remote files. When t, always keep the data. When
195 `check-existence', contact remote server containing the file and only
196 keep the data when the file exists on the server. When a number, keep
197 up to that number persistent values for remote files.
198
199 Note that the last option `check-existence' may cause Emacs to show
200 password prompts to log in."
201 :group 'org-persist
202 :package-version '(Org . "9.6")
203 :type '(choice (const :tag "Never" nil)
204 (const :tag "Always" t)
205 (number :tag "Keep not more than X files")
206 (const :tag "Check if exist on remote" check-existence)))
207
208 (defcustom org-persist-default-expiry 30
209 "Default expiry condition for persistent data.
210
211 When this variable is nil, all the data vanishes at the end of Emacs
212 session. When `never', the data never vanishes. When a number, the
213 data is deleted that number days after last access. When a function,
214 it should be a function returning non-nil when the data is expired. The
215 function will be called with a single argument - collection."
216 :group 'org-persist
217 :package-version '(Org . "9.6")
218 :type '(choice (const :tag "Never" never)
219 (const :tag "Always" nil)
220 (number :tag "Keep N days")
221 (function :tag "Function")))
222
223 (defconst org-persist-index-file "index"
224 "File name used to store the data index.")
225
226 (defvar org-persist--disable-when-emacs-Q t
227 "Disable persistence when Emacs is called with -Q command line arg.
228 When non-nil, this sets `org-persist-directory' to temporary directory.
229
230 This variable must be set before loading org-persist library.")
231
232 (defvar org-persist-before-write-hook nil
233 "Abnormal hook ran before saving data.
234 The hook must accept the same arguments as `org-persist-write'.
235 The hooks will be evaluated until a hook returns non-nil.
236 If any of the hooks return non-nil, do not save the data.")
237
238 (defvar org-persist-before-read-hook nil
239 "Abnormal hook ran before reading data.
240 The hook must accept the same arguments as `org-persist-read'.
241 The hooks will be evaluated until a hook returns non-nil.
242 If any of the hooks return non-nil, do not read the data.")
243
244 (defvar org-persist-after-read-hook nil
245 "Abnormal hook ran after reading data.
246 The hook must accept the same arguments as `org-persist-read'.")
247
248 (defvar org-persist--index nil
249 "Global index.
250
251 The index is a list of plists. Each plist contains information about
252 persistent data storage. Each plist contains the following
253 properties:
254
255 - `:container' : list of data continers to be stored in single file
256 - `:persist-file': data file name
257 - `:associated' : list of associated objects
258 - `:last-access' : last date when the container has been read
259 - `:expiry' : list of expiry conditions
260 - all other keywords are ignored.")
261
262 (defvar org-persist--index-hash nil
263 "Hash table storing `org-persist--index'. Used for quick access.
264 They keys are conses of (container . associated).")
265
266 (defvar org-persist--report-time 0.5
267 "Whether to report read/write time.
268
269 When the value is a number, it is a threshold number of seconds. If
270 the read/write time of a single variable exceeds the threshold, a
271 message is displayed.
272
273 When the value is a non-nil non-number, always display the message.
274 When the value is nil, never display the message.")
275
276 ;;;; Common functions
277
278 (defun org-persist--display-time (duration format &rest args)
279 "Report DURATION according to FORMAT + ARGS message.
280 FORMAT and ARGS are passed to `message'."
281 (when (or (and org-persist--report-time
282 (numberp org-persist--report-time)
283 (>= duration org-persist--report-time))
284 (and org-persist--report-time
285 (not (numberp org-persist--report-time))))
286 (apply #'message
287 (format "org-persist: %s took %%.2f sec" format)
288 (append args (list duration)))))
289
290 (defun org-persist--read-elisp-file (&optional buffer-or-file)
291 "Read elisp data from BUFFER-OR-FILE or current buffer."
292 (unless buffer-or-file (setq buffer-or-file (current-buffer)))
293 (with-temp-buffer
294 (if (bufferp buffer-or-file)
295 (set-buffer buffer-or-file)
296 (insert-file-contents buffer-or-file))
297 (condition-case err
298 (let ((coding-system-for-read 'utf-8)
299 (read-circle t)
300 (start-time (float-time)))
301 ;; FIXME: Reading sometimes fails to read circular objects.
302 ;; I suspect that it happens when we have object reference
303 ;; #N# read before object definition #N=. If it is really
304 ;; so, it should be Emacs bug - either in `read' or in
305 ;; `prin1'. Meanwhile, just fail silently when `read'
306 ;; fails to parse the saved cache object.
307 (prog1
308 (read (current-buffer))
309 (org-persist--display-time
310 (- (float-time) start-time)
311 "Reading from %S" buffer-or-file)))
312 ;; Recover gracefully if index file is corrupted.
313 (error
314 ;; Remove problematic file.
315 (unless (bufferp buffer-or-file) (delete-file buffer-or-file))
316 ;; Do not report the known error to user.
317 (if (string-match-p "Invalid read syntax" (error-message-string err))
318 (message "Emacs reader failed to read data in %S. The error was: %S"
319 buffer-or-file (error-message-string err))
320 (warn "Emacs reader failed to read data in %S. The error was: %S"
321 buffer-or-file (error-message-string err)))
322 nil))))
323
324 (defun org-persist--write-elisp-file (file data &optional no-circular pp)
325 "Write elisp DATA to FILE."
326 (let ((print-circle (not no-circular))
327 print-level
328 print-length
329 print-quoted
330 (print-escape-control-characters t)
331 (print-escape-nonascii t)
332 (print-continuous-numbering t)
333 print-number-table
334 (start-time (float-time)))
335 (unless (file-exists-p (file-name-directory file))
336 (make-directory (file-name-directory file) t))
337 (with-temp-file file
338 (if pp
339 (let ((pp-use-max-width nil)) ; Emacs bug#58687
340 (pp data (current-buffer)))
341 (prin1 data (current-buffer))))
342 (org-persist--display-time
343 (- (float-time) start-time)
344 "Writing to %S" file)))
345
346 (defmacro org-persist-gc:generic (container collection)
347 "Garbage collect CONTAINER data from COLLECTION."
348 `(let* ((c (org-persist--normalize-container ,container))
349 (gc-func-symbol (intern (format "org-persist-gc:%s" (car c)))))
350 (unless (fboundp gc-func-symbol)
351 (error "org-persist: GC function %s not defined"
352 gc-func-symbol))
353 (funcall gc-func-symbol c ,collection)))
354
355 (defmacro org-persist--gc-expired-p (cnd collection)
356 "Check if expiry condition CND triggers for COLLECTION."
357 `(pcase ,cnd
358 (`nil t)
359 (`never nil)
360 ((pred numberp)
361 (when (plist-get ,collection :last-access)
362 (> (float-time) (+ (plist-get ,collection :last-access) (* ,cnd 24 60 60)))))
363 ((pred functionp)
364 (funcall ,cnd ,collection))
365 (_ (error "org-persist: Unsupported expiry type %S" ,cnd))))
366
367 ;;;; Working with index
368
369 (defmacro org-persist-collection-let (collection &rest body)
370 "Bind container and associated from COLLECTION and execute BODY."
371 (declare (debug (form body)) (indent 1))
372 `(with-no-warnings
373 (let* ((container (plist-get ,collection :container))
374 (associated (plist-get ,collection :associated))
375 (path (plist-get associated :file))
376 (inode (plist-get associated :inode))
377 (hash (plist-get associated :hash))
378 (key (plist-get associated :key)))
379 ;; Suppress "unused variable" warnings.
380 (ignore container associated path inode hash key)
381 ,@body)))
382
383 (defun org-persist--find-index (collection)
384 "Find COLLECTION in `org-persist--index'."
385 (org-persist-collection-let collection
386 (and org-persist--index-hash
387 (catch :found
388 (dolist (cont (cons container container))
389 (let (r)
390 (setq r (or (gethash (cons cont associated) org-persist--index-hash)
391 (and path (gethash (cons cont (list :file path)) org-persist--index-hash))
392 (and inode (gethash (cons cont (list :inode inode)) org-persist--index-hash))
393 (and hash (gethash (cons cont (list :hash hash)) org-persist--index-hash))
394 (and key (gethash (cons cont (list :key key)) org-persist--index-hash))))
395 (when r (throw :found r))))))))
396
397 (defun org-persist--add-to-index (collection &optional hash-only)
398 "Add or update COLLECTION in `org-persist--index'.
399 When optional HASH-ONLY is non-nil, only modify the hash table.
400 Return PLIST."
401 (org-persist-collection-let collection
402 (let ((existing (org-persist--find-index collection)))
403 (if existing
404 (progn
405 (plist-put existing :container container)
406 (plist-put (plist-get existing :associated) :file path)
407 (plist-put (plist-get existing :associated) :inode inode)
408 (plist-put (plist-get existing :associated) :hash hash)
409 (plist-put (plist-get existing :associated) :key key)
410 existing)
411 (unless hash-only (push collection org-persist--index))
412 (unless org-persist--index-hash (setq org-persist--index-hash (make-hash-table :test 'equal)))
413 (dolist (cont (cons container container))
414 (puthash (cons cont associated) collection org-persist--index-hash)
415 (when path (puthash (cons cont (list :file path)) collection org-persist--index-hash))
416 (when inode (puthash (cons cont (list :inode inode)) collection org-persist--index-hash))
417 (when hash (puthash (cons cont (list :hash inode)) collection org-persist--index-hash))
418 (when key (puthash (cons cont (list :key inode)) collection org-persist--index-hash)))
419 collection))))
420
421 (defun org-persist--remove-from-index (collection)
422 "Remove COLLECTION from `org-persist--index'."
423 (let ((existing (org-persist--find-index collection)))
424 (when existing
425 (org-persist-collection-let collection
426 (dolist (cont (cons container container))
427 (unless (listp (car container))
428 (org-persist-gc:generic cont collection))
429 (remhash (cons cont associated) org-persist--index-hash)
430 (when path (remhash (cons cont (list :file path)) org-persist--index-hash))
431 (when inode (remhash (cons cont (list :inode inode)) org-persist--index-hash))
432 (when hash (remhash (cons cont (list :hash hash)) org-persist--index-hash))
433 (when key (remhash (cons cont (list :key key)) org-persist--index-hash))))
434 (setq org-persist--index (delq existing org-persist--index)))))
435
436 (defun org-persist--get-collection (container &optional associated misc)
437 "Return or create collection used to store CONTAINER for ASSOCIATED.
438 When ASSOCIATED is nil, it is a global CONTAINER.
439 ASSOCIATED can also be a (:buffer buffer) or buffer, (:file file-path)
440 or file-path, (:inode inode), (:hash hash), or or (:key key).
441 MISC, if non-nil will be appended to the collection. It must be a plist."
442 (unless (and (listp container) (listp (car container)))
443 (setq container (list container)))
444 (setq associated (org-persist--normalize-associated associated))
445 (when (and misc (or (not (listp misc)) (= 1 (% (length misc) 2))))
446 (error "org-persist: Not a plist: %S" misc))
447 (or (org-persist--find-index
448 `( :container ,(org-persist--normalize-container container)
449 :associated ,associated))
450 (org-persist--add-to-index
451 (nconc
452 (list :container (org-persist--normalize-container container)
453 :persist-file
454 (replace-regexp-in-string "^.." "\\&/" (org-id-uuid))
455 :associated associated)
456 misc))))
457
458 ;;;; Reading container data.
459
460 (defun org-persist--normalize-container (container)
461 "Normalize CONTAINER representation into (type . settings)."
462 (if (and (listp container) (listp (car container)))
463 (mapcar #'org-persist--normalize-container container)
464 (pcase container
465 ((or `elisp `version `file `index `url)
466 (list container nil))
467 ((pred symbolp)
468 (list `elisp container))
469 (`(,(or `elisp `version `file `index `url) . ,_)
470 container)
471 (_ (error "org-persist: Unknown container type: %S" container)))))
472
473 (defvar org-persist--associated-buffer-cache (make-hash-table :weakness 'key)
474 "Buffer hash cache.")
475
476 (defun org-persist--normalize-associated (associated)
477 "Normalize ASSOCIATED representation into (:type value)."
478 (pcase associated
479 ((or (pred stringp) `(:file ,_))
480 (unless (stringp associated)
481 (setq associated (cadr associated)))
482 (let* ((rtn `(:file ,associated))
483 (inode (and (fboundp 'file-attribute-inode-number)
484 (file-attribute-inode-number
485 (file-attributes associated)))))
486 (when inode (plist-put rtn :inode inode))
487 rtn))
488 ((or (pred bufferp) `(:buffer ,_))
489 (unless (bufferp associated)
490 (setq associated (cadr associated)))
491 (let ((cached (gethash associated org-persist--associated-buffer-cache))
492 file inode hash)
493 (if (and cached (eq (buffer-modified-tick associated)
494 (car cached)))
495 (progn
496 (setq file (nth 1 cached)
497 inode (nth 2 cached)
498 hash (nth 3 cached)))
499 (setq file (buffer-file-name
500 (or (buffer-base-buffer associated)
501 associated)))
502 (setq inode (when (and file
503 (fboundp 'file-attribute-inode-number))
504 (file-attribute-inode-number
505 (file-attributes file))))
506 (setq hash (secure-hash 'md5 associated))
507 (puthash associated
508 (list (buffer-modified-tick associated)
509 file inode hash)
510 org-persist--associated-buffer-cache))
511 (let ((rtn `(:hash ,hash)))
512 (when file (setq rtn (plist-put rtn :file file)))
513 (when inode (setq rtn (plist-put rtn :inode inode)))
514 rtn)))
515 ((pred listp)
516 associated)
517 (_ (error "Unknown associated object %S" associated))))
518
519 (defmacro org-persist-read:generic (container reference-data collection)
520 "Read and return the data stored in CONTAINER.
521 REFERENCE-DATA is associated with CONTAINER in the persist file.
522 COLLECTION is the plist holding data collection."
523 `(let* ((c (org-persist--normalize-container ,container))
524 (read-func-symbol (intern (format "org-persist-read:%s" (car c)))))
525 (setf ,collection (plist-put ,collection :last-access (float-time)))
526 (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
527 (unless (fboundp read-func-symbol)
528 (error "org-persist: Read function %s not defined"
529 read-func-symbol))
530 (funcall read-func-symbol c ,reference-data ,collection)))
531
532 (defun org-persist-read:elisp (_ lisp-value __)
533 "Read elisp container and return LISP-VALUE."
534 lisp-value)
535
536 (defun org-persist-read:version (container _ __)
537 "Read version CONTAINER."
538 (cadr container))
539
540 (defun org-persist-read:file (_ path __)
541 "Read file container from PATH."
542 (when (and path (file-exists-p (org-file-name-concat org-persist-directory path)))
543 (org-file-name-concat org-persist-directory path)))
544
545 (defun org-persist-read:url (_ path __)
546 "Read file container from PATH."
547 (when (and path (file-exists-p (org-file-name-concat org-persist-directory path)))
548 (org-file-name-concat org-persist-directory path)))
549
550 (defun org-persist-read:index (cont index-file _)
551 "Read index container CONT from INDEX-FILE."
552 (when (file-exists-p index-file)
553 (let ((index (org-persist--read-elisp-file index-file)))
554 (when index
555 (catch :found
556 (dolist (collection index)
557 (org-persist-collection-let collection
558 (when (and (not associated)
559 (pcase container
560 (`((index ,version))
561 (equal version (cadr cont)))
562 (_ nil)))
563 (throw :found index)))))))))
564
565 ;;;; Applying container data for side effects.
566
567 (defmacro org-persist-load:generic (container reference-data collection)
568 "Load the data stored in CONTAINER for side effects.
569 REFERENCE-DATA is associated with CONTAINER in the persist file.
570 COLLECTION is the plist holding data collection."
571 `(let* ((container (org-persist--normalize-container ,container))
572 (load-func-symbol (intern (format "org-persist-load:%s" (car container)))))
573 (setf ,collection (plist-put ,collection :last-access (float-time)))
574 (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
575 (unless (fboundp load-func-symbol)
576 (error "org-persist: Load function %s not defined"
577 load-func-symbol))
578 (funcall load-func-symbol container ,reference-data ,collection)))
579
580 (defun org-persist-load:elisp (container lisp-value collection)
581 "Assign elisp CONTAINER in COLLECTION LISP-VALUE."
582 (let ((lisp-symbol (cadr container))
583 (buffer (when (plist-get (plist-get collection :associated) :file)
584 (get-file-buffer (plist-get (plist-get collection :associated) :file)))))
585 (if buffer
586 (with-current-buffer buffer
587 (make-variable-buffer-local lisp-symbol)
588 (set lisp-symbol lisp-value))
589 (set lisp-symbol lisp-value))))
590
591 (defalias 'org-persist-load:version #'org-persist-read:version)
592 (defalias 'org-persist-load:file #'org-persist-read:file)
593
594 (defun org-persist-load:index (container index-file _)
595 "Load `org-persist--index' from INDEX-FILE according to CONTAINER."
596 (unless org-persist--index
597 (setq org-persist--index (org-persist-read:index container index-file nil))
598 (setq org-persist--index-hash nil)
599 (if org-persist--index
600 (mapc (lambda (collection) (org-persist--add-to-index collection 'hash)) org-persist--index)
601 (setq org-persist--index nil)
602 (when (file-exists-p org-persist-directory)
603 (dolist (file (directory-files org-persist-directory 'absolute
604 "\\`[^.][^.]"))
605 (if (file-directory-p file)
606 (delete-directory file t)
607 (delete-file file))))
608 (plist-put (org-persist--get-collection container) :expiry 'never))))
609
610 (defun org-persist--load-index ()
611 "Load `org-persist--index."
612 (org-persist-load:index
613 `(index ,org-persist--storage-version)
614 (org-file-name-concat org-persist-directory org-persist-index-file)
615 nil))
616
617 ;;;; Writing container data
618
619 (defmacro org-persist-write:generic (container collection)
620 "Write CONTAINER in COLLECTION."
621 `(let* ((c (org-persist--normalize-container ,container))
622 (write-func-symbol (intern (format "org-persist-write:%s" (car c)))))
623 (setf ,collection (plist-put ,collection :last-access (float-time)))
624 (setf ,collection (plist-put ,collection :last-access-hr (format-time-string "%FT%T%z" (float-time))))
625 (unless (fboundp write-func-symbol)
626 (error "org-persist: Write function %s not defined"
627 write-func-symbol))
628 (funcall write-func-symbol c ,collection)))
629
630 (defun org-persist-write:elisp (container collection)
631 "Write elisp CONTAINER according to COLLECTION."
632 (if (and (plist-get (plist-get collection :associated) :file)
633 (get-file-buffer (plist-get (plist-get collection :associated) :file)))
634 (let ((buf (get-file-buffer (plist-get (plist-get collection :associated) :file))))
635 ;; FIXME: There is `buffer-local-boundp' introduced in Emacs 28.
636 ;; Not using it yet to keep backward compatibility.
637 (condition-case nil
638 (buffer-local-value (cadr container) buf)
639 (void-variable nil)))
640 (when (boundp (cadr container))
641 (symbol-value (cadr container)))))
642
643 (defalias 'org-persist-write:version #'ignore)
644
645 (defun org-persist-write:file (c collection)
646 "Write file container C according to COLLECTION."
647 (org-persist-collection-let collection
648 (when (or (and path (file-exists-p path))
649 (and (stringp (cadr c)) (file-exists-p (cadr c))))
650 (when (and (stringp (cadr c)) (file-exists-p (cadr c)))
651 (setq path (cadr c)))
652 (let* ((persist-file (plist-get collection :persist-file))
653 (ext (file-name-extension path))
654 (file-copy (org-file-name-concat
655 org-persist-directory
656 (format "%s-%s.%s" persist-file (md5 path) ext))))
657 (unless (file-exists-p file-copy)
658 (unless (file-exists-p (file-name-directory file-copy))
659 (make-directory (file-name-directory file-copy) t))
660 (copy-file path file-copy 'overwrite))
661 (format "%s-%s.%s" persist-file (md5 path) ext)))))
662
663 (defun org-persist-write:url (c collection)
664 "Write url container C according to COLLECTION."
665 (org-persist-collection-let collection
666 (when (or path (cadr c))
667 (when (cadr c) (setq path (cadr c)))
668 (let* ((persist-file (plist-get collection :persist-file))
669 (ext (file-name-extension path))
670 (file-copy (org-file-name-concat
671 org-persist-directory
672 (format "%s-%s.%s" persist-file (md5 path) ext))))
673 (unless (file-exists-p file-copy)
674 (unless (file-exists-p (file-name-directory file-copy))
675 (make-directory (file-name-directory file-copy) t))
676 (if (org--should-fetch-remote-resource-p path)
677 (url-copy-file path file-copy 'overwrite)
678 (error "The remote resource %S is considered unsafe, and will not be downloaded."
679 path)))
680 (format "%s-%s.%s" persist-file (md5 path) ext)))))
681
682 (defun org-persist-write:index (container _)
683 "Write index CONTAINER."
684 (org-persist--get-collection container)
685 (unless (file-exists-p org-persist-directory)
686 (make-directory org-persist-directory))
687 (unless (file-exists-p org-persist-directory)
688 (warn "Failed to create org-persist storage in %s."
689 org-persist-directory)
690 (let ((dir (directory-file-name
691 (file-name-as-directory org-persist-directory))))
692 (while (and (not (file-exists-p dir))
693 (not (equal dir (setq dir (directory-file-name
694 (file-name-directory dir)))))))
695 (unless (file-writable-p dir)
696 (message "Missing write access rights to org-persist-directory: %S"
697 org-persist-directory))))
698 (when (file-exists-p org-persist-directory)
699 (org-persist--write-elisp-file
700 (org-file-name-concat org-persist-directory org-persist-index-file)
701 org-persist--index
702 t t)
703 (org-file-name-concat org-persist-directory org-persist-index-file)))
704
705 (defun org-persist--save-index ()
706 "Save `org-persist--index."
707 (org-persist-write:index
708 `(index ,org-persist--storage-version) nil))
709
710 ;;;; Public API
711
712 (cl-defun org-persist-register (container &optional associated &rest misc
713 &key inherit
714 &key (expiry org-persist-default-expiry)
715 &key (write-immediately nil)
716 &allow-other-keys)
717 "Register CONTAINER in ASSOCIATED to be persistent across Emacs sessions.
718 Optional key INHERIT makes CONTAINER dependent on another container.
719 Such dependency means that data shared between variables will be
720 preserved (see elisp#Circular Objects).
721 Optional key EXPIRY will set the expiry condition of the container.
722 It can be `never', nil - until end of session, a number of days since
723 last access, or a function accepting a single argument - collection.
724 EXPIRY key has no effect when INHERIT is non-nil.
725 Optional key WRITE-IMMEDIATELY controls whether to save the container
726 data immediately.
727 MISC will be appended to the collection. It must be alternating :KEY
728 VALUE pairs.
729 When WRITE-IMMEDIATELY is non-nil, the return value will be the same
730 with `org-persist-write'."
731 (unless org-persist--index (org-persist--load-index))
732 (setq container (org-persist--normalize-container container))
733 (when inherit
734 (setq inherit (org-persist--normalize-container inherit))
735 (let ((inherited-collection (org-persist--get-collection inherit associated))
736 new-collection)
737 (unless (member container (plist-get inherited-collection :container))
738 (setq new-collection
739 (plist-put (copy-sequence inherited-collection) :container
740 (cons container (plist-get inherited-collection :container))))
741 (org-persist--remove-from-index inherited-collection)
742 (org-persist--add-to-index new-collection))))
743 (let ((collection (org-persist--get-collection container associated misc)))
744 (when (and expiry (not inherit))
745 (when expiry (plist-put collection :expiry expiry))))
746 (when (or (bufferp associated) (bufferp (plist-get associated :buffer)))
747 (with-current-buffer (if (bufferp associated)
748 associated
749 (plist-get associated :buffer))
750 (add-hook 'kill-buffer-hook #'org-persist-write-all-buffer nil 'local)))
751 (when write-immediately (org-persist-write container associated)))
752
753 (defun org-persist-unregister (container &optional associated)
754 "Unregister CONTAINER in ASSOCIATED to be persistent.
755 When ASSOCIATED is `all', unregister CONTAINER everywhere."
756 (unless org-persist--index (org-persist--load-index))
757 (setq container (org-persist--normalize-container container))
758 (if (eq associated 'all)
759 (mapc (lambda (collection)
760 (when (member container (plist-get collection :container))
761 (org-persist-unregister container (plist-get collection :associated))))
762 org-persist--index)
763 (setq associated (org-persist--normalize-associated associated))
764 (let ((collection (org-persist--find-index `(:container ,container :associated ,associated))))
765 (when collection
766 (if (= (length (plist-get collection :container)) 1)
767 (org-persist--remove-from-index collection)
768 (plist-put collection :container
769 (remove container (plist-get collection :container)))
770 (org-persist--add-to-index collection))))))
771
772 (defvar org-persist--write-cache (make-hash-table :test #'equal)
773 "Hash table storing as-written data objects.
774
775 This data is used to avoid reading the data multiple times.")
776 (defun org-persist-read (container &optional associated hash-must-match load?)
777 "Restore CONTAINER data for ASSOCIATED.
778 When HASH-MUST-MATCH is non-nil, do not restore data if hash for
779 ASSOCIATED file or buffer does not match.
780 ASSOCIATED can be a plist, a buffer, or a string.
781 A buffer is treated as (:buffer ASSOCIATED).
782 A string is treated as (:file ASSOCIATED).
783 When LOAD? is non-nil, load the data instead of reading."
784 (unless org-persist--index (org-persist--load-index))
785 (setq associated (org-persist--normalize-associated associated))
786 (setq container (org-persist--normalize-container container))
787 (let* ((collection (org-persist--find-index `(:container ,container :associated ,associated)))
788 (persist-file
789 (when collection
790 (org-file-name-concat
791 org-persist-directory
792 (plist-get collection :persist-file))))
793 (data nil))
794 (when (and collection
795 (file-exists-p persist-file)
796 (or (not (plist-get collection :expiry)) ; current session
797 (not (org-persist--gc-expired-p
798 (plist-get collection :expiry) collection)))
799 (or (not hash-must-match)
800 (and (plist-get associated :hash)
801 (equal (plist-get associated :hash)
802 (plist-get (plist-get collection :associated) :hash)))))
803 (unless (seq-find (lambda (v)
804 (run-hook-with-args-until-success 'org-persist-before-read-hook v associated))
805 (plist-get collection :container))
806 (setq data (or (gethash persist-file org-persist--write-cache)
807 (org-persist--read-elisp-file persist-file)))
808 (when data
809 (cl-loop for container in (plist-get collection :container)
810 with result = nil
811 do
812 (if load?
813 (push (org-persist-load:generic container (alist-get container data nil nil #'equal) collection) result)
814 (push (org-persist-read:generic container (alist-get container data nil nil #'equal) collection) result))
815 (run-hook-with-args 'org-persist-after-read-hook container associated)
816 finally return (if (= 1 (length result)) (car result) result)))))))
817
818 (defun org-persist-load (container &optional associated hash-must-match)
819 "Load CONTAINER data for ASSOCIATED.
820 The arguments have the same meaning as in `org-persist-read'."
821 (org-persist-read container associated hash-must-match t))
822
823 (defun org-persist-load-all (&optional associated)
824 "Restore all the persistent data associated with ASSOCIATED."
825 (unless org-persist--index (org-persist--load-index))
826 (setq associated (org-persist--normalize-associated associated))
827 (let (all-containers)
828 (dolist (collection org-persist--index)
829 (when collection
830 (cl-pushnew (plist-get collection :container) all-containers :test #'equal)))
831 (dolist (container all-containers)
832 (condition-case err
833 (org-persist-load container associated t)
834 (error
835 (message "%s. Deleting bad index entry." err)
836 (org-persist--remove-from-index (org-persist--find-index `(:container ,container :associated ,associated)))
837 nil)))))
838
839 (defun org-persist-load-all-buffer ()
840 "Call `org-persist-load-all' in current buffer."
841 (org-persist-load-all (current-buffer)))
842
843 (defun org-persist-write (container &optional associated ignore-return)
844 "Save CONTAINER according to ASSOCIATED.
845 ASSOCIATED can be a plist, a buffer, or a string.
846 A buffer is treated as (:buffer ASSOCIATED).
847 A string is treated as (:file ASSOCIATED).
848 The return value is nil when writing fails and the written value (as
849 returned by `org-persist-read') on success.
850 When IGNORE-RETURN is non-nil, just return t on success without calling
851 `org-persist-read'."
852 (setq associated (org-persist--normalize-associated associated))
853 ;; Update hash
854 (when (and (plist-get associated :file)
855 (plist-get associated :hash)
856 (get-file-buffer (plist-get associated :file)))
857 (setq associated (org-persist--normalize-associated (get-file-buffer (plist-get associated :file)))))
858 (let ((collection (org-persist--get-collection container associated)))
859 (setf collection (plist-put collection :associated associated))
860 (unless (or
861 ;; Prevent data leakage from encrypted files.
862 ;; We do it in somewhat paranoid manner and do not
863 ;; allow anything related to encrypted files to be
864 ;; written.
865 (and (plist-get associated :file)
866 (string-match-p epa-file-name-regexp (plist-get associated :file)))
867 (seq-find (lambda (v)
868 (run-hook-with-args-until-success 'org-persist-before-write-hook v associated))
869 (plist-get collection :container)))
870 (when (or (file-exists-p org-persist-directory) (org-persist--save-index))
871 (let ((file (org-file-name-concat org-persist-directory (plist-get collection :persist-file)))
872 (data (mapcar (lambda (c) (cons c (org-persist-write:generic c collection)))
873 (plist-get collection :container))))
874 (puthash file data org-persist--write-cache)
875 (org-persist--write-elisp-file file data)
876 (or ignore-return (org-persist-read container associated)))))))
877
878 (defun org-persist-write-all (&optional associated)
879 "Save all the persistent data.
880 When ASSOCIATED is non-nil, only save the matching data."
881 (unless org-persist--index (org-persist--load-index))
882 (setq associated (org-persist--normalize-associated associated))
883 (if
884 (and (equal 1 (length org-persist--index))
885 ;; The single collection only contains a single container
886 ;; in the container list.
887 (equal 1 (length (plist-get (car org-persist--index) :container)))
888 ;; The container is an `index' container.
889 (eq 'index (caar (plist-get (car org-persist--index) :container)))
890 (or (not (file-exists-p org-persist-directory))
891 (org-directory-empty-p org-persist-directory)))
892 ;; Do not write anything, and clear up `org-persist-directory' to reduce
893 ;; clutter.
894 (when (and (file-exists-p org-persist-directory)
895 (org-directory-empty-p org-persist-directory))
896 (delete-directory org-persist-directory))
897 ;; Write the data.
898 (let (all-containers)
899 (dolist (collection org-persist--index)
900 (if associated
901 (when collection
902 (cl-pushnew (plist-get collection :container) all-containers :test #'equal))
903 (condition-case err
904 (org-persist-write (plist-get collection :container) (plist-get collection :associated) t)
905 (error
906 (message "%s. Deleting bad index entry." err)
907 (org-persist--remove-from-index collection)
908 nil))))
909 (dolist (container all-containers)
910 (let ((collection (org-persist--find-index `(:container ,container :associated ,associated))))
911 (when collection
912 (condition-case err
913 (org-persist-write container associated t)
914 (error
915 (message "%s. Deleting bad index entry." err)
916 (org-persist--remove-from-index collection)
917 nil))))))))
918
919 (defun org-persist-write-all-buffer ()
920 "Call `org-persist-write-all' in current buffer.
921 Do nothing in an indirect buffer."
922 (unless (buffer-base-buffer (current-buffer))
923 (org-persist-write-all (current-buffer))))
924
925 (defalias 'org-persist-gc:elisp #'ignore)
926 (defalias 'org-persist-gc:index #'ignore)
927
928 (defun org-persist-gc:file (container collection)
929 "Garbage collect file CONTAINER in COLLECTION."
930 (let ((file (org-persist-read container (plist-get collection :associated))))
931 (when (file-exists-p file)
932 (delete-file file))))
933
934 (defun org-persist-gc:url (container collection)
935 "Garbage collect url CONTAINER in COLLECTION."
936 (let ((file (org-persist-read container (plist-get collection :associated))))
937 (when (file-exists-p file)
938 (delete-file file))))
939
940 (defmacro org-persist--gc-persist-file (persist-file)
941 "Garbage collect PERSIST-FILE."
942 `(when (file-exists-p ,persist-file)
943 (delete-file ,persist-file)
944 (when (org-directory-empty-p (file-name-directory ,persist-file))
945 (delete-directory (file-name-directory ,persist-file)))))
946
947 (defun org-persist-gc ()
948 "Remove expired or unregistered containers.
949 Also, remove containers associated with non-existing files."
950 (let (new-index (remote-files-num 0))
951 (dolist (collection org-persist--index)
952 (let* ((file (plist-get (plist-get collection :associated) :file))
953 (file-remote (when file (file-remote-p file)))
954 (persist-file (when (plist-get collection :persist-file)
955 (org-file-name-concat
956 org-persist-directory
957 (plist-get collection :persist-file))))
958 (expired? (org-persist--gc-expired-p
959 (plist-get collection :expiry) collection)))
960 (when persist-file
961 (when file
962 (when file-remote (cl-incf remote-files-num))
963 (unless (if (not file-remote)
964 (file-exists-p file)
965 (pcase org-persist-remote-files
966 ('t t)
967 ('check-existence
968 (file-exists-p file))
969 ((pred numberp)
970 (<= org-persist-remote-files remote-files-num))
971 (_ nil)))
972 (setq expired? t)))
973 (if expired?
974 (org-persist--gc-persist-file persist-file)
975 (push collection new-index)))))
976 (setq org-persist--index (nreverse new-index))))
977
978 (defun org-persist-clear-storage-maybe ()
979 "Clear `org-persist-directory' according to `org-persist--disable-when-emacs-Q'.
980
981 When `org-persist--disable-when-emacs-Q' is non-nil and Emacs is called with -Q
982 command line argument, `org-persist-directory' is created in potentially public
983 system temporary directory. Remove everything upon existing Emacs in
984 such scenario."
985 (when (and org-persist--disable-when-emacs-Q
986 ;; FIXME: This is relying on undocumented fact that
987 ;; Emacs sets `user-init-file' to nil when loaded with
988 ;; "-Q" argument.
989 (not user-init-file)
990 (file-exists-p org-persist-directory))
991 (delete-directory org-persist-directory 'recursive)))
992
993 ;; Point to temp directory when `org-persist--disable-when-emacs-Q' is set.
994 (when (and org-persist--disable-when-emacs-Q
995 ;; FIXME: This is relying on undocumented fact that
996 ;; Emacs sets `user-init-file' to nil when loaded with
997 ;; "-Q" argument.
998 (not user-init-file))
999 (setq org-persist-directory
1000 (make-temp-file "org-persist-" 'dir)))
1001
1002 ;; Automatically write the data, but only when we have write access.
1003 (let ((dir (directory-file-name
1004 (file-name-as-directory org-persist-directory))))
1005 (while (and (not (file-exists-p dir))
1006 (not (equal dir (setq dir (directory-file-name
1007 (file-name-directory dir)))))))
1008 (if (not (file-writable-p dir))
1009 (message "Missing write access rights to org-persist-directory: %S"
1010 org-persist-directory)
1011 (add-hook 'kill-emacs-hook #'org-persist-clear-storage-maybe) ; Run last.
1012 (add-hook 'kill-emacs-hook #'org-persist-write-all)
1013 ;; `org-persist-gc' should run before `org-persist-write-all'.
1014 ;; So we are adding the hook after `org-persist-write-all'.
1015 (add-hook 'kill-emacs-hook #'org-persist-gc)))
1016
1017 (add-hook 'after-init-hook #'org-persist-load-all)
1018
1019 (provide 'org-persist)
1020
1021 ;;; org-persist.el ends here
00 ;;; org-plot.el --- Support for Plotting from Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2008-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2008-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Eric Schulte <schulte dot eric at gmail dot com>
5 ;; Maintainer: TEC <tecosaur@gmail.com>
5 ;; Maintainer: TEC <orgmode@tec.tecosaur.net>
66 ;; Keywords: tables, plotting
7 ;; Homepage: https://orgmode.org
7 ;; URL: https://orgmode.org
88 ;;
99 ;; This file is part of GNU Emacs.
1010 ;;
2929 ;; feature suggestions
3030
3131 ;;; Code:
32
33 (require 'org-macs)
34 (org-assert-version)
3235
3336 (require 'cl-lib)
3437 (require 'org)
271274 for k in keys collect
272275 (cons k (funcall function (lookup k alist1) (lookup k alist2))))))
273276
274 (defun org--plot/item-frequencies (values &optional normalise)
277 (defun org--plot/item-frequencies (values &optional normalize)
275278 "Return an alist indicating the frequency of values in VALUES list.
276 When NORMALISE is non-nil, the count is divided by the number of values."
277 (let ((normaliser (if normalise (float (length values)) 1)))
279 When NORMALIZE is non-nil, the count is divided by the number of values."
280 (let ((normaliser (if normalize (float (length values)) 1)))
278281 (cl-loop for (n . m) in (seq-group-by #'identity values)
279282 collect (cons n (/ (length m) normaliser)))))
280283
281284 (defun org--plot/prime-factors (value)
282 "Return the prime decomposition of VALUE, e.g. for 12, '(3 2 2)."
285 "Return the prime decomposition of VALUE, e.g. for 12, (3 2 2)."
283286 (let ((factors '(1)) (i 1))
284287 (while (/= 1 value)
285288 (setq i (1+ i))
289292 (setq i (1- i))
290293 ))
291294 (cl-subseq factors 0 -1)))
295
296 (defgroup org-plot nil
297 "Options for plotting in Org mode."
298 :tag "Org Plot"
299 :group 'org)
292300
293301 (defcustom org-plot/gnuplot-script-preamble ""
294302 "String of function to be inserted before the gnuplot plot command is run.
620628 "Find any overlays for IMG-FILE in the current Org buffer, and refresh them."
621629 (dolist (img-overlay org-inline-image-overlays)
622630 (when (string= img-file (plist-get (cdr (overlay-get img-overlay 'display)) :file))
623 (when (file-exists-p img-file)
624 (image-refresh (overlay-get img-overlay 'display))))))
631 (when (and (file-exists-p img-file)
632 (fboundp 'image-flush))
633 (image-flush (overlay-get img-overlay 'display))))))
625634
626635 ;;-----------------------------------------------------------------------------
627636 ;; facade functions
666675 (num-cols (length (if (eq (nth 0 table) 'hline) (nth 1 table)
667676 (nth 0 table))))
668677 (type (assoc (plist-get params :plot-type)
669 org-plot/preset-plot-types)))
678 org-plot/preset-plot-types))
679 gnuplot-script)
670680
671681 (unless type
672682 (user-error "Org-plot type `%s' is undefined" (plist-get params :plot-type)))
681691 (looking-at "[[:space:]]*#\\+"))
682692 (setf params (org-plot/collect-options params))))
683693 ;; Dump table to datafile
684 (if-let ((dump-func (plist-get type :data-dump)))
685 (funcall dump-func table data-file num-cols params)
686 (org-plot/gnuplot-to-data table data-file params))
694 (let ((dump-func (plist-get type :data-dump)))
695 (if dump-func
696 (funcall dump-func table data-file num-cols params)
697 (org-plot/gnuplot-to-data table data-file params)))
687698 ;; Check type of ind column (timestamp? text?)
688699 (when (plist-get params :check-ind-type)
689700 (let* ((ind (1- (plist-get params :ind)))
699710 ind-column))
700711 (plist-put params :textind t))))) ; ind holds text
701712 ;; Write script.
713 (setq gnuplot-script
714 (org-plot/gnuplot-script
715 table data-file num-cols params (plist-get params :script)))
702716 (with-temp-buffer
703717 (if (plist-get params :script) ; user script
704 (progn (insert
705 (org-plot/gnuplot-script table data-file num-cols params t))
706 (insert "\n")
718 (progn (insert gnuplot-script "\n")
707719 (insert-file-contents (plist-get params :script))
708720 (goto-char (point-min))
709721 (while (re-search-forward "\\$datafile" nil t)
710722 (replace-match data-file nil nil)))
711 (insert (org-plot/gnuplot-script table data-file num-cols params)))
723 (insert gnuplot-script))
712724 ;; Graph table.
713725 (gnuplot-mode)
714726 (condition-case nil
00 ;;; org-protocol.el --- Intercept Calls from Emacsclient to Trigger Custom Actions -*- lexical-binding: t; -*-
11 ;;
2 ;; Copyright (C) 2008-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2008-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Authors: Bastien Guerry <bzg@gnu.org>
55 ;; Daniel M German <dmg AT uvic DOT org>
4141 ;;
4242 ;; 1.) Add this to your init file (.emacs probably):
4343 ;;
44 ;; (add-to-list 'load-path "/path/to/org-protocol/")
4544 ;; (require 'org-protocol)
4645 ;;
4746 ;; 3.) Ensure emacs-server is up and running.
6564 ;;
6665 ;;
6766 ;; As of March 2009 Firefox users follow the steps documented on
68 ;; http://kb.mozillazine.org/Register_protocol, Opera setup is described here:
67 ;; https://kb.mozillazine.org/Register_protocol, Opera setup is described here:
6968 ;; http://www.opera.com/support/kb/view/535/
7069 ;;
7170 ;;
128127 ;;
129128 ;;; Code:
130129
130 (require 'org-macs)
131 (org-assert-version)
132
131133 (require 'org)
132134 (require 'ol)
133135
134136 (declare-function org-publish-get-project-from-filename "ox-publish"
135137 (filename &optional up))
136 (declare-function server-edit "server" (&optional arg))
137138
138139 (defvar org-capture-link-is-already-stored)
139140 (defvar org-capture-templates)
173174 reverse order. Set to t (default) to re-reverse the list, i.e. use the
174175 sequence on the command line. If nil, the sequence of the filenames is
175176 unchanged."
176 :group 'org-protocol
177177 :type 'boolean)
178178
179179 (defcustom org-protocol-project-alist nil
232232 Consider using the interactive functions `org-protocol-create'
233233 and `org-protocol-create-for-org' to help you filling this
234234 variable with valid contents."
235 :group 'org-protocol
236235 :type 'alist)
237236
238237 (defcustom org-protocol-protocol-alist nil
283282 (\"your-protocol\"
284283 :protocol \"your-protocol\"
285284 :function your-protocol-handler-function)))"
286 :group 'org-protocol
287285 :type '(alist))
288286
289287 (defcustom org-protocol-default-template-key nil
290288 "The default template key to use.
291289 This is usually a single character string but can also be a
292290 string with two characters."
293 :group 'org-protocol
294291 :type '(choice (const nil) (string)))
295292
296293 (defcustom org-protocol-data-separator "/+\\|\\?"
297294 "The default data separator to use.
298295 This should be a single regexp string."
299 :group 'org-protocol
300296 :version "24.4"
301297 :package-version '(Org . "8.0")
302298 :type 'regexp)
308304 Emacsclient compresses double and triple slashes."
309305 (when (string-match "^\\([a-z]+\\):/" uri)
310306 (let* ((splitparts (split-string uri "/+")))
311 (setq uri (concat (car splitparts) "//" (mapconcat 'identity (cdr splitparts) "/")))))
307 (setq uri (concat (car splitparts) "//"
308 (mapconcat #'identity (cdr splitparts) "/")))))
312309 uri)
313310
314311 (defun org-protocol-split-data (data &optional unhexify separator)
370367 ret)
371368 l)))
372369
370 ;; `flatten-tree' was added in Emacs 27.1.
373371 (defalias 'org-protocol-flatten
374372 (if (fboundp 'flatten-tree) 'flatten-tree
375373 (lambda (list)
548546 "Convert QUERY key=value pairs in the URL to a property list."
549547 (when query
550548 (let ((plus-decoded (replace-regexp-in-string "\\+" " " query t t)))
551 (apply 'append (mapcar (lambda (x)
552 (let ((c (split-string x "=")))
553 (list (intern (concat ":" (car c))) (cadr c))))
554 (split-string plus-decoded "&"))))))
549 (cl-mapcan (lambda (x)
550 (let ((c (split-string x "=")))
551 (list (intern (concat ":" (car c))) (cadr c))))
552 (split-string plus-decoded "&")))))
555553
556554 (defun org-protocol-open-source (fname)
557555 "Process an org-protocol://open-source?url= style URL with FNAME.
640638 also recognized.
641639
642640 If a matching protocol is found, the protocol is stripped from
643 fname and the result is passed to the protocol function as the
641 FNAME and the result is passed to the protocol function as the
644642 first parameter. The second parameter will be non-nil if FNAME
645643 uses key=val&key2=val2-type arguments, or nil if FNAME uses
646644 val/val2-type arguments. If the function returns nil, the
670668 (new-style (not (= ?: (aref (match-string 1 fname) 0)))))
671669 (when (plist-get (cdr prolist) :kill-client)
672670 (message "Greedy org-protocol handler. Killing client.")
673 (server-edit))
671 ;; If not fboundp, there's no client to kill.
672 (if (fboundp 'server-edit) (server-edit)))
674673 (when (fboundp func)
675674 (unless greedy
676675 (throw 'fname
686685 (throw 'fname t))))))))
687686 fname)))
688687
689 (defadvice server-visit-files (before org-protocol-detect-protocol-server activate)
690 "Advice server-visit-flist to call `org-protocol-modify-filename-for-protocol'."
688 (advice-add 'server-visit-files :around #'org--protocol-detect-protocol-server)
689 (defun org--protocol-detect-protocol-server (orig-fun files client &rest args)
690 "Advice server-visit-flist to call `org-protocol-check-filename-for-protocol'."
691691 (let ((flist (if org-protocol-reverse-list-of-files
692 (reverse (ad-get-arg 0))
693 (ad-get-arg 0)))
694 (client (ad-get-arg 1)))
692 (reverse files)
693 files)))
695694 (catch 'greedy
696695 (dolist (var flist)
697696 ;; `\' to `/' on windows. FIXME: could this be done any better?
700699 fname (member var flist) client))
701700 (if (eq fname t) ;; greedy? We need the t return value.
702701 (progn
703 (ad-set-arg 0 nil)
702 ;; FIXME: Doesn't this just ignore all the files before
703 ;; this one (the remaining ones have been passed to
704 ;; `org-protocol-check-filename-for-protocol' but not
705 ;; the ones before).
706 (setq files nil)
704707 (throw 'greedy t))
705708 (if (stringp fname) ;; probably filename
706709 (setcar var fname)
707 (ad-set-arg 0 (delq var (ad-get-arg 0))))))))))
710 (setq files (delq var files)))))))
711 (apply orig-fun files client args)))
708712
709713 ;;; Org specific functions:
710714
00 ;;; org-refile.el --- Refile Org Subtrees -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
2424 ;; Org Refile allows you to refile subtrees to various locations.
2525
2626 ;;; Code:
27 (require 'org-macs)
28 (org-assert-version)
2729
2830 (require 'org)
2931
9496 to verify each headline found by the simple criteria above.
9597
9698 When this variable is nil, all top-level headlines in the current buffer
97 are used, equivalent to the value `((nil . (:level . 1))'."
99 are used, equivalent to the value `((nil . (:level . 1)))'."
98100 :group 'org-refile
99101 :type '(repeat
100102 (cons
152154
153155 When `buffer-name', use the buffer name."
154156 :group 'org-refile
157 :package-version '(Org . "9.6")
155158 :type '(choice
156159 (const :tag "Not" nil)
157160 (const :tag "Yes" t)
158161 (const :tag "Start with file name" file)
159162 (const :tag "Start with full file path" full-file-path)
160 (const :tag "Start with buffer name" buffer-name)))
163 (const :tag "Start with buffer name" buffer-name)
164 (const :tag "Start with document title" title)))
161165
162166 (defcustom org-outline-path-complete-in-steps t
163167 "Non-nil means complete the outline path in hierarchical steps.
316320 (push (list (and (buffer-file-name (buffer-base-buffer))
317321 (file-truename (buffer-file-name (buffer-base-buffer))))
318322 f nil nil) tgs))
323 (when (eq org-refile-use-outline-path 'title)
324 (push (list (or (org-get-title)
325 (and f (file-name-nondirectory f)))
326 f nil nil)
327 tgs))
319328 (org-with-wide-buffer
320329 (goto-char (point-min))
321330 (setq org-outline-path-cache nil)
342351 (and (buffer-file-name (buffer-base-buffer))
343352 (file-name-nondirectory
344353 (buffer-file-name (buffer-base-buffer))))))
345 (`full-file-path
354 (`title (list
355 (or (org-get-title)
356 (and (buffer-file-name (buffer-base-buffer))
357 (file-name-nondirectory
358 (buffer-file-name (buffer-base-buffer)))))))
359 (`full-file-path
346360 (list (buffer-file-name
347361 (buffer-base-buffer))))
348362 (`buffer-name
464478 (unless (or (org-kill-is-subtree-p
465479 (buffer-substring region-start region-end))
466480 (prog1 org-refile-active-region-within-subtree
467 (let ((s (point-at-eol)))
481 (let ((s (line-end-position)))
468482 (org-toggle-heading)
469 (setq region-end (+ (- (point-at-eol) s) region-end)))))
483 (setq region-end (+ (- (line-end-position) s) region-end)))))
470484 (user-error "The region is not a (sequence of) subtree(s)")))
471485 (if (equal arg '(16))
472486 (org-refile-goto-last-stored)
520534 (goto-char (cond (pos)
521535 ((org-notes-order-reversed-p) (point-min))
522536 (t (point-max))))
523 (org-show-context 'org-goto))
537 (org-fold-show-context 'org-goto))
524538 (if regionp
525539 (progn
526540 (org-kill-new (buffer-substring region-start region-end))
565579 (let ((bookmark-name (plist-get org-bookmark-names-plist
566580 :last-refile)))
567581 (when bookmark-name
568 (with-demoted-errors
569 (bookmark-set bookmark-name))))
582 (with-demoted-errors "Bookmark set error: %S"
583 (bookmark-set bookmark-name))))
570584 ;; If we are refiling for capture, make sure that the
571585 ;; last-capture pointers point here
572586 (when (bound-and-true-p org-capture-is-refiling)
573587 (let ((bookmark-name (plist-get org-bookmark-names-plist
574588 :last-capture-marker)))
575589 (when bookmark-name
576 (with-demoted-errors
577 (bookmark-set bookmark-name))))
590 (with-demoted-errors "Bookmark set error: %S"
591 (bookmark-set bookmark-name))))
578592 (move-marker org-capture-last-stored-marker (point)))
579 (when (fboundp 'deactivate-mark) (deactivate-mark))
593 (deactivate-mark)
580594 (run-hooks 'org-after-refile-insert-hook)))
581595 (unless org-refile-keep
582596 (if regionp
630644 (tbl (mapcar
631645 (lambda (x)
632646 (if (and (not (member org-refile-use-outline-path
633 '(file full-file-path)))
647 '(file full-file-path title)))
634648 (not (equal filename (nth 1 x))))
635649 (cons (concat (car x) extra " ("
636650 (file-name-nondirectory (nth 1 x)) ")")
639653 org-refile-target-table))
640654 (completion-ignore-case t)
641655 cdef
642 (prompt (concat prompt
643 (or (and (car org-refile-history)
644 (concat " (default " (car org-refile-history) ")"))
645 (and (assoc cbnex tbl) (setq cdef cbnex)
646 (concat " (default " cbnex ")"))) ": "))
656 (prompt (let ((default (or (car org-refile-history)
657 (and (assoc cbnex tbl) (setq cdef cbnex)
658 cbnex))))
659 (org-format-prompt prompt default)))
647660 pa answ parent-target child parent old-hist)
648661 (setq old-hist org-refile-history)
649662 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
00 ;;; org-src.el --- Source code examples in Org -*- lexical-binding: t; -*-
11 ;;
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Bastien Guerry <bzg@gnu.org>
66 ;; Dan Davison <davison at stats dot ox dot ac dot uk>
77 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: https://orgmode.org
8 ;; URL: https://orgmode.org
99 ;;
1010 ;; This file is part of GNU Emacs.
1111 ;;
3030
3131 ;;; Code:
3232
33 (require 'org-macs)
34 (org-assert-version)
35
3336 (require 'cl-lib)
3437 (require 'ob-comint)
3538 (require 'org-macs)
3639 (require 'org-compat)
3740 (require 'org-keys)
3841
42 (declare-function org--get-expected-indentation "org" (element contentsp))
3943 (declare-function org-mode "org" ())
4044 (declare-function org--get-expected-indentation "org" (element contentsp))
41 (declare-function org-element-at-point "org-element" ())
45 (declare-function org-fold-region "org-fold" (from to flag &optional spec-or-alias))
46 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
4247 (declare-function org-element-class "org-element" (datum &optional parent))
4348 (declare-function org-element-context "org-element" (&optional element))
4449 (declare-function org-element-lineage "org-element"
4550 (blob &optional types with-self))
51 (declare-function org-element--parse-paired-brackets "org-element" (char))
4652 (declare-function org-element-property "org-element" (property element))
4753 (declare-function org-element-type "org-element" (element))
4854 (declare-function org-footnote-goto-definition "org-footnote"
168174 split-window-right) will restore the layout after exiting the edit buffer."
169175 :group 'org-edit-structure
170176 :type '(choice
177 (const plain)
171178 (const current-window)
172179 (const split-window-below)
173180 (const split-window-right)
195202 ("calc" . fundamental)
196203 ("cpp" . c++)
197204 ("ditaa" . artist)
205 ("desktop" . conf-desktop)
198206 ("dot" . fundamental)
199207 ("elisp" . emacs-lisp)
200208 ("ocaml" . tuareg)
201209 ("screen" . shell-script)
202210 ("shell" . sh)
203 ("sqlite" . sql))
211 ("sqlite" . sql)
212 ("toml" . conf-toml))
204213 "Alist mapping languages to their major mode.
205214
206215 The key is the language name. The value is the mode name, as
211220 the user side. For example, there is no `ocaml-mode' in Emacs,
212221 but the mode to use is `tuareg-mode'."
213222 :group 'org-edit-structure
223 :package-version '(Org . "9.6")
214224 :type '(repeat
215225 (cons
216226 (string "Language name")
224234
225235 Where FACE is either a defined face or an anonymous face.
226236
227 For instance, the following value would color the background of
237 For instance, the following would color the background of
228238 emacs-lisp source blocks and python source blocks in purple and
229239 green, respectability.
230240
231 \\='((\"emacs-lisp\" (:background \"#EEE2FF\"))
232 (\"python\" (:background \"#e5ffb8\")))"
241 (setq org-src-block-faces
242 \\='((\"emacs-lisp\" (:background \"#EEE2FF\"))
243 (\"python\" (:background \"#e5ffb8\"))))"
233244 :group 'org-edit-structure
234245 :type '(repeat (list (string :tag "language")
235246 (choice
239250 :package-version '(Org . "9.0"))
240251
241252 (defcustom org-src-tab-acts-natively t
242 "If non-nil, the effect of TAB in a code block is as if it were
243 issued in the language major mode buffer."
253 "If non-nil, TAB uses the language's major-mode binding in code blocks."
244254 :type 'boolean
245255 :package-version '(Org . "9.4")
246256 :group 'org-babel)
303313 (put 'org-src--preserve-blank-line 'permanent-local t)
304314
305315 (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
306 "Construct the buffer name for a source editing buffer."
316 "Construct the buffer name for a source editing buffer.
317 Format is \"*Org Src ORG-BUFFER-NAME[ LANG ]*\"."
307318 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
308319
309320 (defun org-src--edit-buffer (beg end)
377388 (let ((beg (org-element-property :contents-begin datum))
378389 (end (org-element-property :contents-end datum)))
379390 (list beg end (buffer-substring-no-properties beg end))))
380 ((memq type '(example-block export-block src-block))
391 ((memq type '(example-block export-block src-block comment-block))
381392 (list (progn (goto-char (org-element-property :post-affiliated datum))
382393 (line-beginning-position 2))
383394 (progn (goto-char (org-element-property :end datum))
523534 (block-ind (org-with-point-at (org-element-property :begin datum)
524535 (cond
525536 ((save-excursion (skip-chars-backward " \t") (bolp))
526 (current-indentation))
537 (org-current-text-indentation))
527538 ((org-element-property :parent datum)
528539 (org--get-expected-indentation
529540 (org-element-property :parent datum) nil))
530 (t (current-indentation)))))
541 (t (org-current-text-indentation)))))
531542 (content-ind org-edit-src-content-indentation)
532543 (blank-line (save-excursion (beginning-of-line)
533544 (looking-at-p "^[[:space:]]*$")))
612623
613624 ;;; Fontification of source blocks
614625
626 (defvar org-src-fontify-natively) ; Defined in org.el
615627 (defun org-src-font-lock-fontify-block (lang start end)
616 "Fontify code block.
628 "Fontify code block between START and END using LANG's syntax.
617629 This function is called by Emacs' automatic fontification, as long
618630 as `org-src-fontify-natively' is non-nil."
619 (let ((lang-mode (org-src-get-lang-mode lang)))
620 (when (fboundp lang-mode)
621 (let ((string (buffer-substring-no-properties start end))
622 (modified (buffer-modified-p))
623 (org-buffer (current-buffer)))
624 (remove-text-properties start end '(face nil))
625 (with-current-buffer
626 (get-buffer-create
627 (format " *org-src-fontification:%s*" lang-mode))
628 (let ((inhibit-modification-hooks nil))
629 (erase-buffer)
630 ;; Add string and a final space to ensure property change.
631 (insert string " "))
632 (unless (eq major-mode lang-mode) (funcall lang-mode))
633 (org-font-lock-ensure)
634 (let ((pos (point-min)) next)
635 (while (setq next (next-property-change pos))
636 ;; Handle additional properties from font-lock, so as to
637 ;; preserve, e.g., composition.
638 (dolist (prop (cons 'face font-lock-extra-managed-props))
639 (let ((new-prop (get-text-property pos prop)))
640 (put-text-property
641 (+ start (1- pos)) (1- (+ start next)) prop new-prop
642 org-buffer)))
643 (setq pos next))))
644 ;; Add Org faces.
645 (let ((src-face (nth 1 (assoc-string lang org-src-block-faces t))))
646 (when (or (facep src-face) (listp src-face))
647 (font-lock-append-text-property start end 'face src-face))
648 (font-lock-append-text-property start end 'face 'org-block))
649 (add-text-properties
650 start end
651 '(font-lock-fontified t fontified t font-lock-multiline t))
652 (set-buffer-modified-p modified)))))
631 (let ((modified (buffer-modified-p)))
632 (remove-text-properties start end '(face nil))
633 (let ((lang-mode (org-src-get-lang-mode lang)))
634 (when (fboundp lang-mode)
635 (let ((string (buffer-substring-no-properties start end))
636 (org-buffer (current-buffer)))
637 (with-current-buffer
638 (get-buffer-create
639 (format " *org-src-fontification:%s*" lang-mode))
640 (let ((inhibit-modification-hooks nil))
641 (erase-buffer)
642 ;; Add string and a final space to ensure property change.
643 (insert string " "))
644 (unless (eq major-mode lang-mode) (funcall lang-mode))
645 (font-lock-ensure)
646 (let ((pos (point-min)) next)
647 (while (setq next (next-property-change pos))
648 ;; Handle additional properties from font-lock, so as to
649 ;; preserve, e.g., composition.
650 ;; FIXME: We copy 'font-lock-face property explicitly because
651 ;; `font-lock-mode' is not enabled in the buffers starting from
652 ;; space and the remapping between 'font-lock-face and 'face
653 ;; text properties may thus not be set. See commit
654 ;; 453d634bc.
655 (dolist (prop (append '(font-lock-face face) font-lock-extra-managed-props))
656 (let ((new-prop (get-text-property pos prop)))
657 (when new-prop
658 (if (not (eq prop 'invisible))
659 (put-text-property
660 (+ start (1- pos)) (1- (+ start next)) prop new-prop
661 org-buffer)
662 ;; Special case. `invisible' text property may
663 ;; clash with Org folding. Do not assign
664 ;; `invisible' text property directly. Use
665 ;; property alias instead.
666 (let ((invisibility-spec
667 (or
668 ;; ATOM spec.
669 (and (memq new-prop buffer-invisibility-spec)
670 new-prop)
671 ;; (ATOM . ELLIPSIS) spec.
672 (assq new-prop buffer-invisibility-spec))))
673 (with-current-buffer org-buffer
674 ;; Add new property alias.
675 (unless (memq 'org-src-invisible
676 (cdr (assq 'invisible char-property-alias-alist)))
677 (setq-local
678 char-property-alias-alist
679 (cons (cons 'invisible
680 (nconc (cdr (assq 'invisible char-property-alias-alist))
681 '(org-src-invisible)))
682 (remove (assq 'invisible char-property-alias-alist)
683 char-property-alias-alist))))
684 ;; Carry over the invisibility spec, unless
685 ;; already present. Note that there might
686 ;; be conflicting invisibility specs from
687 ;; different major modes. We cannot do much
688 ;; about this then.
689 (when invisibility-spec
690 (add-to-invisibility-spec invisibility-spec))
691 (put-text-property
692 (+ start (1- pos)) (1- (+ start next))
693 'org-src-invisible new-prop
694 org-buffer)))))))
695 (setq pos next)))
696 (set-buffer-modified-p nil)))))
697 ;; Add Org faces.
698 (let ((src-face (nth 1 (assoc-string lang org-src-block-faces t))))
699 (when (or (facep src-face) (listp src-face))
700 (font-lock-append-text-property start end 'face src-face))
701 (font-lock-append-text-property start end 'face 'org-block))
702 ;; Clear abbreviated link folding.
703 (org-fold-region start end nil 'org-link)
704 (add-text-properties
705 start end
706 '(font-lock-fontified t fontified t font-lock-multiline t))
707 (set-buffer-modified-p modified)))
708
709 (defun org-fontify-inline-src-blocks (limit)
710 "Try to apply `org-fontify-inline-src-blocks-1'."
711 (condition-case nil
712 (org-fontify-inline-src-blocks-1 limit)
713 (error (message "Org mode fontification error in %S at %d"
714 (current-buffer)
715 (line-number-at-pos)))))
716
717 (defun org-fontify-inline-src-blocks-1 (limit)
718 "Fontify inline src_LANG blocks, from `point' up to LIMIT."
719 (let ((case-fold-search t))
720 ;; The regexp below is copied from `org-element-inline-src-block-parser'.
721 (while (re-search-forward "\\_<src_\\([^ \t\n[{]+\\)[{[]?" limit t)
722 (let ((beg (match-beginning 0))
723 (lang-beg (match-beginning 1))
724 (lang-end (match-end 1))
725 pt)
726 (font-lock-append-text-property
727 lang-beg lang-end 'face 'org-meta-line)
728 (font-lock-append-text-property
729 beg lang-beg 'face 'shadow)
730 (font-lock-append-text-property
731 beg lang-end 'face 'org-inline-src-block)
732 (setq pt (goto-char lang-end))
733 ;; `org-element--parse-paired-brackets' doesn't take a limit, so to
734 ;; prevent it searching the entire rest of the buffer we temporarily
735 ;; narrow the active region.
736 (save-restriction
737 (narrow-to-region beg
738 (min limit (or (save-excursion
739 (and (search-forward"\n" limit t 2)
740 (point)))
741 (point-max))))
742 (when (ignore-errors (org-element--parse-paired-brackets ?\[))
743 (font-lock-append-text-property
744 pt (point) 'face 'org-inline-src-block)
745 (setq pt (point)))
746 (when (ignore-errors (org-element--parse-paired-brackets ?\{))
747 (remove-text-properties pt (point) '(face nil))
748 (font-lock-append-text-property
749 pt (1+ pt) 'face '(org-inline-src-block shadow))
750 (unless (= (1+ pt) (1- (point)))
751 (if org-src-fontify-natively
752 (org-src-font-lock-fontify-block
753 (buffer-substring-no-properties lang-beg lang-end)
754 (1+ pt) (1- (point)))
755 (font-lock-append-text-property
756 (1+ pt) (1- (point)) 'face 'org-inline-src-block)))
757 (font-lock-append-text-property
758 (1- (point)) (point) 'face '(org-inline-src-block shadow))
759 (setq pt (point)))))
760 t)))
653761
654762
655763 ;;; Escape contents
759867 ;;; Babel related functions
760868
761869 (defun org-src-associate-babel-session (info)
762 "Associate edit buffer with comint session."
870 "Associate edit buffer with comint session.
871 INFO should be a list similar in format to the return value of
872 `org-babel-get-src-block-info'."
763873 (interactive)
764874 (let ((session (cdr (assq :session (nth 2 info)))))
765875 (and session (not (string= session "none"))
769879 (and (fboundp f) (funcall f session))))))
770880
771881 (defun org-src-babel-configure-edit-buffer ()
882 "Configure src editing buffer."
772883 (when org-src--babel-info
773884 (org-src-associate-babel-session org-src--babel-info)))
774885
841952 org-src--source-type)
842953
843954 (defun org-src-switch-to-buffer (buffer context)
955 "Switch to BUFFER considering CONTEXT and `org-src-window-setup'."
844956 (pcase org-src-window-setup
845957 (`plain
846958 (when (eq context 'exit) (quit-restore-window))
10891201 (lambda () (org-escape-code-in-region (point-min) (point-max)))))
10901202 t))
10911203
1204 (defun org-edit-comment-block ()
1205 "Edit comment block at point.
1206 \\<org-src-mode-map>
1207 A new buffer is created and the block is copied into it, and the
1208 buffer is switched into Org mode.
1209
1210 When done, exit with `\\[org-edit-src-exit]'. The edited text will
1211 then replace the area in the Org mode buffer.
1212
1213 Throw an error when not at a comment block."
1214 (interactive)
1215 (let ((element (org-element-at-point)))
1216 (unless (and (eq (org-element-type element) 'comment-block)
1217 (org-src--on-datum-p element))
1218 (user-error "Not in a comment block"))
1219 (org-src--edit-element
1220 element
1221 (org-src--construct-edit-buffer-name (buffer-name) "org")
1222 'org-mode
1223 (lambda () (org-escape-code-in-region (point-min) (point-max)))
1224 (org-unescape-code-in-string (org-element-property :value element)))
1225 t))
1226
10921227 (defun org-edit-src-code (&optional code edit-buffer-name)
10931228 "Edit the source or example block at point.
10941229 \\<org-src-mode-map>
11151250 "example"))
11161251 (lang-f (and (eq type 'src-block) (org-src-get-lang-mode lang)))
11171252 (babel-info (and (eq type 'src-block)
1118 (org-babel-get-src-block-info 'light)))
1253 (org-babel-get-src-block-info 'no-eval)))
11191254 deactivate-mark)
11201255 (when (and (eq type 'src-block) (not (functionp lang-f)))
11211256 (error "No such language mode: %s" lang-f))
11471282 (user-error "Not on inline source code"))
11481283 (let* ((lang (org-element-property :language context))
11491284 (lang-f (org-src-get-lang-mode lang))
1150 (babel-info (org-babel-get-src-block-info 'light))
1285 (babel-info (org-babel-get-src-block-info 'no-eval))
11511286 deactivate-mark)
11521287 (unless (functionp lang-f) (error "No such language mode: %s" lang-f))
11531288 (org-src--edit-element
12031338 (interactive)
12041339 (let (org-src--allow-write-back) (org-edit-src-exit)))
12051340
1206 (defun org-edit-src-continue (e)
1341 (defun org-edit-src-continue (event)
12071342 "Unconditionally return to buffer editing area under point.
1208 Throw an error if there is no such buffer."
1343 Throw an error if there is no such buffer.
1344 EVENT is passed to `mouse-set-point'."
12091345 (interactive "e")
1210 (mouse-set-point e)
1346 (mouse-set-point event)
12111347 (let ((buf (get-char-property (point) 'edit-buffer)))
12121348 (if buf (org-src-switch-to-buffer buf 'continue)
12131349 (user-error "No sub-editing buffer for area at point"))))
12341370 (insert (with-current-buffer write-back-buf (buffer-string))))
12351371 (save-restriction
12361372 (narrow-to-region beg end)
1237 (replace-buffer-contents write-back-buf 0.1 nil)
1373 (org-replace-buffer-contents write-back-buf 0.1 nil)
12381374 (goto-char (point-max))))
12391375 (when (and expecting-bol (not (bolp))) (insert "\n")))
12401376 (kill-buffer write-back-buf)
12711407 (org-with-wide-buffer
12721408 (when (and write-back
12731409 (not (equal (buffer-substring beg end)
1274 (with-current-buffer write-back-buf
1275 (buffer-string)))))
1410 (with-current-buffer write-back-buf
1411 (buffer-string)))))
12761412 (undo-boundary)
12771413 (goto-char beg)
12781414 (let ((expecting-bol (bolp)))
12821418 (buffer-string))))
12831419 (save-restriction
12841420 (narrow-to-region beg end)
1285 (replace-buffer-contents write-back-buf 0.1 nil)
1421 (org-replace-buffer-contents write-back-buf 0.1 nil)
12861422 (goto-char (point-max))))
12871423 (when (and expecting-bol (not (bolp))) (insert "\n")))))
12881424 (when write-back-buf (kill-buffer write-back-buf))
12931429 (goto-char beg)
12941430 (cond
12951431 ;; Block is hidden; move at start of block.
1296 ((cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
1297 (overlays-at (point)))
1432 ((if (eq org-fold-core-style 'text-properties)
1433 (org-fold-folded-p nil 'block)
1434 (cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
1435 (overlays-at (point))))
12981436 (beginning-of-line 0))
12991437 (write-back (org-src--goto-coordinates coordinates beg end))))
13001438 ;; Clean up left-over markers and restore window configuration.
00 ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
3333
3434 ;;; Code:
3535
36 (require 'org-macs)
37 (org-assert-version)
38
3639 (require 'cl-lib)
3740 (require 'org-macs)
3841 (require 'org-compat)
3942 (require 'org-keys)
43 (require 'org-fold-core)
4044
4145 (declare-function calc-eval "calc" (str &optional separator &rest args))
4246 (declare-function face-remap-remove-relative "face-remap" (cookie))
4650 (declare-function org-mode "org" ())
4751 (declare-function org-duration-p "org-duration" (duration &optional canonical))
4852 (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
49 (declare-function org-element-at-point "org-element" ())
53 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
5054 (declare-function org-element-contents "org-element" (element))
5155 (declare-function org-element-extract-element "org-element" (element))
5256 (declare-function org-element-interpret-data "org-element" (data))
5559 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
5660 (declare-function org-element-property "org-element" (property element))
5761 (declare-function org-element-type "org-element" (element))
62 (declare-function org-element-cache-reset "org-element" (&optional all no-persistence))
5863 (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
5964 (declare-function org-export-create-backend "ox" (&rest rest) t)
6065 (declare-function org-export-data-with-backend "ox" (data backend info))
461466 (when pos (goto-char pos))
462467 (goto-char (line-beginning-position))
463468 (let ((end (line-end-position)) str)
464 (backward-char)
469 (goto-char (1- pos))
465470 (while (progn (forward-char 1) (< (point) end))
466471 (let ((ov (car (overlays-at (point)))))
467472 (if (not ov)
468473 (push (char-to-string (char-after)) str)
469474 (push (overlay-get ov 'display) str)
470475 (goto-char (1- (overlay-end ov))))))
471 (format "%s" (mapconcat #'identity (reverse str) "")))))
476 (format "|%s" (mapconcat #'identity (reverse str) "")))))
472477
473478 (defvar-local org-table-header-overlay nil)
479 (put 'org-table-header-overlay 'permanent-local t)
474480 (defun org-table-header-set-header ()
475481 "Display the header of the table at point."
476482 (let ((gcol temporary-goal-column))
485491 (looking-at-p ".*|\\s-+<[rcl]?\\([0-9]+\\)?>"))
486492 (move-beginning-of-line 2))
487493 (line-beginning-position)))
488 (end (save-excursion (goto-char beg) (point-at-eol))))
494 (end (save-excursion (goto-char beg) (line-end-position))))
489495 (if (pos-visible-in-window-p beg)
490496 (when (overlayp org-table-header-overlay)
491497 (delete-overlay org-table-header-overlay))
565571 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
566572 "Match a reference that needs translation, for reference display.")
567573
568 (defconst org-table-separator-space
574 (defconst org-table--separator-space-pre
569575 (propertize " " 'display '(space :relative-width 1))
570 "Space used around fields when aligning the table.
576 "Space used in front of fields when aligning the table.
571577 This space serves as a segment separator for the purposes of the
572 bidirectional reordering.")
578 bidirectional reordering.
579 Note that `org-table--separator-space-pre' is not `eq' to
580 `org-table--separator-space-post'. This is done to prevent Emacs from
581 visually merging spaces in an empty table cell. See bug#45915.")
582
583 (defconst org-table--separator-space-post
584 (propertize " " 'display '(space :relative-width 1.001))
585 "Space used after fields when aligning the table.
586 This space serves as a segment separator for the purposes of the
587 bidirectional reordering.
588 Note that `org-table--separator-space-pre' is not `eq' to
589 `org-table--separator-space-post'. This is done to prevent Emacs from
590 visually merging spaces in an empty table cell. See bug#45915.")
573591
574592
575593 ;;; Internal Variables
824842 (line (concat (apply 'concat indent "|" (make-list columns " |"))
825843 "\n")))
826844 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
827 (point-at-bol) (point)))
845 (line-beginning-position) (point)))
828846 (beginning-of-line 1)
829847 (newline))
830848 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
842860 "Convert region to a table.
843861
844862 The region goes from BEG0 to END0, but these borders will be moved
845 slightly, to make sure a beginning of line in the first line is included.
863 slightly, to make sure a beginning of line in the first line is
864 included.
865
866 Throw an error when the region has more than
867 `org-table-convert-region-max-lines' lines.
846868
847869 SEPARATOR specifies the field separator in the lines. It can have the
848870 following values:
10861108 (while (> n 1)
10871109 (setq n (1- n))
10881110 (org-table-previous-field))
1089 (if (not (re-search-backward "|" (point-at-bol 0) t))
1111 (if (not (re-search-backward "|" (line-beginning-position 0) t))
10901112 (user-error "No more table fields before the current")
10911113 (goto-char (match-end 0))
10921114 (and (looking-at " ") (forward-char 1)))
11011123 (while (> n 1)
11021124 (setq n (1- n))
11031125 (org-table-next-field))
1104 (when (re-search-forward "|" (point-at-eol 1) t)
1126 (when (re-search-forward "|" (line-end-position 1) t)
11051127 (backward-char 1)
11061128 (skip-chars-backward " ")
11071129 (when (and (equal (char-before (point)) ?|) (equal (char-after (point)) ?\s))
11581180 (goto-char (org-table-begin))
11591181 (while (and (re-search-forward org-table-dataline-regexp end t)
11601182 (setq cnt (1+ cnt))
1161 (< (point-at-eol) pos))))
1183 (< (line-end-position) pos))))
11621184 cnt))
11631185
11641186 (defun org-table-current-column ()
12071229 (if (looking-at "|[^|\n]+")
12081230 (let* ((pos (match-beginning 0))
12091231 (match (match-string 0))
1210 (len (org-string-width match)))
1232 (len (save-match-data (org-string-width match))))
12111233 (replace-match (concat "|" (make-string (1- len) ?\ )))
12121234 (goto-char (+ 2 pos))
12131235 (substring match 1)))))
13211343 (beginning-of-line 1)
13221344 (when (> n 0)
13231345 (while (and (> (setq n (1- n)) -1)
1324 (or (search-forward "|" (point-at-eol) t)
1346 (or (search-forward "|" (line-end-position) t)
13251347 (and force
13261348 (progn (end-of-line 1)
13271349 (skip-chars-backward "^|")
13381360 "Insert a new column into the table."
13391361 (interactive)
13401362 (unless (org-at-table-p) (user-error "Not at a table"))
1363 (when (eobp) (save-excursion (insert "\n")))
1364 (unless (string-match-p "|[ \t]*$" (org-current-line-string))
1365 (org-table-align))
13411366 (org-table-find-dataline)
13421367 (let ((col (max 1 (org-table-current-column)))
13431368 (beg (org-table-begin))
16321657 With prefix ARG, insert below the current line."
16331658 (interactive "P")
16341659 (unless (org-at-table-p) (user-error "Not at a table"))
1660 (when (eobp) (save-excursion (insert "\n")))
1661 (unless (string-match-p "|[ \t]*$" (org-current-line-string))
1662 (org-table-align))
16351663 (org-table-with-shrunk-columns
16361664 (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
16371665 (new (org-table-clean-line line)))
16621690 (org-table-align))
16631691 (org-table-with-shrunk-columns
16641692 (let ((line (org-table-clean-line
1665 (buffer-substring (point-at-bol) (point-at-eol))))
1693 (buffer-substring (line-beginning-position) (line-end-position))))
16661694 (col (current-column)))
16671695 (while (string-match "|\\( +\\)|" line)
16681696 (setq line (replace-match
16971725 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
16981726 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
16991727 (setq s (replace-match
1700 (concat "|" (make-string (org-string-width (match-string 1 s))
1701 ?\ ) "|")
1728 (concat "|"
1729 (make-string
1730 (save-match-data
1731 (org-string-width (match-string 1 s)))
1732 ?\ )
1733 "|")
17021734 t t s)))
17031735 s))
17041736
17111743 (dline (and (not (org-match-line org-table-hline-regexp))
17121744 (org-table-current-dline))))
17131745 (org-table-with-shrunk-columns
1714 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1746 (kill-region (line-beginning-position)
1747 (min (1+ (line-end-position)) (point-max)))
17151748 (if (not (org-at-table-p)) (beginning-of-line 0))
17161749 (org-move-to-column col)
17171750 (when (and dline
22522285 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
22532286 s n a)
22542287 (when remove
2255 (while (re-search-forward re2 (point-at-eol) t)
2256 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2257 (if (equal (char-before (match-beginning 0)) ?.)
2258 (user-error
2259 "Change makes TBLFM term %s invalid, use undo to recover"
2260 (match-string 0))
2261 (replace-match "")))))
2262 (while (re-search-forward re (point-at-eol) t)
2288 (save-excursion
2289 (while (re-search-forward re2 (line-end-position) t)
2290 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2291 (if (equal (char-before (match-beginning 0)) ?.)
2292 (user-error
2293 "Change makes TBLFM term %s invalid, use undo to recover"
2294 (match-string 0))
2295 (replace-match ""))))))
2296 (while (re-search-forward re (line-end-position) t)
22632297 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
22642298 (setq s (match-string 1) n (string-to-number s))
22652299 (cond
25842618
25852619 (if lispp
25862620 (setq ev (condition-case nil
2621 ;; FIXME: Arbitrary code evaluation.
25872622 (eval (eval (read form)))
25882623 (error "#ERROR"))
25892624 ev (if (numberp ev) (number-to-string ev) ev)
26052640 (format-time-string
26062641 (org-time-stamp-format
26072642 (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2608 (apply #'encode-time
2609 (save-match-data (org-parse-time-string ts))))))
2643 (save-match-data (org-time-string-to-time ts)))))
26102644 form t t))
26112645
26122646 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
28672901 current time if a message is printed, otherwise returns T1. If
28682902 T1 is nil, always messages."
28692903 (let ((curtime (current-time)))
2870 (if (or (not t1) (org-time-less-p 1 (org-time-subtract curtime t1)))
2904 (if (or (not t1) (time-less-p 1 (time-subtract curtime t1)))
28712905 (progn (apply 'message args)
28722906 curtime)
28732907 t1)))
34133447 (defun org-table-convert-refs-to-an (s)
34143448 "Convert spreadsheet references from to @7$28 to AB7.
34153449 Works for single references, but also for entire formulas and even the
3416 full TBLFM line."
3450 full TBLFM line.
3451
3452 Leave the relative references unchanged."
34173453 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
34183454 (setq s (replace-match
34193455 (format "%s%d"
34213457 (string-to-number (match-string 2 s)))
34223458 (string-to-number (match-string 1 s)))
34233459 t t s)))
3424 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3460 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([1-9][0-9]*\\)" s)
34253461 (setq s (replace-match (concat "\\1"
34263462 (org-number-to-letters
34273463 (string-to-number (match-string 2 s))) "&")
36653701 (goto-char pos)
36663702 (call-interactively 'lisp-indent-line))
36673703 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3668 ((not (fboundp 'pp-buffer))
3669 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
36703704 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
36713705 (goto-char (- (match-end 0) 2))
36723706 (setq beg (point))
37783812
37793813 (defvar-local org-table-coordinate-overlays nil
37803814 "Collects the coordinate grid overlays, so that they can be removed.")
3815 (put 'org-table-coordinate-overlays 'permanent-local t)
37813816
37823817 (defun org-table-overlay-coordinates ()
37833818 "Add overlays to the table at point, to show row/column coordinates."
37883823 (let ((id 0) (ih 0) hline eol str ov)
37893824 (goto-char (org-table-begin))
37903825 (while (org-at-table-p)
3791 (setq eol (point-at-eol))
3792 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3826 (setq eol (line-end-position))
3827 (setq ov (make-overlay (line-beginning-position)
3828 (1+ (line-beginning-position))))
37933829 (push ov org-table-coordinate-overlays)
37943830 (setq hline (looking-at org-table-hline-regexp))
37953831 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
38873923
38883924 When optional argument PRE is non-nil, assume the overlay is
38893925 located at the beginning of the field, and prepend
3890 `org-table-separator-space' to it. Otherwise, concatenate
3926 `org-table--separator-space-pre' to it. Otherwise, concatenate
38913927 `org-table-shrunk-column-indicator' at its end.
38923928
38933929 Return the overlay."
39063942 ;; Make sure overlays stays on top of table coordinates overlays.
39073943 ;; See `org-table-overlay-coordinates'.
39083944 (overlay-put o 'priority 1)
3909 (let ((d (if pre (concat org-table-separator-space display)
3945 (let ((d (if pre (concat org-table--separator-space-pre display)
39103946 (concat display org-table-shrunk-column-indicator))))
39113947 (org-overlay-display o d 'org-table t))
39123948 o))
40794115 respectively, the beginning position and the end position of the
40804116 table."
40814117 (org-with-wide-buffer
4082 (org-font-lock-ensure beg end)
4118 (font-lock-ensure beg end)
40834119 (dolist (c columns)
40844120 (goto-char beg)
40854121 (let ((align nil)
42014237 (org-table-expand begin end)
42024238 ;; Make sure invisible characters in the table are at the right
42034239 ;; place since column widths take them into account.
4204 (org-font-lock-ensure begin end)
4240 (font-lock-ensure begin end)
42054241 (org-table--shrink-columns (sort columns #'<) begin end))))
42064242
42074243 ;;;###autoload
43194355 ("r" (make-string spaces ?\s))
43204356 ("c" (make-string (/ spaces 2) ?\s))))
43214357 (suffix (make-string (- spaces (length prefix)) ?\s)))
4322 (concat org-table-separator-space
4358 (concat org-table--separator-space-pre
43234359 prefix
43244360 field
43254361 suffix
4326 org-table-separator-space)))
4362 org-table--separator-space-post)))
43274363
43284364 (defun org-table-align ()
43294365 "Align the table at point by aligning all vertical bars."
43334369 (org-table-save-field
43344370 ;; Make sure invisible characters in the table are at the right
43354371 ;; place since column widths take them into account.
4336 (org-font-lock-ensure beg end)
4372 (font-lock-ensure beg end)
43374373 (move-marker org-table-aligned-begin-marker beg)
43384374 (move-marker org-table-aligned-end-marker end)
43394375 (goto-char beg)
44194455 (defun org-table-justify-field-maybe (&optional new)
44204456 "Justify the current field, text to left, number to right.
44214457 Optional argument NEW may specify text to replace the current field content."
4458 ;; FIXME: Prevent newlines inside field. They are currently not
4459 ;; supported.
4460 (when (and (stringp new) (string-match-p "\n" new))
4461 (message "Removing newlines from formula result: %S" new)
4462 (setq new (replace-regexp-in-string
4463 "\n" " "
4464 (replace-regexp-in-string "\\(^\n+\\)\\|\\(\n+$\\)" "" new))))
44224465 (cond
44234466 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
44244467 ((org-at-table-hline-p))
45614604 (predicate
45624605 (cl-case sorting-type
45634606 ((?n ?N ?t ?T) #'<)
4564 ((?a ?A) (if with-case #'org-string-collate-lessp
4565 (lambda (s1 s2) (org-string-collate-lessp s1 s2 nil t))))
4607 ((?a ?A) (if with-case #'string-collate-lessp
4608 (lambda (s1 s2) (string-collate-lessp s1 s2 nil t))))
45664609 ((?f ?F)
45674610 (or compare-func
45684611 (and interactive?
49224965 ((not local) nil)
49234966 (t (user-error "No reference at point")))
49244967 match (and what (or match (match-string 0))))
4925 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
4968 (when (and match (not (equal (match-beginning 0) (line-beginning-position))))
49264969 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
49274970 'secondary-selection))
49284971 (add-hook 'before-change-functions
51655208 (concat orgtbl-line-start-regexp "\\|"
51665209 auto-fill-inhibit-regexp)
51675210 orgtbl-line-start-regexp))
5168 (when (fboundp 'font-lock-add-keywords)
5169 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
5170 (org-restart-font-lock)))
5211 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
5212 (org-restart-font-lock))
51715213 (t
51725214 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
51735215 (remove-hook 'before-change-functions 'org-before-change-function t)
5174 (when (fboundp 'font-lock-remove-keywords)
5175 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
5176 (org-restart-font-lock))
5216 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
5217 (org-restart-font-lock)
51775218 (force-mode-line-update 'all))))
51785219
51795220 (defun orgtbl-make-binding (fun n &rest keys)
52885329 (org-remap orgtbl-mode-map
52895330 'self-insert-command 'orgtbl-self-insert-command
52905331 'delete-char 'org-delete-char
5332 'delete-forward-char 'org-delete-char
52915333 'delete-backward-char 'org-delete-backward-char)
52925334 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
52935335 t))
53735415 (self-insert-command N))
53745416 (setq org-table-may-need-update t)
53755417 (let* (orgtbl-mode
5376 a
53775418 (cmd (or (key-binding
53785419 (or (and (listp function-key-map)
5379 (setq a (assoc last-input-event function-key-map))
5380 (cdr a))
5381 (vector last-input-event)))
5420 (cdr (assoc last-command-event function-key-map)))
5421 (vector last-command-event)))
53825422 'self-insert-command)))
53835423 (call-interactively cmd)
53845424 (if (and org-self-insert-cluster-for-undo
54645504 (nreverse table)))))
54655505
54665506 (defun org-table-collapse-header (table &optional separator max-header-lines)
5467 "Collapse the lines before 'hline into a single header.
5507 "Collapse the lines before `hline' into a single header.
54685508
54695509 The given TABLE is a list of lists as returned by `org-table-to-lisp'.
54705510 The leading lines before the first `hline' symbol are considered
55415581 beg end)
55425582 (save-excursion
55435583 (beginning-of-line 1)
5544 (while (looking-at re) (beginning-of-line 0))
5545 (beginning-of-line 2)
5584 (while (and (not (eq (point) (point-min)))
5585 (looking-at re))
5586 (beginning-of-line 0))
5587 (unless (eq (point) (point-min)) (beginning-of-line 2))
55465588 (setq beg (point))
5547 (while (looking-at re) (beginning-of-line 2))
5589 (while (and (not (eq (point) (point-max)))
5590 (looking-at re))
5591 (beginning-of-line 2))
55485592 (setq end (point)))
55495593 (comment-region beg end (if commented '(4) nil))))
55505594
56475691 functions, e.g.,
56485692
56495693 (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
5694
5695 The format is ignored for empty fields. Use :raw t with non-nil
5696 :backend option to force formatting empty fields.
56505697
56515698 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
56525699
56865733 ;; Initialize communication channel in INFO.
56875734 (with-temp-buffer
56885735 (let ((org-inhibit-startup t)) (org-mode))
5689 (let ((standard-output (current-buffer))
5690 (org-element-use-cache nil))
5691 (dolist (e table)
5692 (cond ((eq e 'hline) (princ "|--\n"))
5693 ((consp e)
5694 (princ "| ") (dolist (c e) (princ c) (princ " |"))
5695 (princ "\n")))))
5696 ;; Add back-end specific filters, but not user-defined ones. In
5697 ;; particular, make sure to call parse-tree filters on the
5698 ;; table.
5699 (setq info
5700 (let ((org-export-filters-alist nil))
5701 (org-export-install-filters
5702 (org-combine-plists
5703 (org-export-get-environment backend nil params)
5704 `(:back-end ,(org-export-get-backend backend))))))
5705 (setq data
5706 (org-export-filter-apply-functions
5707 (plist-get info :filter-parse-tree)
5708 (org-element-map (org-element-parse-buffer) 'table
5709 #'identity nil t)
5710 info)))
5711 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
5712 (user-error "Unknown :backend value"))
5736 (org-fold-core-ignore-modifications
5737 (let ((standard-output (current-buffer))
5738 (org-element-use-cache nil))
5739 (dolist (e table)
5740 (cond ((eq e 'hline) (princ "|--\n"))
5741 ((consp e)
5742 (princ "| ") (dolist (c e) (princ c) (princ " |"))
5743 (princ "\n")))))
5744 (org-element-cache-reset)
5745 ;; Add back-end specific filters, but not user-defined ones. In
5746 ;; particular, make sure to call parse-tree filters on the
5747 ;; table.
5748 (setq info
5749 (let ((org-export-filters-alist nil))
5750 (org-export-install-filters
5751 (org-combine-plists
5752 (org-export-get-environment backend nil params)
5753 `(:back-end ,(org-export-get-backend backend))))))
5754 (setq data
5755 (org-export-filter-apply-functions
5756 (plist-get info :filter-parse-tree)
5757 (org-element-map (org-element-parse-buffer) 'table
5758 #'identity nil t)
5759 info))
5760 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
5761 (user-error "Unknown :backend value"))))
57135762 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
57145763 ;; Handle :skip parameter.
57155764 (let ((skip (plist-get info :skip)))
00 ;;; org-tempo.el --- Template expansion for Org structures -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2017-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2017-2023 Free Software Foundation, Inc.
33 ;;
44 ;; Author: Rasmus Pank Roulund <emacs at pank dot eu>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
3737 ;;
3838 ;;; Code:
3939
40 (require 'org-macs)
41 (org-assert-version)
42
4043 (require 'tempo)
4144 (require 'cl-lib)
4245 (require 'org)
6669
6770 Do not use \"I\" as a KEY, as it is reserved for expanding
6871 \"#+include\"."
69 :group 'org-tempo
7072 :type '(repeat (cons (string :tag "Key")
7173 (string :tag "Keyword")))
7274 :package-version '(Org . "9.2"))
101103
102104 Go through `org-structure-template-alist' and
103105 `org-tempo-keywords-alist' and update tempo templates."
104 (mapc 'org--check-org-structure-template-alist '(org-structure-template-alist
105 org-tempo-keywords-alist))
106 (mapc #'org--check-org-structure-template-alist '(org-structure-template-alist
107 org-tempo-keywords-alist))
106108 (let ((keys (org-tempo--keys)))
107109 ;; Check for duplicated snippet keys and warn if any are found.
108110 (when (> (length keys) (length (delete-dups keys)))
118120 "Add block entry from `org-structure-template-alist'."
119121 (let* ((key (format "<%s" (car entry)))
120122 (name (cdr entry))
121 (special (member name '("src" "export"))))
123 (special (member name '("src" "export")))
124 (upcase? (string= (car (split-string name))
125 (upcase (car (split-string name))))))
122126 (tempo-define-template (format "org-%s" (replace-regexp-in-string " " "-" name))
123 `(,(format "#+begin_%s%s" name (if special " " ""))
127 `(,(format "#+%s_%s%s"
128 (if upcase? "BEGIN" "begin")
129 name
130 (if special " " ""))
124131 ,(when special 'p) '> n ,(unless special 'p) n
125 ,(format "#+end_%s" (car (split-string name " ")))
132 ,(format "#+%s_%s"
133 (if upcase? "END" "end")
134 (car (split-string name " ")))
126135 >)
127136 key
128137 (format "Insert a %s block" name)
175184 ;; Org Tempo is set up with each new Org buffer and potentially in the
176185 ;; current Org buffer.
177186
178 (add-hook 'org-mode-hook 'org-tempo-setup)
179 (add-hook 'org-tab-before-tab-emulation-hook 'org-tempo-complete-tag)
187 (add-hook 'org-mode-hook #'org-tempo-setup)
188 (add-hook 'org-tab-before-tab-emulation-hook #'org-tempo-complete-tag)
180189
181190 ;; Enable Org Tempo in all open Org buffers.
182191 (dolist (b (org-buffer-list 'files))
00 ;;; org-timer.el --- Timer code for Org mode -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2008-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2008-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77 ;;
88 ;; This file is part of GNU Emacs.
99 ;;
3333 ;; and `org-timer-set-timer' to start the countdown timer.
3434
3535 ;;; Code:
36
37 (require 'org-macs)
38 (org-assert-version)
3639
3740 (require 'cl-lib)
3841 (require 'org-clock)
138141 (format "Restart timer with offset [%s]: " def)))
139142 (unless (string-match "\\S-" s) (setq s def))
140143 (setq delta (org-timer-hms-to-secs (org-timer-fix-incomplete s)))))
141 (setq org-timer-start-time (org-time-since delta)))
144 (setq org-timer-start-time (time-since delta)))
142145 (setq org-timer-pause-time nil)
143146 (org-timer-set-mode-line 'on)
144147 (message "Timer start time set to %s, current value is %s"
162165 (setq org-timer-countdown-timer
163166 (org-timer--run-countdown-timer
164167 new-secs org-timer-countdown-timer-title))
165 (setq org-timer-start-time (org-time-add nil new-secs)))
168 (setq org-timer-start-time (time-add nil new-secs)))
166169 (setq org-timer-start-time
167 (org-time-since (- pause-secs start-secs))))
170 (time-since (- pause-secs start-secs))))
168171 (setq org-timer-pause-time nil)
169172 (org-timer-set-mode-line 'on)
170173 (run-hooks 'org-timer-continue-hook)
386389 ;; Note: Once our minimal require is Emacs 27, we can drop this
387390 ;; org-time-convert-to-integer call.
388391 (org-time-convert-to-integer
389 (org-time-subtract (timer--time org-timer-countdown-timer) nil))))))
392 (time-subtract (timer--time org-timer-countdown-timer) nil))))))
390393
391394 ;;;###autoload
392395 (defun org-timer-set-timer (&optional opt)
447450 (org-timer--run-countdown-timer
448451 secs org-timer-countdown-timer-title))
449452 (run-hooks 'org-timer-set-hook)
450 (setq org-timer-start-time (org-time-add nil secs))
453 (setq org-timer-start-time (time-add nil secs))
451454 (setq org-timer-pause-time nil)
452455 (org-timer-set-mode-line 'on))))))
453456
477480 (with-current-buffer (marker-buffer marker)
478481 (org-with-wide-buffer
479482 (goto-char hdmarker)
480 (org-show-entry)
481483 (or (ignore-errors (org-get-heading))
482484 (buffer-name (buffer-base-buffer))))))))
483485 ((derived-mode-p 'org-mode)
+2612
-2759
lisp/org.el less more
00 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
11
22 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
3 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
44 ;;
55 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
66 ;; Maintainer: Bastien Guerry <bzg@gnu.org>
77 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: https://orgmode.org
9 ;; Package-Requires: ((emacs "25.1"))
10
11 ;; Version: 9.5.2
8 ;; URL: https://orgmode.org
9 ;; Package-Requires: ((emacs "26.1"))
10
11 ;; Version: 9.6.8
1212
1313 ;; This file is part of GNU Emacs.
1414 ;;
5555 ;; Documentation
5656 ;; -------------
5757 ;; The documentation of Org mode can be found in the TeXInfo file. The
58 ;; distribution also contains a PDF version of it. At the homepage of
59 ;; Org mode, you can read the same text online as HTML. There is also an
60 ;; excellent reference card made by Philip Rooke. This card can be found
61 ;; in the doc/ directory.
58 ;; distribution also contains a PDF version of it. At the Org mode website,
59 ;; you can read the same text online as HTML. There is also an excellent
60 ;; reference card made by Philip Rooke. This card can be found in the
61 ;; doc/ directory.
6262 ;;
6363 ;; A list of recent changes can be found at
6464 ;; https://orgmode.org/Changes.html
7070
7171 ;;;; Require other packages
7272
73 (require 'org-compat)
74 (org-assert-version)
75
7376 (require 'cl-lib)
7477
7578 (eval-when-compile (require 'gnus-sum))
7881 (require 'find-func)
7982 (require 'format-spec)
8083
81 (or (eq this-command 'eval-buffer)
82 (condition-case nil
83 (load (concat (file-name-directory load-file-name)
84 "org-loaddefs.el")
85 nil t t t)
86 (error
87 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
88 (sit-for 3)
89 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
90 (sit-for 3))))
84 (condition-case nil
85 (load (concat (file-name-directory load-file-name)
86 "org-loaddefs")
87 nil t nil t)
88 (error
89 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
90 (sit-for 3)
91 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
92 (sit-for 3)))
9193
9294 (eval-and-compile (require 'org-macs))
9395 (require 'org-compat)
9496 (require 'org-keys)
9597 (require 'ol)
9698 (require 'oc)
97 (require 'oc-basic)
9899 (require 'org-table)
100 (require 'org-fold)
101
102 (require 'org-cycle)
103 (defvaralias 'org-hide-block-startup 'org-cycle-hide-block-startup)
104 (defvaralias 'org-hide-drawer-startup 'org-cycle-hide-drawer-startup)
105 (defvaralias 'org-pre-cycle-hook 'org-cycle-pre-hook)
106 (defvaralias 'org-tab-first-hook 'org-cycle-tab-first-hook)
107 (defalias 'org-global-cycle #'org-cycle-global)
108 (defalias 'org-overview #'org-cycle-overview)
109 (defalias 'org-content #'org-cycle-content)
110 (defalias 'org-reveal #'org-fold-reveal)
111 (defalias 'org-force-cycle-archived #'org-cycle-force-archived)
99112
100113 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
101114 ;; some places -- e.g. see the macro `org-with-limited-levels'.
118131 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
119132 (declare-function org-add-archive-files "org-archive" (files))
120133 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
134 (declare-function org-agenda-todo-yesterday "org-agenda" (&optional arg))
121135 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
122136 (declare-function org-agenda-redo "org-agenda" (&optional all))
123137 (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
151165 (declare-function org-columns-insert-dblock "org-colview" ())
152166 (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
153167 (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
154 (declare-function org-element-at-point "org-element" ())
168 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
169 (declare-function org-element-at-point-no-context "org-element" (&optional pom))
155170 (declare-function org-element-cache-refresh "org-element" (pos))
156 (declare-function org-element-cache-reset "org-element" (&optional all))
171 (declare-function org-element-cache-reset "org-element" (&optional all no-persistence))
172 (declare-function org-element-cache-map "org-element" (func &rest keys))
157173 (declare-function org-element-contents "org-element" (element))
158174 (declare-function org-element-context "org-element" (&optional element))
159175 (declare-function org-element-copy "org-element" (datum))
161177 (declare-function org-element-extract-element "org-element" (element))
162178 (declare-function org-element-insert-before "org-element" (element location))
163179 (declare-function org-element-interpret-data "org-element" (data))
180 (declare-function org-element-keyword-parser "org-element" (limit affiliated))
164181 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
165182 (declare-function org-element-link-parser "org-element" ())
166183 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
173190 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
174191 (declare-function org-element-timestamp-parser "org-element" ())
175192 (declare-function org-element-type "org-element" (element))
193 (declare-function org-element--cache-active-p "org-element" ())
176194 (declare-function org-export-dispatch "ox" (&optional arg))
177195 (declare-function org-export-get-backend "ox" (name))
178196 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
187205 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
188206 (declare-function org-num-mode "org-num" (&optional arg))
189207 (declare-function org-plot/gnuplot "org-plot" (&optional params))
208 (declare-function org-persist-load "org-persist" (container &optional associated hash-must-match))
190209 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
191210 (declare-function org-timer "org-timer" (&optional restart no-insert))
192211 (declare-function org-timer-item "org-timer" (&optional arg))
197216 (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
198217 (declare-function org-update-radio-target-regexp "ol" ())
199218
219 (defvar org-agenda-buffer-name)
200220 (defvar org-element-paragraph-separate)
221 (defvar org-element-cache-map-continue-from)
222 (defvar org-element--timestamp-regexp)
201223 (defvar org-indent-indentation-per-level)
202224 (defvar org-radio-target-regexp)
203225 (defvar org-target-link-regexp)
212234 ;;;###autoload
213235 (defun org-babel-do-load-languages (sym value)
214236 "Load the languages defined in `org-babel-load-languages'."
215 (set-default sym value)
237 (set-default-toplevel-value sym value)
216238 (dolist (pair org-babel-load-languages)
217239 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
218240 (if active
232254 byte-compiled before it is loaded."
233255 (interactive "fFile to load: \nP")
234256 (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
235 ;; Tangle only if the Org file is newer than the Elisp file.
236 (unless (org-file-newer-than-p
237 tangled-file
238 (file-attribute-modification-time
239 (file-attributes (file-truename file))))
257 ;; Tangle only if the Elisp file is older than the Org file.
258 ;; Catch the case when the .el file exists while the .org file is missing.
259 (unless (file-exists-p file)
260 (error "File to tangle does not exist: %s" file))
261 (when (file-newer-than-file-p file tangled-file)
240262 (org-babel-tangle-file file
241263 tangled-file
242264 (rx string-start
243265 (or "emacs-lisp" "elisp")
244 string-end)))
266 string-end))
267 ;; Make sure that tangled file modification time is
268 ;; updated even when `org-babel-tangle-file' does not make changes.
269 ;; This avoids re-tangling changed FILE where the changes did
270 ;; not affect the tangled code.
271 (when (file-exists-p tangled-file)
272 (set-file-times tangled-file)))
245273 (if compile
246274 (progn
247275 (byte-compile-file tangled-file)
248 (load tangled-file)
276 (load-file (byte-compile-dest-file tangled-file))
249277 (message "Compiled and loaded %s" tangled-file))
250278 (load-file tangled-file)
251279 (message "Loaded %s" tangled-file))))
253281 (defcustom org-babel-load-languages '((emacs-lisp . t))
254282 "Languages which can be evaluated in Org buffers.
255283 \\<org-mode-map>
256 This list can be used to load support for any of the languages
257 below. Each language will depend on a different set of system
258 executables and/or Emacs modes.
284 This list can be used to load support for any of the available
285 languages with babel support (see info node `(org) Languages'). Each
286 language will depend on a different set of system executables and/or
287 Emacs modes.
259288
260289 When a language is \"loaded\", code blocks in that language can
261290 be evaluated with `org-babel-execute-src-block', which is bound
267296 requirement."
268297 :group 'org-babel
269298 :set 'org-babel-do-load-languages
270 :version "24.1"
299 :package-version '(Org . "9.6")
271300 :type '(alist :tag "Babel Languages"
272301 :key-type
273302 (choice
274303 (const :tag "Awk" awk)
275 (const :tag "C" C)
304 (const :tag "C, D, C++, and cpp" C)
276305 (const :tag "R" R)
277306 (const :tag "Calc" calc)
278 (const :tag "Clojure" clojure)
307 (const :tag "Clojure and ClojureScript" clojure)
279308 (const :tag "CSS" css)
280309 (const :tag "Ditaa" ditaa)
281310 (const :tag "Dot" dot)
282311 (const :tag "Emacs Lisp" emacs-lisp)
312 (const :tag "Eshell" eshell)
283313 (const :tag "Forth" forth)
284314 (const :tag "Fortran" fortran)
285 (const :tag "Gnuplot" gnuplot)
315 (const :tag "GnuPlot" gnuplot)
316 (const :tag "Groovy" groovy)
286317 (const :tag "Haskell" haskell)
287318 (const :tag "Java" java)
288 (const :tag "Javascript" js)
289 (const :tag "LaTeX" latex)
290 (const :tag "Lilypond" lilypond)
319 (const :tag "JavaScript" js)
320 (const :tag "Julia" julia)
321 (const :tag "LaTeX" latex)
322 (const :tag "LilyPond" lilypond)
291323 (const :tag "Lisp" lisp)
324 (const :tag "Lua" lua)
292325 (const :tag "Makefile" makefile)
293326 (const :tag "Maxima" maxima)
294 (const :tag "Matlab" matlab)
295 (const :tag "Ocaml" ocaml)
296 (const :tag "Octave" octave)
327 (const :tag "OCaml" ocaml)
328 (const :tag "Octave and MatLab" octave)
297329 (const :tag "Org" org)
298330 (const :tag "Perl" perl)
299 (const :tag "Pico Lisp" picolisp)
331 (const :tag "Processing" processing)
300332 (const :tag "PlantUML" plantuml)
301333 (const :tag "Python" python)
302334 (const :tag "Ruby" ruby)
303335 (const :tag "Sass" sass)
304 (const :tag "Scala" scala)
305336 (const :tag "Scheme" scheme)
306337 (const :tag "Screen" screen)
338 (const :tag "Sed" sed)
307339 (const :tag "Shell Script" shell)
308340 (const :tag "Sql" sql)
309 (const :tag "Sqlite" sqlite)
310 (const :tag "Stan" stan))
341 (const :tag "Sqlite" sqlite))
311342 :value-type (boolean :tag "Activate" :value t)))
312343
313344 ;;;; Customization variables
332363 FULL is given."
333364 (interactive (list current-prefix-arg t (not current-prefix-arg)))
334365 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
335 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
366 (save-load-suffixes load-suffixes)
336367 (load-suffixes (list ".el"))
337368 (org-install-dir
338369 (ignore-errors (org-find-library-dir "org-loaddefs"))))
407438 This one does not require the space after the date, so it can be used
408439 on a string that terminates immediately after the date.")
409440
410 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
441 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\(?: *\\([^]+0-9>\r\n -]+\\)\\)?\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
411442 "Regular expression matching time strings for analysis.")
412443
413444 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
439470 "Regular expression for specifying repeated events.
440471 After a match, group 1 contains the repeat expression.")
441472
442 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
443 "Formats for `format-time-string' which are used for time stamps.")
473 (defconst org-time-stamp-formats '("%Y-%m-%d %a" . "%Y-%m-%d %a %H:%M")
474 "Formats for `format-time-string' which are used for time stamps.
475
476 The value is a cons cell containing two strings. The `car' and `cdr'
477 of the cons cell are used to format time stamps that do not and do
478 contain time, respectively.
479
480 Leading \"<\"/\"[\" and trailing \">\"/\"]\" pair will be stripped
481 from the format strings.
482
483 Also, see `org-time-stamp-format'.")
444484
445485 ;;;; Clock and Planning
446486
565605
566606 (defconst org-property-drawer-re
567607 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
568 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
608 "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
569609 "[ \t]*:END:[ \t]*$")
570610 "Matches an entire property drawer.")
571611
681721
682722 (defun org-set-modules (var value)
683723 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
684 (set var value)
724 (set-default-toplevel-value var value)
685725 (when (featurep 'org)
686726 (org-load-modules-maybe 'force)
727 ;; FIXME: We can't have all the requires at top-level due to
728 ;; circular dependencies. Yet, this function might sometimes be
729 ;; called when 'org-element is not loaded.
730 (require 'org-element)
687731 (org-element-cache-reset 'all)))
688732
689733 (defcustom org-modules '(ol-doi ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
812856 :package-version '(Org . "9.0")
813857 :initialize 'custom-initialize-set
814858 :set (lambda (var val)
815 (if (not (featurep 'ox)) (set-default var val)
859 (if (not (featurep 'ox)) (set-default-toplevel-value var val)
816860 ;; Any back-end not required anymore (not present in VAL and not
817861 ;; a parent of any back-end in the new value) is removed from the
818862 ;; list of registered back-ends.
837881 backend))
838882 ((not (memq backend new-list)) (push backend new-list))))
839883 ;; Set VAR to that list with fixed dependencies.
840 (set-default var new-list))))
884 (set-default-toplevel-value var new-list))))
841885 :type '(set :greedy t
842886 (const :tag " ascii Export buffer to ASCII format" ascii)
843887 (const :tag " beamer Export buffer to Beamer presentation" beamer)
939983 :group 'org-todo
940984 :group 'org-archive)
941985
986 (defgroup org-startup nil
987 "Startup options Org uses when first visiting a file."
988 :tag "Org Startup"
989 :group 'org)
990
942991 (defcustom org-startup-folded 'showeverything
943992 "Non-nil means entering Org mode will switch to OVERVIEW.
944993
11711220 :tag "Org Structure"
11721221 :group 'org)
11731222
1174 (defgroup org-reveal-location nil
1175 "Options about how to make context of a location visible."
1176 :tag "Org Reveal Location"
1177 :group 'org-structure)
1178
1179 (defcustom org-show-context-detail '((agenda . local)
1180 (bookmark-jump . lineage)
1181 (isearch . lineage)
1182 (default . ancestors))
1183 "Alist between context and visibility span when revealing a location.
1184
1185 \\<org-mode-map>Some actions may move point into invisible
1186 locations. As a consequence, Org always exposes a neighborhood
1187 around point. How much is shown depends on the initial action,
1188 or context. Valid contexts are
1189
1190 agenda when exposing an entry from the agenda
1191 org-goto when using the command `org-goto' (`\\[org-goto]')
1192 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1193 tags-tree when constructing a sparse tree based on tags matches
1194 link-search when exposing search matches associated with a link
1195 mark-goto when exposing the jump goal of a mark
1196 bookmark-jump when exposing a bookmark location
1197 isearch when exiting from an incremental search
1198 default default for all contexts not set explicitly
1199
1200 Allowed visibility spans are
1201
1202 minimal show current headline; if point is not on headline,
1203 also show entry
1204
1205 local show current headline, entry and next headline
1206
1207 ancestors show current headline and its direct ancestors; if
1208 point is not on headline, also show entry
1209
1210 ancestors-full show current subtree and its direct ancestors
1211
1212 lineage show current headline, its direct ancestors and all
1213 their children; if point is not on headline, also show
1214 entry and first child
1215
1216 tree show current headline, its direct ancestors and all
1217 their children; if point is not on headline, also show
1218 entry and all children
1219
1220 canonical show current headline, its direct ancestors along with
1221 their entries and children; if point is not located on
1222 the headline, also show current entry and all children
1223
1224 As special cases, a nil or t value means show all contexts in
1225 `minimal' or `canonical' view, respectively.
1226
1227 Some views can make displayed information very compact, but also
1228 make it harder to edit the location of the match. In such
1229 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1230 more context."
1231 :group 'org-reveal-location
1232 :version "26.1"
1233 :package-version '(Org . "9.0")
1234 :type '(choice
1235 (const :tag "Canonical" t)
1236 (const :tag "Minimal" nil)
1237 (repeat :greedy t :tag "Individual contexts"
1238 (cons
1239 (choice :tag "Context"
1240 (const agenda)
1241 (const org-goto)
1242 (const occur-tree)
1243 (const tags-tree)
1244 (const link-search)
1245 (const mark-goto)
1246 (const bookmark-jump)
1247 (const isearch)
1248 (const default))
1249 (choice :tag "Detail level"
1250 (const minimal)
1251 (const local)
1252 (const ancestors)
1253 (const ancestors-full)
1254 (const lineage)
1255 (const tree)
1256 (const canonical))))))
1257
12581223 (defcustom org-indirect-buffer-display 'other-window
12591224 "How should indirect tree buffers be displayed?
12601225
13541319 \"evince -p %1 %s\")
13551320 to open [[file:document.pdf::5]] with evince at page 5.
13561321
1322 Likely, you will need more entries: without page
1323 number; with search pattern; with cross-reference
1324 anchor; some combination of options. Consider simple
1325 pattern here and a Lisp function to determine command
1326 line arguments instead. Passing argument list to
1327 `call-process' or `make-process' directly allows to
1328 avoid treating some character in peculiar file names
1329 as shell specialls causing executing part of file
1330 name as a subcommand.
1331
13571332 `directory' Matches a directory
1358 `remote' Matches a remote file, accessible through tramp or efs.
1333 `remote' Matches a remote file, accessible through tramp.
13591334 Remote files most likely should be visited through Emacs
13601335 because external applications cannot handle such paths.
13611336 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
14111386 (string :tag "Command")
14121387 (function :tag "Function")))))
14131388
1389 (defcustom org-resource-download-policy 'prompt
1390 "The policy applied to requests to obtain remote resources.
1391
1392 This affects keywords like #+setupfile and #+include on export,
1393 `org-persist-write:url',and `org-attach-url' in non-interactive
1394 Emacs sessions.
1395
1396 This recognizes four possible values:
1397 - t, remote resources should always be downloaded.
1398 - prompt, you will be prompted to download resources not considered safe.
1399 - safe, only resources considered safe will be downloaded.
1400 - nil, never download remote resources.
1401
1402 A resource is considered safe if it matches one of the patterns
1403 in `org-safe-remote-resources'."
1404 :group 'org
1405 :package-version '(Org . "9.6")
1406 :type '(choice (const :tag "Always download remote resources" t)
1407 (const :tag "Prompt before downloading an unsafe resource" prompt)
1408 (const :tag "Only download resources considered safe" safe)
1409 (const :tag "Never download any resources" nil)))
1410
1411 (defcustom org-safe-remote-resources nil
1412 "A list of regexp patterns matching safe URIs.
1413 URI regexps are applied to both URLs and Org files requesting
1414 remote resources."
1415 :group 'org
1416 :package-version '(Org . "9.6")
1417 :type '(repeat regexp))
1418
14141419 (defcustom org-open-non-existing-files nil
14151420 "Non-nil means `org-open-file' opens non-existing files.
14161421
14451450 is not set."
14461451 :group 'org-structure
14471452 :type 'plist)
1448
1449 (defgroup org-cycle nil
1450 "Options concerning visibility cycling in Org mode."
1451 :tag "Org Cycle"
1452 :group 'org-structure)
1453
1454 (defcustom org-cycle-skip-children-state-if-no-children t
1455 "Non-nil means skip CHILDREN state in entries that don't have any."
1456 :group 'org-cycle
1457 :type 'boolean)
1458
1459 (defcustom org-cycle-max-level nil
1460 "Maximum level which should still be subject to visibility cycling.
1461 Levels higher than this will, for cycling, be treated as text, not a headline.
1462 When `org-odd-levels-only' is set, a value of N in this variable actually
1463 means 2N-1 stars as the limiting headline.
1464 When nil, cycle all levels.
1465 Note that the limiting level of cycling is also influenced by
1466 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1467 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1468 than its value."
1469 :group 'org-cycle
1470 :type '(choice
1471 (const :tag "No limit" nil)
1472 (integer :tag "Maximum level")))
1473
1474 (defcustom org-hide-block-startup nil
1475 "Non-nil means entering Org mode will fold all blocks.
1476 This can also be set in on a per-file basis with
1477
1478 #+STARTUP: hideblocks
1479 #+STARTUP: showblocks"
1480 :group 'org-startup
1481 :group 'org-cycle
1482 :type 'boolean)
1483
1484 (defcustom org-cycle-global-at-bob nil
1485 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1486
1487 This makes it possible to do global cycling without having to use `S-TAB'
1488 or `\\[universal-argument] TAB'. For this special case to work, the first \
1489 line of the buffer
1490 must not be a headline -- it may be empty or some other text.
1491
1492 When used in this way, `org-cycle-hook' is disabled temporarily to make
1493 sure the cursor stays at the beginning of the buffer.
1494
1495 When this option is nil, don't do anything special at the beginning of
1496 the buffer."
1497 :group 'org-cycle
1498 :type 'boolean)
1499
1500 (defcustom org-cycle-level-after-item/entry-creation t
1501 "Non-nil means cycle entry level or item indentation in new empty entries.
1502
1503 When the cursor is at the end of an empty headline, i.e., with only stars
1504 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1505 and then all possible ancestor states, before returning to the original state.
1506 This makes data entry extremely fast: M-RET to create a new headline,
1507 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1508
1509 When the cursor is at the end of an empty plain list item, one TAB will
1510 make it a subitem, two or more tabs will back up to make this an item
1511 higher up in the item hierarchy."
1512 :group 'org-cycle
1513 :type 'boolean)
1514
1515 (defcustom org-cycle-emulate-tab t
1516 "Where should `org-cycle' emulate TAB.
1517 nil Never
1518 white Only in completely white lines
1519 whitestart Only at the beginning of lines, before the first non-white char
1520 t Everywhere except in headlines
1521 exc-hl-bol Everywhere except at the start of a headline
1522 If TAB is used in a place where it does not emulate TAB, the current subtree
1523 visibility is cycled."
1524 :group 'org-cycle
1525 :type '(choice (const :tag "Never" nil)
1526 (const :tag "Only in completely white lines" white)
1527 (const :tag "Before first char in a line" whitestart)
1528 (const :tag "Everywhere except in headlines" t)
1529 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1530
1531 (defcustom org-cycle-separator-lines 2
1532 "Number of empty lines needed to keep an empty line between collapsed trees.
1533 If you leave an empty line between the end of a subtree and the following
1534 headline, this empty line is hidden when the subtree is folded.
1535 Org mode will leave (exactly) one empty line visible if the number of
1536 empty lines is equal or larger to the number given in this variable.
1537 So the default 2 means at least 2 empty lines after the end of a subtree
1538 are needed to produce free space between a collapsed subtree and the
1539 following headline.
1540
1541 If the number is negative, and the number of empty lines is at least -N,
1542 all empty lines are shown.
1543
1544 Special case: when 0, never leave empty lines in collapsed view."
1545 :group 'org-cycle
1546 :type 'integer)
1547 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1548
1549 (defcustom org-pre-cycle-hook nil
1550 "Hook that is run before visibility cycling is happening.
1551 The function(s) in this hook must accept a single argument which indicates
1552 the new state that will be set right after running this hook. The
1553 argument is a symbol. Before a global state change, it can have the values
1554 `overview', `content', or `all'. Before a local state change, it can have
1555 the values `folded', `children', or `subtree'."
1556 :group 'org-cycle
1557 :type 'hook)
1558
1559 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1560 org-cycle-hide-drawers
1561 org-cycle-show-empty-lines
1562 org-optimize-window-after-visibility-change)
1563 "Hook that is run after `org-cycle' has changed the buffer visibility.
1564 The function(s) in this hook must accept a single argument which indicates
1565 the new state that was set by the most recent `org-cycle' command. The
1566 argument is a symbol. After a global state change, it can have the values
1567 `overview', `contents', or `all'. After a local state change, it can have
1568 the values `folded', `children', or `subtree'."
1569 :group 'org-cycle
1570 :package-version '(Org . "9.4")
1571 :type 'hook)
15721453
15731454 (defgroup org-edit-structure nil
15741455 "Options concerning structure editing in Org mode."
16681549 (const :tag "reversed: after tags first" reversed)))))
16691550
16701551 (defcustom org-special-ctrl-k nil
1671 "Non-nil means `C-k' will behave specially in headlines.
1672 When nil, `C-k' will call the default `kill-line' command.
1673 When t, the following will happen while the cursor is in the headline:
1674
1675 - When at the beginning of a headline, kill the entire subtree.
1676 - When in the middle of the headline text, kill the text up to the tags.
1677 - When after the headline text and before the tags, kill all the tags."
1552 "Non-nil means that \\<org-mode-map>\\[org-kill-line] \
1553 will behave specially in headlines.
1554
1555 When nil, \\[org-kill-line] will call the default `kill-line' command.
1556 Otherwise, the following will happen when point is in a headline:
1557
1558 - At the beginning of a headline, kill the entire line.
1559 - In the middle of the headline text, kill the text up to the tags.
1560 - After the headline text and before the tags, kill all the tags."
16781561 :group 'org-edit-structure
16791562 :type 'boolean)
16801563
16921575 (const :tag "Never kill a hidden subtree with C-k" error)))
16931576
16941577 (defcustom org-special-ctrl-o t
1695 "Non-nil means, make `C-o' insert a row in tables."
1578 "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
16961579 :group 'org-edit-structure
16971580 :type 'boolean)
1698
1699 (defcustom org-catch-invisible-edits nil
1700 "Check if in invisible region before inserting or deleting a character.
1701 Valid values are:
1702
1703 nil Do not check, so just do invisible edits.
1704 error Throw an error and do nothing.
1705 show Make point visible, and do the requested edit.
1706 show-and-error Make point visible, then throw an error and abort the edit.
1707 smart Make point visible, and do insertion/deletion if it is
1708 adjacent to visible text and the change feels predictable.
1709 Never delete a previously invisible character or add in the
1710 middle or right after an invisible region. Basically, this
1711 allows insertion and backward-delete right before ellipses.
1712 FIXME: maybe in this case we should not even show?"
1713 :group 'org-edit-structure
1714 :version "24.1"
1715 :type '(choice
1716 (const :tag "Do not check" nil)
1717 (const :tag "Throw error when trying to edit" error)
1718 (const :tag "Unhide, but do not do the edit" show-and-error)
1719 (const :tag "Show invisible part and do the edit" show)
1720 (const :tag "Be smart and do the right thing" smart)))
17211581
17221582 (defcustom org-yank-folded-subtrees t
17231583 "Non-nil means when yanking subtrees, fold them.
17601620 (const table)
17611621 (const default))
17621622 (boolean)))))
1763
17641623
17651624 (defcustom org-insert-heading-respect-content nil
17661625 "Non-nil means insert new headings after the current subtree.
20221881 :group 'org-todo
20231882 :set (lambda (var val)
20241883 (cond
2025 ((eq var t) (set var 'auto))
2026 ((eq var 'prefix) (set var nil))
2027 (t (set var val))))
1884 ((eq var t) (set-default-toplevel-value var 'auto))
1885 ((eq var 'prefix) (set-default-toplevel-value var nil))
1886 (t (set-default-toplevel-value var val))))
20281887 :type '(choice
20291888 (const :tag "Never" nil)
20301889 (const :tag "Automatically, when key letter have been defined" auto)
21061965 Finally, if the parent is blocked because of ordered siblings of its own,
21071966 the child will also be blocked."
21081967 :set (lambda (var val)
2109 (set var val)
1968 (set-default-toplevel-value var val)
21101969 (if val
21111970 (add-hook 'org-blocker-hook
21121971 'org-block-todo-from-children-or-siblings-or-parent)
21241983 restart Emacs after a change to make the change effective. The only way
21251984 to change it while Emacs is running is through the customize interface."
21261985 :set (lambda (var val)
2127 (set var val)
1986 (set-default-toplevel-value var val)
21281987 (if val
21291988 (add-hook 'org-blocker-hook
21301989 'org-block-todo-from-checkboxes)
25752434 To turn this on on a per-file basis, insert anywhere in the file:
25762435 #+STARTUP: customtime"
25772436 :group 'org-time
2578 :set 'set-default
25792437 :type 'sexp)
25802438 (make-variable-buffer-local 'org-display-custom-times)
25812439
25822440 (defcustom org-time-stamp-custom-formats
2583 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2584 "Custom formats for time stamps. See `format-time-string' for the syntax.
2441 '("%m/%d/%y %a" . "%m/%d/%y %a %H:%M") ; american
2442 "Custom formats for time stamps.
2443
2444 See `format-time-string' for the syntax.
2445
25852446 These are overlaid over the default ISO format if the variable
25862447 `org-display-custom-times' is set. Time like %H:%M should be at the
25872448 end of the second format. The custom formats are also honored by export
2588 commands, if custom time display is turned on at the time of export."
2449 commands, if custom time display is turned on at the time of export.
2450
2451 Leading \"<\" and trailing \">\" pair will be stripped from the format
2452 strings."
25892453 :group 'org-time
2590 :type 'sexp)
2591
2592 (defun org-time-stamp-format (&optional long inactive)
2593 "Get the right format for a time string."
2594 (let ((f (if long (cdr org-time-stamp-formats)
2595 (car org-time-stamp-formats))))
2596 (if inactive
2597 (concat "[" (substring f 1 -1) "]")
2598 f)))
2454 :package-version '(Org . "9.6")
2455 :type '(cons string string))
2456
2457 (defun org-time-stamp-format (&optional with-time inactive custom)
2458 "Get timestamp format for a time string.
2459
2460 The format is based on `org-time-stamp-formats' (if CUSTOM is nil) or or
2461 `org-time-stamp-custom-formats' (if CUSTOM if non-nil).
2462
2463 When optional argument WITH-TIME is non-nil, the timestamp will contain
2464 time.
2465
2466 When optional argument INACTIVE is nil, format active timestamp.
2467 When `no-brackets', strip timestamp brackets.
2468 Otherwise, format inactive timestamp."
2469 (let ((format (funcall
2470 (if with-time #'cdr #'car)
2471 (if custom
2472 org-time-stamp-custom-formats
2473 org-time-stamp-formats))))
2474 ;; Strip brackets, if any.
2475 (when (or (and (string-prefix-p "<" format)
2476 (string-suffix-p ">" format))
2477 (and (string-prefix-p "[" format)
2478 (string-suffix-p "]" format)))
2479 (setq format (substring format 1 -1)))
2480 (pcase inactive
2481 (`no-brackets format)
2482 (`nil (concat "<" format ">"))
2483 (_ (concat "[" format "]")))))
25992484
26002485 (defcustom org-deadline-warning-days 14
26012486 "Number of days before expiration during which a deadline becomes active.
29742859 :group 'org-tags
29752860 :type '(choice
29762861 (const :tag "No sorting" nil)
2977 (const :tag "Alphabetical" org-string-collate-lessp)
2862 (const :tag "Alphabetical" string-collate-lessp)
29782863 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
29792864 (function :tag "Custom function" nil)))
29802865
30622947 ((listp org-use-property-inheritance)
30632948 (member-ignore-case property org-use-property-inheritance))
30642949 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2950
2951 (defcustom org-property-separators nil
2952 "An alist to control how properties are combined.
2953
2954 The car of each item should be either a list of property names or
2955 a regular expression, while the cdr should be the separator to
2956 use when combining that property.
2957
2958 If an alist item cannot be found that matches a given property, a
2959 single space will be used as the separator."
2960 :group 'org-properties
2961 :package-version '(Org . "9.6")
2962 :type '(alist :key-type (choice (repeat :tag "Properties" string)
2963 (string :tag "Regular Expression"))
2964 :value-type (restricted-sexp :tag "Separator"
2965 :match-alternatives (stringp)
2966 :value " ")))
2967
2968 (defun org--property-get-separator (property)
2969 "Get the separator to use for combining PROPERTY."
2970 (or
2971 (catch 'separator
2972 (dolist (spec org-property-separators)
2973 (if (listp (car spec))
2974 (if (member property (car spec))
2975 (throw 'separator (cdr spec)))
2976 (if (string-match-p (car spec) property)
2977 (throw 'separator (cdr spec))))))
2978 " "))
30652979
30662980 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
30672981 "The default column format, if no other format has been defined.
32993213 %i: The LaTeX fragment to be converted.
33003214
33013215 For example, this could be used with LaTeXML as
3302 \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
3216 \"latexmlc \\='literal:%i\\=' --profile=math --preload=siunitx.sty 2>/dev/null\"."
33033217 :group 'org-latex
33043218 :package-version '(Org . "9.4")
33053219 :type '(choice
33243238 :image-output-type "png"
33253239 :image-size-adjust (1.0 . 1.0)
33263240 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3327 :image-converter ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
3241 :image-converter ("dvipng -D %D -T tight -o %O %f")
3242 :transparent-image-converter
3243 ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
33283244 (dvisvgm
33293245 :programs ("latex" "dvisvgm")
33303246 :description "dvi > svg"
33333249 :image-output-type "svg"
33343250 :image-size-adjust (1.7 . 1.5)
33353251 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3336 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3252 :image-converter ("dvisvgm %f --no-fonts --exact-bbox --scale=%S --output=%O"))
33373253 (imagemagick
33383254 :programs ("latex" "convert")
33393255 :description "pdf > png"
33793295 given to the shell and supports any of the following
33803296 place-holders defined below.
33813297
3298 If set, :transparent-image-converter is used instead of :image-converter to
3299 convert an image when the background color is nil or \"Transparent\".
3300
33823301 Place-holders used by `:image-converter' and `:latex-compiler':
33833302
33843303 %f input file name
33923311 %S the image size scale ratio, which is used to adjust image size by some
33933312 processing commands."
33943313 :group 'org-latex
3395 :version "26.1"
3396 :package-version '(Org . "9.0")
3314 :package-version '(Org . "9.6")
33973315 :type '(alist :tag "LaTeX to image backends"
33983316 :value-type (plist)))
33993317
34223340
34233341 (defcustom org-format-latex-header "\\documentclass{article}
34243342 \\usepackage[usenames]{color}
3343 \[DEFAULT-PACKAGES]
34253344 \[PACKAGES]
3426 \[DEFAULT-PACKAGES]
34273345 \\pagestyle{empty} % do not remove
34283346 % The settings below are copied from fullpage.sty
34293347 \\setlength{\\textwidth}{\\paperwidth}
34493367
34503368 (defun org-set-packages-alist (var val)
34513369 "Set the packages alist and make sure it has 3 elements per entry."
3452 (set var (mapcar (lambda (x)
3370 (set-default-toplevel-value var (mapcar (lambda (x)
34533371 (if (and (consp x) (= (length x) 2))
34543372 (list (car x) (nth 1 x) t)
34553373 x))
35643482 :group 'org-export-latex
35653483 :set 'org-set-packages-alist
35663484 :get 'org-get-packages-alist
3567 :type '(repeat
3568 (choice
3569 (list :tag "options/package pair"
3570 (string :tag "options")
3571 (string :tag "package")
3572 (boolean :tag "Snippet"))
3573 (string :tag "A line of LaTeX"))))
3485 :type
3486 '(repeat
3487 (choice
3488 (list :tag "options/package pair"
3489 (string :tag "options")
3490 (string :tag "package")
3491 (boolean :tag "snippet")
3492 (choice
3493 (const :tag "All compilers include this package" nil)
3494 (repeat :tag "Only include from these compilers" string)))
3495 (string :tag "A line of LaTeX"))))
35743496
35753497 (defgroup org-appearance nil
35763498 "Settings for Org mode appearance."
36033525
36043526 (defcustom org-hidden-keywords nil
36053527 "List of symbols corresponding to keywords to be hidden in the Org buffer.
3606 For example, a value \\='(title) for this list makes the document's title
3528 For example, a value (title) for this list makes the document's title
36073529 appear in the buffer without the initial \"#+TITLE:\" part."
36083530 :group 'org-appearance
36093531 :package-version '(Org . "9.5")
36813603 (const :tag "Entities" entities))))
36823604
36833605 (defcustom org-hide-emphasis-markers nil
3684 "Non-nil mean font-lock should hide the emphasis marker characters."
3606 "Non-nil means font-lock should hide the emphasis marker characters."
36853607 :group 'org-appearance
36863608 :type 'boolean
36873609 :safe #'booleanp)
36883610
36893611 (defcustom org-hide-macro-markers nil
3690 "Non-nil mean font-lock should hide the brackets marking macro calls."
3612 "Non-nil means font-lock should hide the brackets marking macro calls."
36913613 :group 'org-appearance
36923614 :type 'boolean)
36933615
36993621 :type 'boolean)
37003622
37013623 (defcustom org-pretty-entities-include-sub-superscripts t
3702 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3624 "Non-nil means pretty entity display includes formatting sub/superscripts."
37033625 :group 'org-appearance
37043626 :version "24.1"
37053627 :type 'boolean)
37223644 (defvar org-emphasis-alist) ; defined just below
37233645 (defun org-set-emph-re (var val)
37243646 "Set variable and compute the emphasis regular expression."
3725 (set var val)
3647 (set-default-toplevel-value var val)
37263648 (when (and (boundp 'org-emphasis-alist)
37273649 (boundp 'org-emphasis-regexp-components)
37283650 org-emphasis-alist org-emphasis-regexp-components)
38053727 (declare-function dired-get-filename
38063728 "dired"
38073729 (&optional localp no-error-if-not-filep))
3808 (declare-function iswitchb-read-buffer
3809 "iswitchb"
3810 (prompt &optional
3811 default require-match _predicate start matches-set))
38123730 (declare-function org-agenda-change-all-lines
38133731 "org-agenda"
38143732 (newhead hdmarker &optional fixface just-this))
38253743 "org-agenda"
38263744 (beg end))
38273745 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3828 (declare-function org-agenda-skip "org-agenda" ())
3746 (declare-function org-agenda-skip "org-agenda" (&optional element))
38293747 (declare-function org-attach-expand "org-attach" (file))
38303748 (declare-function org-attach-reveal "org-attach" ())
38313749 (declare-function org-attach-reveal-in-emacs "org-attach" ())
38423760 (defvar calc-embedded-open-formula)
38433761 (defvar calc-embedded-open-mode)
38443762 (defvar font-lock-unfontify-region-function)
3845 (defvar iswitchb-temp-buflist)
38463763 (defvar org-agenda-tags-todo-honor-ignore-options)
38473764 (defvar remember-data-file)
38483765 (defvar texmathp-why)
39713888 "Non-nil means ignore archived trees when creating column view."
39723889 :group 'org-archive
39733890 :group 'org-properties
3974 :type 'boolean)
3975
3976 (defcustom org-cycle-open-archived-trees nil
3977 "Non-nil means `org-cycle' will open archived trees.
3978 An archived tree is a tree marked with the tag ARCHIVE.
3979 When nil, archived trees will stay folded. You can still open them with
3980 normal outline commands like `show-all', but not with the cycling commands."
3981 :group 'org-archive
3982 :group 'org-cycle
39833891 :type 'boolean)
39843892
39853893 (defcustom org-sparse-tree-open-archived-trees nil
40113919 :package-version '(Org . "8.3")
40123920 :group 'org-sparse-trees)
40133921
4014 (defun org-cycle-hide-archived-subtrees (state)
4015 "Re-hide all archived subtrees after a visibility state change.
4016 STATE should be one of the symbols listed in the docstring of
4017 `org-cycle-hook'."
4018 (when (and (not org-cycle-open-archived-trees)
4019 (not (memq state '(overview folded))))
4020 (save-excursion
4021 (let* ((globalp (memq state '(contents all)))
4022 (beg (if globalp (point-min) (point)))
4023 (end (if globalp (point-max) (org-end-of-subtree t))))
4024 (org-hide-archived-subtrees beg end)
4025 (goto-char beg)
4026 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4027 (message "%s" (substitute-command-keys
4028 "Subtree is archived and stays closed. Use \
4029 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4030
4031 (defun org-force-cycle-archived ()
4032 "Cycle subtree even if it is archived."
4033 (interactive)
4034 (setq this-command 'org-cycle)
4035 (let ((org-cycle-open-archived-trees t))
4036 (call-interactively 'org-cycle)))
4037
4038 (defun org-hide-archived-subtrees (beg end)
4039 "Re-hide all archived subtrees after a visibility state change."
4040 (org-with-wide-buffer
4041 (let ((case-fold-search nil)
4042 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4043 (goto-char beg)
4044 ;; Include headline point is currently on.
4045 (beginning-of-line)
4046 (while (and (< (point) end) (re-search-forward re end t))
4047 (when (member org-archive-tag (org-get-tags nil t))
4048 (org-flag-subtree t)
4049 (org-end-of-subtree t))))))
4050
4051 (defun org-flag-subtree (flag)
4052 (save-excursion
4053 (org-back-to-heading t)
4054 (org-flag-region (line-end-position)
4055 (progn (org-end-of-subtree t) (point))
4056 flag
4057 'outline)))
4058
40593922 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
40603923
40613924 ;; Declare Column View Code
41083971 "Printf format to make regexp to match an exact headline.
41093972 This regexp will match the headline of any node which has the
41103973 exact headline text that is put into the format, but may have any
4111 TODO state, priority and tags.")
3974 TODO state, priority, tags, statistics cookies (at the beginning
3975 or end of the headline title), or COMMENT keyword.")
41123976
41133977 (defvar-local org-todo-line-tags-regexp nil
41143978 "Matches a headline and puts TODO state into group 2 if present.
42174081 ("noptag" org-tag-persistent-alist nil)
42184082 ("hideblocks" org-hide-block-startup t)
42194083 ("nohideblocks" org-hide-block-startup nil)
4084 ("hidedrawers" org-hide-drawer-startup t)
4085 ("nohidedrawers" org-hide-drawer-startup nil)
42204086 ("beamer" org-startup-with-beamer-mode t)
42214087 ("entitiespretty" org-pretty-entities t)
42224088 ("entitiesplain" org-pretty-entities nil))
43714237 (delq nil
43724238 (mapcar
43734239 (lambda (value)
4374 (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4240 (and (or
4241 ;; "abbrev with spaces" spec
4242 (string-match "\\`\"\\(.+[^\\]\\)\"[ \t]+\\(.+\\)" value)
4243 ;; abbrev spec
4244 (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value))
43754245 (cons (match-string-no-properties 1 value)
43764246 (match-string-no-properties 2 value))))
43774247 (cdr (assoc "LINK" alist))))))
44754345 "\\(?: +" org-todo-regexp "\\)?"
44764346 "\\(?: +\\(\\[#.\\]\\)\\)?"
44774347 "\\(?: +"
4348 ;; Headline might be commented
4349 "\\(?:" org-comment-string " +\\)?"
44784350 ;; Stats cookies can be stuck to body.
44794351 "\\(?:\\[[0-9%%/]+\\] *\\)*"
44804352 "\\(%s\\)"
46914563 (cond
46924564 (cache)
46934565 (is-url
4694 (with-current-buffer (url-retrieve-synchronously file)
4695 (goto-char (point-min))
4696 ;; Move point to after the url-retrieve header.
4697 (search-forward "\n\n" nil :move)
4698 ;; Search for the success code only in the url-retrieve header.
4699 (if (save-excursion
4700 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
4701 ;; Update the cache `org--file-cache' and return contents.
4702 (puthash file
4703 (buffer-substring-no-properties (point) (point-max))
4704 org--file-cache)
4705 (funcall (if noerror #'message #'user-error)
4706 "Unable to fetch file from %S"
4707 file)
4708 nil)))
4566 (if (org--should-fetch-remote-resource-p file)
4567 (condition-case error
4568 (with-current-buffer (url-retrieve-synchronously file)
4569 (goto-char (point-min))
4570 ;; Move point to after the url-retrieve header.
4571 (search-forward "\n\n" nil :move)
4572 ;; Search for the success code only in the url-retrieve header.
4573 (if (save-excursion
4574 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
4575 ;; Update the cache `org--file-cache' and return contents.
4576 (puthash file
4577 (buffer-substring-no-properties (point) (point-max))
4578 org--file-cache)
4579 (funcall (if noerror #'message #'user-error)
4580 "Unable to fetch file from %S"
4581 file)
4582 nil))
4583 (error (if noerror
4584 (message "Org could't download \"%s\": %s %S" file (car error) (cdr error))
4585 (signal (car error) (cdr error)))))
4586 (funcall (if noerror #'message #'user-error)
4587 "The remote resource %S is considered unsafe, and will not be downloaded."
4588 file)))
47094589 (t
47104590 (with-temp-buffer
47114591 (condition-case nil
47174597 "Unable to read file %S"
47184598 file)
47194599 nil)))))))
4600
4601 (defun org--should-fetch-remote-resource-p (uri)
4602 "Return non-nil if the URI should be fetched."
4603 (or (eq org-resource-download-policy t)
4604 (org--safe-remote-resource-p uri)
4605 (and (eq org-resource-download-policy 'prompt)
4606 (org--confirm-resource-safe uri))))
4607
4608 (defun org--safe-remote-resource-p (uri)
4609 "Return non-nil if URI is considered safe.
4610 This checks every pattern in `org-safe-remote-resources', and
4611 returns non-nil if any of them match."
4612 (let ((uri-patterns org-safe-remote-resources)
4613 (file-uri (and (buffer-file-name (buffer-base-buffer))
4614 (concat "file://" (file-truename (buffer-file-name (buffer-base-buffer))))))
4615 match-p)
4616 (while (and (not match-p) uri-patterns)
4617 (setq match-p (or (string-match-p (car uri-patterns) uri)
4618 (and file-uri (string-match-p (car uri-patterns) file-uri)))
4619 uri-patterns (cdr uri-patterns)))
4620 match-p))
4621
4622 (defun org--confirm-resource-safe (uri)
4623 "Ask the user if URI should be considered safe, returning non-nil if so."
4624 (unless noninteractive
4625 (let ((current-file (and (buffer-file-name (buffer-base-buffer))
4626 (file-truename (buffer-file-name (buffer-base-buffer)))))
4627 (domain (and (string-match
4628 (rx (seq "http" (? "s") "://")
4629 (optional (+ (not (any "@/\n"))) "@")
4630 (optional "www.")
4631 (one-or-more (not (any ":/?\n"))))
4632 uri)
4633 (match-string 0 uri)))
4634 (buf (get-buffer-create "*Org Remote Resource*")))
4635 ;; Set up the contents of the *Org Remote Resource* buffer.
4636 (with-current-buffer buf
4637 (erase-buffer)
4638 (insert "An org-mode document would like to download "
4639 (propertize uri 'face '(:inherit org-link :weight normal))
4640 ", which is not considered safe.\n\n"
4641 "Do you want to download this? You can type\n "
4642 (propertize "!" 'face 'success)
4643 " to download this resource, and permanently mark it as safe.\n "
4644 (if domain
4645 (concat
4646 (propertize "d" 'face 'success)
4647 " to download this resource, and mark the domain ("
4648 (propertize domain 'face '(:inherit org-link :weight normal))
4649 ") as safe.\n ")
4650 "")
4651 (propertize "f" 'face 'success)
4652 (if current-file
4653 (concat
4654 " to download this resource, and permanently mark all resources in "
4655 (propertize current-file 'face 'underline)
4656 " as safe.\n ")
4657 "")
4658 (propertize "y" 'face 'warning)
4659 " to download this resource, just this once.\n "
4660 (propertize "n" 'face 'error)
4661 " to skip this resource.\n")
4662 (setq-local cursor-type nil)
4663 (set-buffer-modified-p nil)
4664 (goto-char (point-min)))
4665 ;; Display the buffer and read a choice.
4666 (save-window-excursion
4667 (pop-to-buffer buf)
4668 (let* ((exit-chars (append '(?y ?n ?! ?d ?\s) (and current-file '(?f))))
4669 (prompt (format "Please type y, n%s, d, or !%s: "
4670 (if current-file ", f" "")
4671 (if (< (line-number-at-pos (point-max))
4672 (window-body-height))
4673 ""
4674 ", or C-v/M-v to scroll")))
4675 char)
4676 (setq char (read-char-choice prompt exit-chars))
4677 (when (memq char '(?! ?f ?d))
4678 (customize-push-and-save
4679 'org-safe-remote-resources
4680 (list (if (eq char ?d)
4681 (concat "\\`" (regexp-quote domain) "\\(?:/\\|\\'\\)")
4682 (concat "\\`"
4683 (regexp-quote
4684 (if (and (= char ?f) current-file)
4685 (concat "file://" current-file) uri))
4686 "\\'")))))
4687 (prog1 (memq char '(?y ?n ?! ?d ?\s ?f))
4688 (quit-window t)))))))
47204689
47214690 (defun org-extract-log-state-settings (x)
47224691 "Extract the log state setting from a TODO keyword string.
47934762
47944763 ;; Other stuff we need.
47954764 (require 'time-date)
4796 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
47974765 (when (< emacs-major-version 28) ; preloaded in Emacs 28
47984766 (require 'easymenu))
47994767
48074775
48084776 ;; babel
48094777 (require 'ob)
4778
4779 (defvar org-element-cache-persistent); Defined in org-element.el
4780 (defvar org-element-use-cache); Defined in org-element.el
4781 (defvar org-mode-loading nil
4782 "Non-nil during Org mode initialization.")
4783
4784 (defvar org-agenda-file-menu-enabled t
4785 "When non-nil, refresh Agenda files in Org menu when loading Org.")
48104786
48114787 ;;;###autoload
48124788 (define-derived-mode org-mode outline-mode "Org"
48274803 The following commands are available:
48284804
48294805 \\{org-mode-map}"
4806 (setq-local org-mode-loading t)
48304807 (org-load-modules-maybe)
4831 (org-install-agenda-files-menu)
4832 (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
4808 (when org-agenda-file-menu-enabled
4809 (org-install-agenda-files-menu))
4810 (when (and org-link-descriptive
4811 (eq org-fold-core-style 'overlays))
4812 (add-to-invisibility-spec '(org-link)))
4813 (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
4814 "..."))
48334815 (make-local-variable 'org-link-descriptive)
4834 (add-to-invisibility-spec '(org-hide-block . t))
4816 (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
4817 (if org-link-descriptive
4818 (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible nil)
4819 (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible t))
48354820 (setq-local outline-regexp org-outline-regexp)
48364821 (setq-local outline-level 'org-outline-level)
4837 (setq bidi-paragraph-direction 'left-to-right)
48384822 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
48394823 (unless org-display-table
48404824 (setq org-display-table (make-display-table)))
48624846 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
48634847 ;; Check for running clock before killing a buffer
48644848 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4849 ;; Initialize cache.
4850 (org-element-cache-reset)
4851 (when (and org-element-cache-persistent
4852 org-element-use-cache)
4853 (org-persist-load 'org-element--cache (current-buffer) t))
48654854 ;; Initialize macros templates.
48664855 (org-macro-initialize-templates)
48674856 ;; Initialize radio targets.
48734862 (org-setup-filling)
48744863 ;; Comments.
48754864 (org-setup-comments-handling)
4876 ;; Initialize cache.
4877 (org-element-cache-reset)
48784865 ;; Beginning/end of defun
48794866 (setq-local beginning-of-defun-function 'org-backward-element)
48804867 (setq-local end-of-defun-function
49244911 (= (point-min) (point-max)))
49254912 (insert "# -*- mode: org -*-\n\n"))
49264913 (unless org-inhibit-startup
4914 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
4915 (org-table-map-tables
4916 (cond ((and org-startup-align-all-tables
4917 org-startup-shrink-all-tables)
4918 (lambda () (org-table-align) (org-table-shrink)))
4919 (org-startup-align-all-tables #'org-table-align)
4920 (t #'org-table-shrink))
4921 t))
4922 ;; Suppress modification hooks to speed up the startup.
4923 ;; However, do it only when text properties/overlays, but not
4924 ;; buffer text are actually modified. We still need to track text
4925 ;; modifications to make cache updates work reliably.
49274926 (org-unmodified
49284927 (when org-startup-with-beamer-mode (org-beamer-mode))
4929 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
4930 (org-table-map-tables
4931 (cond ((and org-startup-align-all-tables
4932 org-startup-shrink-all-tables)
4933 (lambda () (org-table-align) (org-table-shrink)))
4934 (org-startup-align-all-tables #'org-table-align)
4935 (t #'org-table-shrink))
4936 t))
49374928 (when org-startup-with-inline-images (org-display-inline-images))
49384929 (when org-startup-with-latex-preview (org-latex-preview '(16)))
4939 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
4930 (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
49404931 (when org-startup-truncated (setq truncate-lines t))
49414932 (when org-startup-numerated (require 'org-num) (org-num-mode 1))
49424933 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
49634954 ;; Set face extension as requested.
49644955 (org--set-faces-extend '(org-block-begin-line org-block-end-line)
49654956 org-fontify-whole-block-delimiter-line)
4966 (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
4957 (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
4958 (setq-local org-mode-loading nil))
49674959
49684960 ;; Update `customize-package-emacs-version-alist'
49694961 (add-to-list 'customize-package-emacs-version-alist
49774969 ("9.2" . "27.1")
49784970 ("9.3" . "27.1")
49794971 ("9.4" . "27.2")
4980 ("9.5" . "28.1")))
4972 ("9.5" . "28.1")
4973 ("9.6" . "29.1")))
49814974
49824975 (defvar org-mode-transpose-word-syntax-table
49834976 (let ((st (make-syntax-table text-mode-syntax-table)))
50135006 (if (< r 1)
50145007 now
50155008 (let* ((time (decode-time now))
5016 (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
5017 (nthcdr 2 time))))
5018 (if (or (not past) (org-time-less-p res now))
5009 (res (org-encode-time
5010 (apply #'list
5011 0 (* r (round (nth 1 time) r))
5012 (nthcdr 2 time)))))
5013 (if (or (not past) (time-less-p res now))
50195014 res
5020 (org-time-subtract res (* r 60)))))))
5015 (time-subtract res (* r 60)))))))
50215016
50225017 (defun org-today ()
50235018 "Return today date, considering `org-extend-today-until'."
50245019 (time-to-days
5025 (org-time-since (* 3600 org-extend-today-until))))
5020 (time-since (* 3600 org-extend-today-until))))
50265021
50275022 ;;;; Font-Lock stuff, including the activators
50285023
51035098 (when verbatim?
51045099 (org-remove-flyspell-overlays-in
51055100 (match-beginning 0) (match-end 0))
5101 (when (and (org-fold-core-folding-spec-p 'org-link)
5102 (org-fold-core-folding-spec-p 'org-link-description))
5103 (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link)
5104 (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link-description))
51065105 (remove-text-properties (match-beginning 2) (match-end 2)
51075106 '(display t invisible t intangible t)))
51085107 (add-text-properties (match-beginning 2) (match-end 2)
51665165 (defsubst org-rear-nonsticky-at (pos)
51675166 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
51685167
5169 (defun org-activate-links (limit)
5168 (defun org-activate-links--overlays (limit)
51705169 "Add link properties to links.
51715170 This includes angle, plain, and bracket links."
51725171 (catch :exit
51815180 (when (and (memq style org-highlight-links)
51825181 ;; Do not span over paragraph boundaries.
51835182 (not (string-match-p org-element-paragraph-separate
5184 (match-string 0)))
5183 (match-string 0)))
51855184 ;; Do not confuse plain links with tags.
51865185 (not (and (eq style 'plain)
5187 (let ((face (get-text-property
5188 (max (1- start) (point-min)) 'face)))
5189 (if (consp face) (memq 'org-tag face)
5190 (eq 'org-tag face))))))
5186 (let ((face (get-text-property
5187 (max (1- start) (point-min)) 'face)))
5188 (if (consp face) (memq 'org-tag face)
5189 (eq 'org-tag face))))))
51915190 (let* ((link-object (save-excursion
51925191 (goto-char start)
51935192 (save-match-data (org-element-link-parser))))
52375236 (funcall f start end path (eq style 'bracket))))
52385237 (throw :exit t))))) ;signal success
52395238 nil))
5239 (defun org-activate-links--text-properties (limit)
5240 "Add link properties to links.
5241 This includes angle, plain, and bracket links."
5242 (catch :exit
5243 (while (re-search-forward org-link-any-re limit t)
5244 (let* ((start (match-beginning 0))
5245 (end (match-end 0))
5246 (visible-start (or (match-beginning 3) (match-beginning 2)))
5247 (visible-end (or (match-end 3) (match-end 2)))
5248 (style (cond ((eq ?< (char-after start)) 'angle)
5249 ((eq ?\[ (char-after (1+ start))) 'bracket)
5250 (t 'plain))))
5251 (when (and (memq style org-highlight-links)
5252 ;; Do not span over paragraph boundaries.
5253 (not (string-match-p org-element-paragraph-separate
5254 (match-string 0)))
5255 ;; Do not confuse plain links with tags.
5256 (not (and (eq style 'plain)
5257 (let ((face (get-text-property
5258 (max (1- start) (point-min)) 'face)))
5259 (if (consp face) (memq 'org-tag face)
5260 (eq 'org-tag face))))))
5261 (let* ((link-object (save-excursion
5262 (goto-char start)
5263 (save-match-data (org-element-link-parser))))
5264 (link (org-element-property :raw-link link-object))
5265 (type (org-element-property :type link-object))
5266 (path (org-element-property :path link-object))
5267 (face-property (pcase (org-link-get-parameter type :face)
5268 ((and (pred functionp) face) (funcall face path))
5269 ((and (pred facep) face) face)
5270 ((and (pred consp) face) face) ;anonymous
5271 (_ 'org-link)))
5272 (properties ;for link's visible part
5273 (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
5274 'highlight)
5275 'keymap (or (org-link-get-parameter type :keymap)
5276 org-mouse-map)
5277 'help-echo (pcase (org-link-get-parameter type :help-echo)
5278 ((and (pred stringp) echo) echo)
5279 ((and (pred functionp) echo) echo)
5280 (_ (concat "LINK: " link)))
5281 'htmlize-link (pcase (org-link-get-parameter type
5282 :htmlize-link)
5283 ((and (pred functionp) f) (funcall f))
5284 (_ `(:uri ,link)))
5285 'font-lock-multiline t)))
5286 (org-remove-flyspell-overlays-in start end)
5287 (org-rear-nonsticky-at end)
5288 (if (not (eq 'bracket style))
5289 (progn
5290 (add-face-text-property start end face-property)
5291 (add-text-properties start end properties))
5292 ;; Initialize folding when used outside org-mode.
5293 (unless (or (derived-mode-p 'org-mode)
5294 (and (org-fold-folding-spec-p 'org-link-description)
5295 (org-fold-folding-spec-p 'org-link)))
5296 (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
5297 "...")))
5298 ;; Handle invisible parts in bracket links.
5299 (let ((spec (or (org-link-get-parameter type :display)
5300 'org-link)))
5301 (unless (org-fold-folding-spec-p spec)
5302 (org-fold-add-folding-spec spec
5303 (cdr org-link--link-folding-spec)
5304 nil
5305 'append)
5306 (org-fold-core-set-folding-spec-property spec :visible t))
5307 (org-fold-region start end nil 'org-link)
5308 (org-fold-region start end nil 'org-link-description)
5309 ;; We are folding the whole emphasized text with SPEC
5310 ;; first. It makes everything invisible (or whatever
5311 ;; the user wants).
5312 (org-fold-region start end t spec)
5313 ;; The visible part of the text is folded using
5314 ;; 'org-link-description, which is forcing this part of
5315 ;; the text to be visible.
5316 (org-fold-region visible-start visible-end t 'org-link-description)
5317 (add-text-properties start end properties)
5318 (add-face-text-property start end face-property)
5319 (org-rear-nonsticky-at visible-start)
5320 (org-rear-nonsticky-at visible-end)))
5321 (let ((f (org-link-get-parameter type :activate-func)))
5322 (when (functionp f)
5323 (funcall f start end path (eq style 'bracket))))
5324 (throw :exit t))))) ;signal success
5325 nil))
5326 (defsubst org-activate-links (limit)
5327 "Add link properties to links.
5328 This includes angle, plain, and bracket links."
5329 (if (eq org-fold-core-style 'text-properties)
5330 (org-activate-links--text-properties limit)
5331 (org-activate-links--overlays limit)))
52405332
52415333 (defun org-activate-code (limit)
52425334 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
55985690
55995691 If this is called at a normal headline, the level is the number
56005692 of stars. Use `org-reduced-level' to remove the effect of
5601 `org-odd-levels'. Unlike to `org-current-level', this function
5693 `org-odd-levels-only'. Unlike `org-current-level', this function
56025694 takes into consideration inlinetasks."
56035695 (org-with-wide-buffer
56045696 (end-of-line)
57685860 '(9 'org-special-keyword t))
57695861 ;; Blocks and meta lines
57705862 '(org-fontify-meta-lines-and-blocks)
5771 ;; Citations
5772 '(org-cite-activate))))
5863 '(org-fontify-inline-src-blocks)
5864 ;; Citations. When an activate processor is specified, if
5865 ;; specified, try loading it beforehand.
5866 (progn
5867 (unless (null org-cite-activate-processor)
5868 (org-cite-try-load-processor org-cite-activate-processor))
5869 '(org-cite-activate)))))
57735870 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
57745871 (run-hooks 'org-font-lock-set-keywords-hook)
57755872 ;; Now set the full font-lock-keywords
57955892
57965893 (defvar-local org-custom-properties-overlays nil
57975894 "List of overlays used for custom properties.")
5895 ;; Preserve when switching modes or when restarting Org.
5896 (put 'org-custom-properties-overlays 'permanent-local t)
57985897
57995898 (defun org-toggle-custom-properties-visibility ()
58005899 "Display or hide properties in `org-custom-properties'."
58555954 (insert s)
58565955 (let ((org-odd-levels-only odd-levels))
58575956 (org-mode)
5858 (org-font-lock-ensure)
5859 (buffer-string))))
5957 (font-lock-ensure)
5958 (if org-link-descriptive
5959 (org-link-display-format
5960 (buffer-string))
5961 (buffer-string)))))
58605962
58615963 (defun org-get-level-face (n)
58625964 "Get the right face for match N in font-lock matching of headlines."
59326034 (defun org-unfontify-region (beg end &optional _maybe_loudly)
59336035 "Remove fontification and activation overlays from links."
59346036 (font-lock-default-unfontify-region beg end)
5935 (let* ((buffer-undo-list t)
5936 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5937 (inhibit-modification-hooks t)
5938 deactivate-mark buffer-file-name buffer-file-truename)
6037 (with-silent-modifications
59396038 (decompose-region beg end)
59406039 (remove-text-properties beg end
59416040 '(mouse-face t keymap t org-linked-text t
59426041 invisible t intangible t
59436042 org-emphasis t))
6043 (org-fold-region beg end nil 'org-link)
6044 (org-fold-region beg end nil 'org-link-description)
6045 (org-fold-core-update-optimisation beg end)
59446046 (org-remove-font-lock-display-properties beg end)))
59456047
59466048 (defconst org-script-display '(((raise -0.3) (height 0.7))
59746076 (emph-p (get-text-property mpos 'org-emphasis))
59756077 (link-p (get-text-property mpos 'mouse-face))
59766078 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5977 (goto-char (point-at-bol))
6079 (goto-char (line-beginning-position))
59786080 (setq table-p (looking-at-p org-table-dataline-regexp)
59796081 comment-p (looking-at-p "^[ \t]*#[ +]"))
59806082 (goto-char pos)
59866088 (if (equal (char-after (match-beginning 2)) ?^)
59876089 (nth (if table-p 3 1) org-script-display)
59886090 (nth (if table-p 2 0) org-script-display)))
6091 (put-text-property (match-beginning 2) (match-end 3)
6092 'org-emphasis t)
59896093 (add-text-properties (match-beginning 2) (match-end 2)
59906094 (list 'invisible t))
59916095 (when (and (eq (char-after (match-beginning 3)) ?{)
60056109 (overlay-end o))))
60066110 (delete-overlay o))))
60076111
6112 ;; FIXME: This function is unused.
60086113 (defun org-show-empty-lines-in-parent ()
60096114 "Move to the parent and re-show empty lines before visible headlines."
60106115 (save-excursion
60456150 (set-window-start window (line-beginning-position))))))
60466151
60476152
6048 ;;; Visibility (headlines, blocks, drawers)
6049
6050 ;;;; Headlines visibility
6051
6052 (defun org-show-entry ()
6053 "Show the body directly following its heading.
6054 Show the heading too, if it is currently invisible."
6055 (interactive)
6056 (save-excursion
6057 (org-back-to-heading-or-point-min t)
6058 (org-flag-region
6059 (line-end-position 0)
6060 (save-excursion
6061 (if (re-search-forward
6062 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6063 (match-beginning 1)
6064 (point-max)))
6065 nil
6066 'outline)
6067 (org-cycle-hide-drawers 'children)))
6068
6069 (defun org-hide-entry ()
6070 "Hide the body directly following its heading."
6071 (interactive)
6072 (save-excursion
6073 (org-back-to-heading-or-point-min t)
6074 (when (org-at-heading-p) (forward-line))
6075 (org-flag-region
6076 (line-end-position 0)
6077 (save-excursion
6078 (if (re-search-forward
6079 (concat "[\r\n]" org-outline-regexp) nil t)
6080 (line-end-position 0)
6081 (point-max)))
6082 t
6083 'outline)))
6084
6085 (defun org-show-children (&optional level)
6086 "Show all direct subheadings of this heading.
6087 Prefix arg LEVEL is how many levels below the current level
6088 should be shown. Default is enough to cause the following
6089 heading to appear."
6090 (interactive "p")
6091 (unless (org-before-first-heading-p)
6092 (save-excursion
6093 (org-with-limited-levels (org-back-to-heading t))
6094 (let* ((current-level (funcall outline-level))
6095 (max-level (org-get-valid-level
6096 current-level
6097 (if level (prefix-numeric-value level) 1)))
6098 (end (save-excursion (org-end-of-subtree t t)))
6099 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6100 (past-first-child nil)
6101 ;; Make sure to skip inlinetasks.
6102 (re (format regexp-fmt
6103 current-level
6104 (cond
6105 ((not (featurep 'org-inlinetask)) "")
6106 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6107 3))
6108 (t (1- org-inlinetask-min-level))))))
6109 ;; Display parent heading.
6110 (org-flag-heading nil)
6111 (forward-line)
6112 ;; Display children. First child may be deeper than expected
6113 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6114 ;; MAX-LEVEL accordingly.
6115 (while (re-search-forward re end t)
6116 (unless past-first-child
6117 (setq re (format regexp-fmt
6118 current-level
6119 (max (funcall outline-level) max-level)))
6120 (setq past-first-child t))
6121 (org-flag-heading nil))))))
6122
6123 (defun org-show-subtree ()
6124 "Show everything after this heading at deeper levels."
6125 (interactive)
6126 (org-flag-region
6127 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6128
6129 ;;;; Blocks and drawers visibility
6130
6131 (defun org--hide-wrapper-toggle (element category force no-error)
6132 "Toggle visibility for ELEMENT.
6133
6134 ELEMENT is a block or drawer type parsed element. CATEGORY is
6135 either `block' or `drawer'. When FORCE is `off', show the block
6136 or drawer. If it is non-nil, hide it unconditionally. Throw an
6137 error when not at a block or drawer, unless NO-ERROR is non-nil.
6138
6139 Return a non-nil value when toggling is successful."
6140 (let ((type (org-element-type element)))
6141 (cond
6142 ((memq type
6143 (pcase category
6144 (`drawer '(drawer property-drawer))
6145 (`block '(center-block
6146 comment-block dynamic-block example-block export-block
6147 quote-block special-block src-block verse-block))
6148 (_ (error "Unknown category: %S" category))))
6149 (let* ((post (org-element-property :post-affiliated element))
6150 (start (save-excursion
6151 (goto-char post)
6152 (line-end-position)))
6153 (end (save-excursion
6154 (goto-char (org-element-property :end element))
6155 (skip-chars-backward " \t\n")
6156 (line-end-position))))
6157 ;; Do nothing when not before or at the block opening line or
6158 ;; at the block closing line.
6159 (unless (let ((eol (line-end-position)))
6160 (and (> eol start) (/= eol end)))
6161 (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
6162 (flag
6163 (cond ((eq force 'off) nil)
6164 (force t)
6165 ((eq spec (get-char-property start 'invisible)) nil)
6166 (t t))))
6167 (org-flag-region start end flag spec))
6168 ;; When the block is hidden away, make sure point is left in
6169 ;; a visible part of the buffer.
6170 (when (invisible-p (max (1- (point)) (point-min)))
6171 (goto-char post))
6172 ;; Signal success.
6173 t)))
6174 (no-error nil)
6175 (t
6176 (user-error (if (eq category 'drawer)
6177 "Not at a drawer"
6178 "Not at a block"))))))
6179
6180 (defun org-hide-block-toggle (&optional force no-error element)
6181 "Toggle the visibility of the current block.
6182
6183 When optional argument FORCE is `off', make block visible. If it
6184 is non-nil, hide it unconditionally. Throw an error when not at
6185 a block, unless NO-ERROR is non-nil. When optional argument
6186 ELEMENT is provided, consider it instead of the current block.
6187
6188 Return a non-nil value when toggling is successful."
6189 (interactive)
6190 (org--hide-wrapper-toggle
6191 (or element (org-element-at-point)) 'block force no-error))
6192
6193 (defun org-hide-drawer-toggle (&optional force no-error element)
6194 "Toggle the visibility of the current drawer.
6195
6196 When optional argument FORCE is `off', make drawer visible. If
6197 it is non-nil, hide it unconditionally. Throw an error when not
6198 at a drawer, unless NO-ERROR is non-nil. When optional argument
6199 ELEMENT is provided, consider it instead of the current drawer.
6200
6201 Return a non-nil value when toggling is successful."
6202 (interactive)
6203 (org--hide-wrapper-toggle
6204 (or element (org-element-at-point)) 'drawer force no-error))
6205
6206 (defun org-hide-block-all ()
6207 "Fold all blocks in the current buffer."
6208 (interactive)
6209 (org-show-all '(blocks))
6210 (org-block-map 'org-hide-block-toggle))
6211
6212 (defun org-hide-drawer-all ()
6213 "Fold all drawers in the current buffer."
6214 (let ((begin (point-min))
6215 (end (point-max)))
6216 (org--hide-drawers begin end)))
6217
6218 (defun org-cycle-hide-drawers (state)
6219 "Re-hide all drawers after a visibility state change.
6220 STATE should be one of the symbols listed in the docstring of
6221 `org-cycle-hook'."
6222 (when (derived-mode-p 'org-mode)
6223 (cond ((not (memq state '(overview folded contents)))
6224 (let* ((global? (eq state 'all))
6225 (beg (if global? (point-min) (line-beginning-position)))
6226 (end (cond (global? (point-max))
6227 ((eq state 'children) (org-entry-end-position))
6228 (t (save-excursion (org-end-of-subtree t t))))))
6229 (org--hide-drawers beg end)))
6230 ((memq state '(overview contents))
6231 ;; Hide drawers before first heading.
6232 (let ((beg (point-min))
6233 (end (save-excursion
6234 (goto-char (point-min))
6235 (if (org-before-first-heading-p)
6236 (org-entry-end-position)
6237 (point-min)))))
6238 (when (< beg end)
6239 (org--hide-drawers beg end)))))))
6240
6241 (defun org--hide-drawers (begin end)
6242 "Hide all drawers between BEGIN and END."
6243 (save-excursion
6244 (goto-char begin)
6245 (while (re-search-forward org-drawer-regexp end t)
6246 (let* ((pair (get-char-property-and-overlay (line-beginning-position)
6247 'invisible))
6248 (o (cdr-safe pair)))
6249 (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
6250 (pcase (get-char-property-and-overlay (point) 'invisible)
6251 (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
6252 (_
6253 (let* ((drawer (org-element-at-point))
6254 (type (org-element-type drawer)))
6255 (when (memq type '(drawer property-drawer))
6256 (org-hide-drawer-toggle t nil drawer)
6257 ;; Make sure to skip drawer entirely or we might flag it
6258 ;; another time when matching its ending line with
6259 ;; `org-drawer-regexp'.
6260 (goto-char (org-element-property :end drawer)))))))))))
6261
6262 ;;;; Visibility cycling
6263
6264 (defvar-local org-cycle-global-status nil)
6265 (put 'org-cycle-global-status 'org-state t)
6266 (defvar-local org-cycle-subtree-status nil)
6267 (put 'org-cycle-subtree-status 'org-state t)
6268
6269 (defun org-show-all (&optional types)
6270 "Show all contents in the visible part of the buffer.
6271 By default, the function expands headings, blocks and drawers.
6272 When optional argument TYPE is a list of symbols among `blocks',
6273 `drawers' and `headings', to only expand one specific type."
6274 (interactive)
6275 (let ((types (or types '(blocks drawers headings))))
6276 (when (memq 'blocks types)
6277 (org-flag-region (point-min) (point-max) nil 'org-hide-block))
6278 (cond
6279 ;; Fast path. Since headings and drawers share the same
6280 ;; invisible spec, clear everything in one go.
6281 ((and (memq 'headings types)
6282 (memq 'drawers types))
6283 (org-flag-region (point-min) (point-max) nil 'outline))
6284 ((memq 'headings types)
6285 (org-flag-region (point-min) (point-max) nil 'outline)
6286 (org-cycle-hide-drawers 'all))
6287 ((memq 'drawers types)
6288 (save-excursion
6289 (goto-char (point-min))
6290 (while (re-search-forward org-drawer-regexp nil t)
6291 (let* ((pair (get-char-property-and-overlay (line-beginning-position)
6292 'invisible))
6293 (o (cdr-safe pair)))
6294 (if (overlayp o) (goto-char (overlay-end o))
6295 (pcase (get-char-property-and-overlay (point) 'invisible)
6296 (`(outline . ,o)
6297 (goto-char (overlay-end o))
6298 (delete-overlay o))
6299 (_ nil))))))))))
6300
6301 ;;;###autoload
6302 (defun org-cycle (&optional arg)
6303 "TAB-action and visibility cycling for Org mode.
6304
6305 This is the command invoked in Org mode by the `TAB' key. Its main
6306 purpose is outline visibility cycling, but it also invokes other actions
6307 in special contexts.
6308
6309 When this function is called with a `\\[universal-argument]' prefix, rotate \
6310 the entire
6311 buffer through 3 states (global cycling)
6312 1. OVERVIEW: Show only top-level headlines.
6313 2. CONTENTS: Show all headlines of all levels, but no body text.
6314 3. SHOW ALL: Show everything.
6315
6316 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6317 switch to the startup visibility,
6318 determined by the variable `org-startup-folded', and by any VISIBILITY
6319 properties in the buffer.
6320
6321 With a `\\[universal-argument] \\[universal-argument] \
6322 \\[universal-argument]' prefix argument, show the entire buffer, including
6323 any drawers.
6324
6325 When inside a table, re-align the table and move to the next field.
6326
6327 When point is at the beginning of a headline, rotate the subtree started
6328 by this line through 3 different states (local cycling)
6329 1. FOLDED: Only the main headline is shown.
6330 2. CHILDREN: The main headline and the direct children are shown.
6331 From this state, you can move to one of the children
6332 and zoom in further.
6333 3. SUBTREE: Show the entire subtree, including body text.
6334 If there is no subtree, switch directly from CHILDREN to FOLDED.
6335
6336 When point is at the beginning of an empty headline and the variable
6337 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6338 of the headline by demoting and promoting it to likely levels. This
6339 speeds up creation document structure by pressing `TAB' once or several
6340 times right after creating a new headline.
6341
6342 When there is a numeric prefix, go up to a heading with level ARG, do
6343 a `show-subtree' and return to the previous cursor position. If ARG
6344 is negative, go up that many levels.
6345
6346 When point is not at the beginning of a headline, execute the global
6347 binding for `TAB', which is re-indenting the line. See the option
6348 `org-cycle-emulate-tab' for details.
6349
6350 As a special case, if point is at the very beginning of the buffer, if
6351 there is no headline there, and if the variable `org-cycle-global-at-bob'
6352 is non-nil, this function acts as if called with prefix argument \
6353 \(`\\[universal-argument] TAB',
6354 same as `S-TAB') also when called without prefix argument."
6355 (interactive "P")
6356 (org-load-modules-maybe)
6357 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6358 (and org-cycle-level-after-item/entry-creation
6359 (or (org-cycle-level)
6360 (org-cycle-item-indentation))))
6361 (let* ((limit-level
6362 (or org-cycle-max-level
6363 (and (boundp 'org-inlinetask-min-level)
6364 org-inlinetask-min-level
6365 (1- org-inlinetask-min-level))))
6366 (nstars
6367 (and limit-level
6368 (if org-odd-levels-only
6369 (1- (* 2 limit-level))
6370 limit-level)))
6371 (org-outline-regexp
6372 (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
6373 (cond
6374 ((equal arg '(16))
6375 (setq last-command 'dummy)
6376 (org-set-startup-visibility)
6377 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6378 ((equal arg '(64))
6379 (org-show-all)
6380 (org-unlogged-message "Entire buffer visible, including drawers"))
6381 ((equal arg '(4)) (org-cycle-internal-global))
6382 ;; Show-subtree, ARG levels up from here.
6383 ((integerp arg)
6384 (save-excursion
6385 (org-back-to-heading)
6386 (outline-up-heading (if (< arg 0) (- arg)
6387 (- (funcall outline-level) arg)))
6388 (org-show-subtree)))
6389 ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
6390 ((and org-cycle-global-at-bob
6391 (bobp)
6392 (not (looking-at org-outline-regexp)))
6393 (let ((org-cycle-hook
6394 (remq 'org-optimize-window-after-visibility-change
6395 org-cycle-hook)))
6396 (org-cycle-internal-global)))
6397 ;; Try CDLaTeX TAB completion.
6398 ((org-try-cdlatex-tab))
6399 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6400 ((and (featurep 'org-inlinetask)
6401 (org-inlinetask-at-task-p)
6402 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6403 (org-inlinetask-toggle-visibility))
6404 (t
6405 (let ((pos (point))
6406 (element (org-element-at-point)))
6407 (cond
6408 ;; Try toggling visibility for block at point.
6409 ((org-hide-block-toggle nil t element))
6410 ;; Try toggling visibility for drawer at point.
6411 ((org-hide-drawer-toggle nil t element))
6412 ;; Table: enter it or move to the next field.
6413 ((and (org-match-line "[ \t]*[|+]")
6414 (org-element-lineage element '(table) t))
6415 (if (and (eq 'table (org-element-type element))
6416 (eq 'table.el (org-element-property :type element)))
6417 (message (substitute-command-keys "\\<org-mode-map>\
6418 Use `\\[org-edit-special]' to edit table.el tables"))
6419 (org-table-justify-field-maybe)
6420 (call-interactively #'org-table-next-field)))
6421 ((run-hook-with-args-until-success
6422 'org-tab-after-check-for-table-hook))
6423 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6424 ((and (or (and org-cycle-include-plain-lists
6425 (let ((item (org-element-lineage element
6426 '(item plain-list)
6427 t)))
6428 (and item
6429 (= (line-beginning-position)
6430 (org-element-property :post-affiliated
6431 item)))))
6432 (org-match-line org-outline-regexp))
6433 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6434 (org-cycle-internal-local))
6435 ;; From there: TAB emulation and template completion.
6436 (buffer-read-only (org-back-to-heading))
6437 ((run-hook-with-args-until-success
6438 'org-tab-after-check-for-cycling-hook))
6439 ((run-hook-with-args-until-success
6440 'org-tab-before-tab-emulation-hook))
6441 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6442 (or (not (bolp))
6443 (not (looking-at org-outline-regexp))))
6444 (call-interactively (global-key-binding (kbd "TAB"))))
6445 ((or (eq org-cycle-emulate-tab t)
6446 (and (memq org-cycle-emulate-tab '(white whitestart))
6447 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6448 (or (and (eq org-cycle-emulate-tab 'white)
6449 (= (match-end 0) (point-at-eol)))
6450 (and (eq org-cycle-emulate-tab 'whitestart)
6451 (>= (match-end 0) pos)))))
6452 (call-interactively (global-key-binding (kbd "TAB"))))
6453 (t
6454 (save-excursion
6455 (org-back-to-heading)
6456 (org-cycle))))))))))
6457
6458 (defun org-cycle-internal-global ()
6459 "Do the global cycling action."
6460 ;; Hack to avoid display of messages for .org attachments in Gnus
6461 (let ((ga (string-match-p "\\*fontification" (buffer-name))))
6462 (cond
6463 ((and (eq last-command this-command)
6464 (eq org-cycle-global-status 'overview))
6465 ;; We just created the overview - now do table of contents
6466 ;; This can be slow in very large buffers, so indicate action
6467 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6468 (unless ga (org-unlogged-message "CONTENTS..."))
6469 (org-content)
6470 (unless ga (org-unlogged-message "CONTENTS...done"))
6471 (setq org-cycle-global-status 'contents)
6472 (run-hook-with-args 'org-cycle-hook 'contents))
6473
6474 ((and (eq last-command this-command)
6475 (eq org-cycle-global-status 'contents))
6476 ;; We just showed the table of contents - now show everything
6477 (run-hook-with-args 'org-pre-cycle-hook 'all)
6478 (org-show-all '(headings blocks))
6479 (unless ga (org-unlogged-message "SHOW ALL"))
6480 (setq org-cycle-global-status 'all)
6481 (run-hook-with-args 'org-cycle-hook 'all))
6482
6483 (t
6484 ;; Default action: go to overview
6485 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6486 (org-overview)
6487 (unless ga (org-unlogged-message "OVERVIEW"))
6488 (setq org-cycle-global-status 'overview)
6489 (run-hook-with-args 'org-cycle-hook 'overview)))))
6490
6153
6154 ;; FIXME: It was in the middle of visibility section. Where should it go to?
64916155 (defvar org-called-with-limited-levels nil
64926156 "Non-nil when `org-with-limited-levels' is currently active.")
6493
6494 (defun org-cycle-internal-local ()
6495 "Do the local cycling action."
6496 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6497 ;; First, determine end of headline (EOH), end of subtree or item
6498 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6499 (save-excursion
6500 (if (org-at-item-p)
6501 (progn
6502 (beginning-of-line)
6503 (setq struct (org-list-struct))
6504 (setq eoh (point-at-eol))
6505 (setq eos (org-list-get-item-end-before-blank (point) struct))
6506 (setq has-children (org-list-has-child-p (point) struct)))
6507 (org-back-to-heading)
6508 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6509 (setq eos (save-excursion
6510 (org-end-of-subtree t t)
6511 (unless (eobp) (forward-char -1))
6512 (point)))
6513 (setq has-children
6514 (or
6515 (save-excursion
6516 (let ((level (funcall outline-level)))
6517 (outline-next-heading)
6518 (and (org-at-heading-p t)
6519 (> (funcall outline-level) level))))
6520 (and (eq org-cycle-include-plain-lists 'integrate)
6521 (save-excursion
6522 (org-list-search-forward (org-item-beginning-re) eos t))))))
6523 ;; Determine end invisible part of buffer (EOL)
6524 (beginning-of-line 2)
6525 (while (and (not (eobp)) ;this is like `next-line'
6526 (get-char-property (1- (point)) 'invisible))
6527 (goto-char (next-single-char-property-change (point) 'invisible))
6528 (and (eolp) (beginning-of-line 2)))
6529 (setq eol (point)))
6530 ;; Find out what to do next and set `this-command'
6531 (cond
6532 ((= eos eoh)
6533 ;; Nothing is hidden behind this heading
6534 (unless (org-before-first-heading-p)
6535 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6536 (org-unlogged-message "EMPTY ENTRY")
6537 (setq org-cycle-subtree-status nil)
6538 (save-excursion
6539 (goto-char eos)
6540 (outline-next-heading)
6541 (when (org-invisible-p) (org-flag-heading nil))))
6542 ((and (or (>= eol eos)
6543 (not (string-match "\\S-" (buffer-substring eol eos))))
6544 (or has-children
6545 (not (setq children-skipped
6546 org-cycle-skip-children-state-if-no-children))))
6547 ;; Entire subtree is hidden in one line: children view
6548 (unless (org-before-first-heading-p)
6549 (run-hook-with-args 'org-pre-cycle-hook 'children))
6550 (if (org-at-item-p)
6551 (org-list-set-item-visibility (point-at-bol) struct 'children)
6552 (org-show-entry)
6553 (org-with-limited-levels (org-show-children))
6554 (org-show-set-visibility 'tree)
6555 ;; Fold every list in subtree to top-level items.
6556 (when (eq org-cycle-include-plain-lists 'integrate)
6557 (save-excursion
6558 (org-back-to-heading)
6559 (while (org-list-search-forward (org-item-beginning-re) eos t)
6560 (beginning-of-line 1)
6561 (let* ((struct (org-list-struct))
6562 (prevs (org-list-prevs-alist struct))
6563 (end (org-list-get-bottom-point struct)))
6564 (dolist (e (org-list-get-all-items (point) struct prevs))
6565 (org-list-set-item-visibility e struct 'folded))
6566 (goto-char (if (< end eos) end eos)))))))
6567 (org-unlogged-message "CHILDREN")
6568 (save-excursion
6569 (goto-char eos)
6570 (outline-next-heading)
6571 (when (org-invisible-p) (org-flag-heading nil)))
6572 (setq org-cycle-subtree-status 'children)
6573 (unless (org-before-first-heading-p)
6574 (run-hook-with-args 'org-cycle-hook 'children)))
6575 ((or children-skipped
6576 (and (eq last-command this-command)
6577 (eq org-cycle-subtree-status 'children)))
6578 ;; We just showed the children, or no children are there,
6579 ;; now show everything.
6580 (unless (org-before-first-heading-p)
6581 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6582 (org-flag-region eoh eos nil 'outline)
6583 (org-unlogged-message
6584 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6585 (setq org-cycle-subtree-status 'subtree)
6586 (unless (org-before-first-heading-p)
6587 (run-hook-with-args 'org-cycle-hook 'subtree)))
6588 (t
6589 ;; Default action: hide the subtree.
6590 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6591 (org-flag-region eoh eos t 'outline)
6592 (org-unlogged-message "FOLDED")
6593 (setq org-cycle-subtree-status 'folded)
6594 (unless (org-before-first-heading-p)
6595 (run-hook-with-args 'org-cycle-hook 'folded))))))
6596
6597 ;;;###autoload
6598 (defun org-global-cycle (&optional arg)
6599 "Cycle the global visibility. For details see `org-cycle'.
6600 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6601 With a numeric prefix, show all headlines up to that level."
6602 (interactive "P")
6603 (cond
6604 ((integerp arg)
6605 (org-content arg)
6606 (setq org-cycle-global-status 'contents))
6607 ((equal arg '(4))
6608 (org-set-startup-visibility)
6609 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6610 (t
6611 (org-cycle '(4)))))
6612
6613 (defun org-set-startup-visibility ()
6614 "Set the visibility required by startup options and properties."
6615 (cond
6616 ((eq org-startup-folded t)
6617 (org-overview))
6618 ((eq org-startup-folded 'content)
6619 (org-content))
6620 ((eq org-startup-folded 'show2levels)
6621 (org-content 2))
6622 ((eq org-startup-folded 'show3levels)
6623 (org-content 3))
6624 ((eq org-startup-folded 'show4levels)
6625 (org-content 4))
6626 ((eq org-startup-folded 'show5levels)
6627 (org-content 5))
6628 ((or (eq org-startup-folded 'showeverything)
6629 (eq org-startup-folded nil))
6630 (org-show-all)))
6631 (unless (eq org-startup-folded 'showeverything)
6632 (when org-hide-block-startup (org-hide-block-all))
6633 (org-set-visibility-according-to-property)
6634 (org-cycle-hide-archived-subtrees 'all)
6635 (org-cycle-hide-drawers 'all)
6636 (org-cycle-show-empty-lines t)))
6637
6638 (defun org-set-visibility-according-to-property ()
6639 "Switch subtree visibility according to VISIBILITY property."
6640 (interactive)
6641 (let ((regexp (org-re-property "VISIBILITY")))
6642 (org-with-point-at 1
6643 (while (re-search-forward regexp nil t)
6644 (let ((state (match-string 3)))
6645 (if (not (org-at-property-p)) (outline-next-heading)
6646 (save-excursion
6647 (org-back-to-heading t)
6648 (org-flag-subtree t)
6649 (org-reveal)
6650 (pcase state
6651 ("folded"
6652 (org-flag-subtree t))
6653 ("children"
6654 (org-show-hidden-entry)
6655 (org-show-children))
6656 ("content"
6657 (save-excursion
6658 (save-restriction
6659 (org-narrow-to-subtree)
6660 (org-content))))
6661 ((or "all" "showall")
6662 (outline-show-subtree))
6663 (_ nil)))
6664 (org-end-of-subtree)))))))
6665
6666 (defun org-overview ()
6667 "Switch to overview mode, showing only top-level headlines."
6668 (interactive)
6669 (org-show-all '(headings drawers))
6670 (save-excursion
6671 (goto-char (point-min))
6672 (when (re-search-forward org-outline-regexp-bol nil t)
6673 (let* ((last (line-end-position))
6674 (level (- (match-end 0) (match-beginning 0) 1))
6675 (regexp (format "^\\*\\{1,%d\\} " level)))
6676 (while (re-search-forward regexp nil :move)
6677 (org-flag-region last (line-end-position 0) t 'outline)
6678 (setq last (line-end-position))
6679 (setq level (- (match-end 0) (match-beginning 0) 1))
6680 (setq regexp (format "^\\*\\{1,%d\\} " level)))
6681 (org-flag-region last (point) t 'outline)))))
6682
6683 (defun org-content (&optional arg)
6684 "Show all headlines in the buffer, like a table of contents.
6685 With numerical argument N, show content up to level N."
6686 (interactive "p")
6687 (org-show-all '(headings drawers))
6688 (save-excursion
6689 (goto-char (point-max))
6690 (let ((regexp (if (and (wholenump arg) (> arg 0))
6691 (format "^\\*\\{1,%d\\} " arg)
6692 "^\\*+ "))
6693 (last (point)))
6694 (while (re-search-backward regexp nil t)
6695 (org-flag-region (line-end-position) last t 'outline)
6696 (setq last (line-end-position 0))))))
6697
6698 (defvar org-scroll-position-to-restore nil
6699 "Temporarily store scroll position to restore.")
6700 (defun org-optimize-window-after-visibility-change (state)
6701 "Adjust the window after a change in outline visibility.
6702 This function is the default value of the hook `org-cycle-hook'."
6703 (when (get-buffer-window (current-buffer))
6704 (let ((repeat (eq last-command this-command)))
6705 (unless repeat
6706 (setq org-scroll-position-to-restore nil))
6707 (cond
6708 ((eq state 'content) nil)
6709 ((eq state 'all) nil)
6710 ((and org-scroll-position-to-restore repeat
6711 (eq state 'folded))
6712 (set-window-start nil org-scroll-position-to-restore))
6713 ((eq state 'folded) nil)
6714 ((eq state 'children)
6715 (setq org-scroll-position-to-restore (window-start))
6716 (or (org-subtree-end-visible-p) (recenter 1)))
6717 ((eq state 'subtree)
6718 (unless repeat
6719 (setq org-scroll-position-to-restore (window-start)))
6720 (or (org-subtree-end-visible-p) (recenter 1)))))))
6721
6722 (defun org-clean-visibility-after-subtree-move ()
6723 "Fix visibility issues after moving a subtree."
6724 ;; First, find a reasonable region to look at:
6725 ;; Start two siblings above, end three below
6726 (let* ((beg (save-excursion
6727 (and (org-get-previous-sibling)
6728 (org-get-previous-sibling))
6729 (point)))
6730 (end (save-excursion
6731 (and (org-get-next-sibling)
6732 (org-get-next-sibling)
6733 (org-get-next-sibling))
6734 (if (org-at-heading-p)
6735 (point-at-eol)
6736 (point))))
6737 (level (looking-at "\\*+"))
6738 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
6739 (save-excursion
6740 (save-restriction
6741 (narrow-to-region beg end)
6742 (when re
6743 ;; Properly fold already folded siblings
6744 (goto-char (point-min))
6745 (while (re-search-forward re nil t)
6746 (when (and (not (org-invisible-p))
6747 (org-invisible-p (line-end-position)))
6748 (outline-hide-entry))))
6749 (org-cycle-hide-drawers 'all)
6750 (org-cycle-show-empty-lines 'overview)))))
6751
6752 (defun org-cycle-show-empty-lines (state)
6753 "Show empty lines above all visible headlines.
6754 The region to be covered depends on STATE when called through
6755 `org-cycle-hook'. Lisp program can use t for STATE to get the
6756 entire buffer covered. Note that an empty line is only shown if there
6757 are at least `org-cycle-separator-lines' empty lines before the headline."
6758 (when (/= org-cycle-separator-lines 0)
6759 (save-excursion
6760 (let* ((n (abs org-cycle-separator-lines))
6761 (re (cond
6762 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6763 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6764 (t (let ((ns (number-to-string (- n 2))))
6765 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6766 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6767 beg end)
6768 (cond
6769 ((memq state '(overview contents t))
6770 (setq beg (point-min) end (point-max)))
6771 ((memq state '(children folded))
6772 (setq beg (point)
6773 end (progn (org-end-of-subtree t t)
6774 (line-beginning-position 2)))))
6775 (when beg
6776 (goto-char beg)
6777 (while (re-search-forward re end t)
6778 (unless (get-char-property (match-end 1) 'invisible)
6779 (let ((e (match-end 1))
6780 (b (if (>= org-cycle-separator-lines 0)
6781 (match-beginning 1)
6782 (save-excursion
6783 (goto-char (match-beginning 0))
6784 (skip-chars-backward " \t\n")
6785 (line-end-position)))))
6786 (org-flag-region b e nil 'outline))))))))
6787 ;; Never hide empty lines at the end of the file.
6788 (save-excursion
6789 (goto-char (point-max))
6790 (outline-previous-heading)
6791 (outline-end-of-heading)
6792 (when (and (looking-at "[ \t\n]+")
6793 (= (match-end 0) (point-max)))
6794 (org-flag-region (point) (match-end 0) nil 'outline))))
6795
6796 ;;;; Reveal point location
6797
6798 (defun org-show-context (&optional key)
6799 "Make sure point and context are visible.
6800 Optional argument KEY, when non-nil, is a symbol. See
6801 `org-show-context-detail' for allowed values and how much is to
6802 be shown."
6803 (org-show-set-visibility
6804 (cond ((symbolp org-show-context-detail) org-show-context-detail)
6805 ((cdr (assq key org-show-context-detail)))
6806 (t (cdr (assq 'default org-show-context-detail))))))
6807
6808 (defun org-show-set-visibility (detail)
6809 "Set visibility around point according to DETAIL.
6810 DETAIL is either nil, `minimal', `local', `ancestors',
6811 `ancestors-full', `lineage', `tree', `canonical' or t. See
6812 `org-show-context-detail' for more information."
6813 ;; Show current heading and possibly its entry, following headline
6814 ;; or all children.
6815 (if (and (org-at-heading-p) (not (eq detail 'local)))
6816 (org-flag-heading nil)
6817 (org-show-entry)
6818 ;; If point is hidden within a drawer or a block, make sure to
6819 ;; expose it.
6820 (dolist (o (overlays-at (point)))
6821 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
6822 (delete-overlay o)))
6823 (unless (org-before-first-heading-p)
6824 (org-with-limited-levels
6825 (cl-case detail
6826 ((tree canonical t) (org-show-children))
6827 ((nil minimal ancestors ancestors-full))
6828 (t (save-excursion
6829 (outline-next-heading)
6830 (org-flag-heading nil)))))))
6831 ;; Show whole subtree.
6832 (when (eq detail 'ancestors-full) (org-show-subtree))
6833 ;; Show all siblings.
6834 (when (eq detail 'lineage) (org-show-siblings))
6835 ;; Show ancestors, possibly with their children.
6836 (when (memq detail '(ancestors ancestors-full lineage tree canonical t))
6837 (save-excursion
6838 (while (org-up-heading-safe)
6839 (org-flag-heading nil)
6840 (when (memq detail '(canonical t)) (org-show-entry))
6841 (when (memq detail '(tree canonical t)) (org-show-children))))))
6842
6843 (defvar org-reveal-start-hook nil
6844 "Hook run before revealing a location.")
6845
6846 (defun org-reveal (&optional siblings)
6847 "Show current entry, hierarchy above it, and the following headline.
6848
6849 This can be used to show a consistent set of context around
6850 locations exposed with `org-show-context'.
6851
6852 With optional argument SIBLINGS, on each level of the hierarchy all
6853 siblings are shown. This repairs the tree structure to what it would
6854 look like when opened with hierarchical calls to `org-cycle'.
6855
6856 With a \\[universal-argument] \\[universal-argument] prefix, \
6857 go to the parent and show the entire tree."
6858 (interactive "P")
6859 (run-hooks 'org-reveal-start-hook)
6860 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
6861 ((equal siblings '(16))
6862 (save-excursion
6863 (when (org-up-heading-safe)
6864 (org-show-subtree)
6865 (run-hook-with-args 'org-cycle-hook 'subtree))))
6866 (t (org-show-set-visibility 'lineage))))
68676157
68686158
68696159 ;;; Indirect buffer display of subtrees
69336223 (pop-to-buffer ibuf))
69346224 (t (error "Invalid value")))
69356225 (narrow-to-region beg end)
6936 (org-show-all '(headings drawers blocks))
6226 (org-fold-show-all '(headings drawers blocks))
69376227 (goto-char pos)
69386228 (run-hook-with-args 'org-cycle-hook 'all)
69396229 (and (window-live-p cwin) (select-window cwin))))
69406230
6941 (defun org-get-indirect-buffer (&optional buffer heading)
6942 (setq buffer (or buffer (current-buffer)))
6943 (let ((n 1) (base (buffer-name buffer)) bname)
6944 (while (buffer-live-p
6945 (get-buffer
6946 (setq bname
6947 (concat base "-"
6948 (if heading (concat heading "-" (number-to-string n))
6949 (number-to-string n))))))
6950 (setq n (1+ n)))
6951 (condition-case nil
6952 (make-indirect-buffer buffer bname 'clone)
6953 (error (make-indirect-buffer buffer bname)))))
6231 (cl-defun org-get-indirect-buffer (&optional (buffer (current-buffer)) heading)
6232 "Return an indirect buffer based on BUFFER.
6233 If HEADING, append it to the name of the new buffer."
6234 (let* ((base-buffer (or (buffer-base-buffer buffer) buffer))
6235 (buffer-name (generate-new-buffer-name
6236 (format "%s%s"
6237 (buffer-name base-buffer)
6238 (if heading
6239 (concat "::" heading)
6240 ""))))
6241 (indirect-buffer (make-indirect-buffer base-buffer buffer-name 'clone)))
6242 ;; Decouple folding state. We need to do it manually since
6243 ;; `make-indirect-buffer' does not run
6244 ;; `clone-indirect-buffer-hook'.
6245 (org-fold-core-decouple-indirect-buffer-folds)
6246 indirect-buffer))
69546247
69556248 (defun org-set-frame-title (title)
69566249 "Set the title of the current frame to the string TITLE."
70296322 (if (not level) (outline-next-heading) ;before first headline
70306323 (org-back-to-heading invisible-ok)
70316324 (when (equal arg '(16)) (org-up-heading-safe))
7032 (org-end-of-subtree)))
6325 (org-end-of-subtree invisible-ok 'to-heading)))
6326 ;; At `point-max', if the file does not have ending newline,
6327 ;; create one, so that we are not appending stars at non-empty
6328 ;; line.
70336329 (unless (bolp) (insert "\n"))
70346330 (when (and blank? (save-excursion
70356331 (backward-char)
70416337 (backward-char))
70426338 (unless (and blank? (org-previous-line-empty-p))
70436339 (org-N-empty-lines-before-current (if blank? 1 0)))
7044 (insert stars " ")
6340 (insert stars " " "\n")
6341 ;; Move point after stars.
6342 (backward-char)
70456343 ;; When INVISIBLE-OK is non-nil, ensure newly created headline
70466344 ;; is visible.
70476345 (unless invisible-ok
7048 (pcase (get-char-property-and-overlay (point) 'invisible)
7049 (`(outline . ,o)
7050 (move-overlay o (overlay-start o) (line-end-position 0)))
7051 (_ nil))))
6346 (if (eq org-fold-core-style 'text-properties)
6347 (cond
6348 ((org-fold-folded-p
6349 (max (point-min)
6350 (1- (line-beginning-position)))
6351 'headline)
6352 (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
6353 (t nil))
6354 (pcase (get-char-property-and-overlay (point) 'invisible)
6355 (`(outline . ,o)
6356 (move-overlay o (overlay-start o) (line-end-position 0)))
6357 (_ nil)))))
70526358 ;; At a headline...
70536359 ((org-at-heading-p)
70546360 (cond ((bolp)
71126418 (org-back-to-heading t)
71136419 (let ((case-fold-search nil))
71146420 (looking-at org-complex-heading-regexp)
7115 (let ((todo (and (not no-todo) (match-string 2)))
6421 ;; When using `org-fold-core--optimise-for-huge-buffers',
6422 ;; returned text will be invisible. Clear it up.
6423 (save-match-data
6424 (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0)))
6425 (let ((todo (and (not no-todo) (match-string 2)))
71166426 (priority (and (not no-priority) (match-string 3)))
71176427 (headline (pcase (match-string 4)
71186428 (`nil "")
71236433 "" h))
71246434 (h h)))
71256435 (tags (and (not no-tags) (match-string 5))))
6436 ;; Restore cleared optimization.
6437 (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
71266438 (mapconcat #'identity
71276439 (delq nil (list todo priority headline tags))
71286440 " "))))))
71396451 (save-excursion
71406452 (org-back-to-heading t)
71416453 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7142 (list (length (match-string 1))
7143 (org-reduced-level (length (match-string 1)))
7144 (match-string-no-properties 2)
7145 (and (match-end 3) (aref (match-string 3) 2))
7146 (match-string-no-properties 4)
7147 (match-string-no-properties 5)))))
6454 (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
6455 (prog1
6456 (list (length (match-string 1))
6457 (org-reduced-level (length (match-string 1)))
6458 (match-string-no-properties 2)
6459 (and (match-end 3) (aref (match-string 3) 2))
6460 (match-string-no-properties 4)
6461 (match-string-no-properties 5))
6462 (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
71486463
71496464 (defun org-get-entry ()
71506465 "Get the entry text, after heading, entire subtree."
71516466 (save-excursion
71526467 (org-back-to-heading t)
7153 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6468 (filter-buffer-substring (line-beginning-position 2) (org-end-of-subtree t))))
71546469
71556470 (defun org-edit-headline (&optional heading)
71566471 "Edit the current headline.
71836498 (interactive)
71846499 (org-insert-heading '(4) invisible-ok))
71856500
7186 (defun org-insert-todo-heading-respect-content (&optional force-state)
6501 (defun org-insert-todo-heading-respect-content (&optional _)
71876502 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
71886503 (interactive)
7189 (org-insert-todo-heading force-state '(4)))
6504 (let ((org-insert-heading-respect-content t))
6505 (org-insert-todo-heading '(4) t)))
71906506
71916507 (defun org-insert-todo-heading (arg &optional force-heading)
71926508 "Insert a new heading with the same level and TODO state as current heading.
72596575 See also `org-promote'."
72606576 (interactive)
72616577 (save-excursion
7262 (org-with-limited-levels (org-map-tree 'org-promote)))
6578 (org-back-to-heading t)
6579 (org-combine-change-calls (point) (save-excursion (org-end-of-subtree t))
6580 (org-with-limited-levels (org-map-tree 'org-promote))))
72636581 (org-fix-position-after-promote))
72646582
72656583 (defun org-demote-subtree ()
72676585 See `org-demote' and `org-promote'."
72686586 (interactive)
72696587 (save-excursion
7270 (org-with-limited-levels (org-map-tree 'org-demote)))
6588 (org-back-to-heading t)
6589 (org-combine-change-calls (point) (save-excursion (org-end-of-subtree t))
6590 (org-with-limited-levels (org-map-tree 'org-demote))))
72716591 (org-fix-position-after-promote))
72726592
72736593 (defun org-do-promote ()
73076627 "Return the level of the current entry, or nil if before the first headline.
73086628 The level is the number of stars at the beginning of the
73096629 headline. Use `org-reduced-level' to remove the effect of
7310 `org-odd-levels'. Unlike to `org-outline-level', this function
6630 `org-odd-levels-only'. Unlike `org-outline-level', this function
73116631 ignores inlinetasks."
73126632 (let ((level (org-with-limited-levels (org-outline-level))))
73136633 (and (> level 0) level)))
73616681 (replace-match "# " nil t))
73626682 ((= level 1)
73636683 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7364 (t (replace-match up-head nil t)))
6684 (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
73656685 (unless (= level 1)
73666686 (when org-auto-align-tags (org-align-tags))
73676687 (when org-adapt-indentation (org-fixup-indentation (- diff))))
73766696 (level (save-match-data (funcall outline-level)))
73776697 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
73786698 (diff (abs (- level (length down-head) -1))))
7379 (replace-match down-head nil t)
7380 (when org-auto-align-tags (org-align-tags))
7381 (when org-adapt-indentation (org-fixup-indentation diff))
6699 (org-fold-core-ignore-fragility-checks
6700 (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
6701 (when org-auto-align-tags (org-align-tags))
6702 (when org-adapt-indentation (org-fixup-indentation diff)))
73826703 (run-hooks 'org-after-demote-entry-hook))))
73836704
73846705 (defun org-cycle-level ()
75866907 (goto-char (point-min))
75876908 ;; First check if there are no even levels
75886909 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7589 (org-show-set-visibility 'canonical)
6910 (org-fold-show-set-visibility 'canonical)
75906911 (error "Not all levels are odd in this file. Conversion not possible"))
75916912 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
75926913 (let ((outline-regexp org-outline-regexp)
76106931 "Move the current subtree up past ARG headlines of the same level."
76116932 (interactive "p")
76126933 (org-move-subtree-down (- (prefix-numeric-value arg))))
6934
6935 (defun org-clean-visibility-after-subtree-move ()
6936 "Fix visibility issues after moving a subtree."
6937 ;; First, find a reasonable region to look at:
6938 ;; Start two siblings above, end three below
6939 (let* ((beg (save-excursion
6940 (and (org-get-previous-sibling)
6941 (org-get-previous-sibling))
6942 (point)))
6943 (end (save-excursion
6944 (and (org-get-next-sibling)
6945 (org-get-next-sibling)
6946 (org-get-next-sibling))
6947 (if (org-at-heading-p)
6948 (line-end-position)
6949 (point))))
6950 (level (looking-at "\\*+"))
6951 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
6952 (save-excursion
6953 (save-restriction
6954 (narrow-to-region beg end)
6955 (when re
6956 ;; Properly fold already folded siblings
6957 (goto-char (point-min))
6958 (while (re-search-forward re nil t)
6959 (when (and (not (org-invisible-p))
6960 (org-invisible-p (line-end-position)))
6961 (org-fold-heading nil))))
6962 (org-cycle-hide-drawers 'all)
6963 (org-cycle-show-empty-lines 'overview)))))
76136964
76146965 (defun org-move-subtree-down (&optional arg)
76156966 "Move the current subtree down past ARG headlines of the same level."
76497000 (setq txt (buffer-substring beg end))
76507001 (org-save-markers-in-region beg end)
76517002 (delete-region beg end)
7652 (org-remove-empty-overlays-at beg)
7653 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
7654 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
7003 (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
7004 (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
7005 (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
76557006 (and (not (bolp)) (looking-at "\n") (forward-char 1))
76567007 (let ((bbb (point)))
76577008 (insert-before-markers txt)
76627013 (org-skip-whitespace)
76637014 (move-marker ins-point nil)
76647015 (if folded
7665 (org-flag-subtree t)
7666 (org-show-entry)
7667 (org-show-children))
7016 (org-fold-subtree t)
7017 (org-fold-show-entry 'hide-drawers)
7018 (org-fold-show-children))
76687019 (org-clean-visibility-after-subtree-move)
76697020 ;; move back to the initial column we were at
76707021 (move-to-column col))))
77537104
77547105 When REMOVE is non-nil, remove the subtree from the clipboard."
77557106 (interactive "P")
7756 (setq tree (or tree (and kill-ring (current-kill 0))))
7107 (setq tree (or tree (current-kill 0)))
77577108 (unless (org-kill-is-subtree-p tree)
77587109 (user-error
77597110 (substitute-command-keys
77607111 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
77617112 (org-with-limited-levels
7762 (let* ((visp (not (org-invisible-p)))
7763 (txt tree)
7764 (old-level (if (string-match org-outline-regexp-bol txt)
7765 (- (match-end 0) (match-beginning 0) 1)
7766 -1))
7767 (force-level
7768 (cond
7769 (level (prefix-numeric-value level))
7770 ;; When point is after the stars in an otherwise empty
7771 ;; headline, use the number of stars as the forced level.
7772 ((and (org-match-line "^\\*+[ \t]*$")
7773 (not (eq ?* (char-after))))
7774 (org-outline-level))
7775 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
7776 (previous-level
7777 (save-excursion
7778 (org-previous-visible-heading 1)
7779 (if (org-at-heading-p) (org-outline-level) 1)))
7780 (next-level
7781 (save-excursion
7782 (if (org-at-heading-p) (org-outline-level)
7783 (org-next-visible-heading 1)
7784 (if (org-at-heading-p) (org-outline-level) 1))))
7785 (new-level (or force-level (max previous-level next-level)))
7786 (shift (if (or (= old-level -1)
7787 (= new-level -1)
7788 (= old-level new-level))
7789 0
7790 (- new-level old-level)))
7791 (delta (if (> shift 0) -1 1))
7792 (func (if (> shift 0) #'org-demote #'org-promote))
7793 (org-odd-levels-only nil)
7794 beg end newend)
7795 ;; Remove the forced level indicator.
7796 (when (and force-level (not level))
7797 (delete-region (line-beginning-position) (point)))
7798 ;; Paste before the next visible heading or at end of buffer,
7799 ;; unless point is at the beginning of a headline.
7800 (unless (and (bolp) (org-at-heading-p))
7801 (org-next-visible-heading 1)
7802 (unless (bolp) (insert "\n")))
7803 (setq beg (point))
7804 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7805 (insert-before-markers txt)
7806 (unless (string-suffix-p "\n" txt) (insert "\n"))
7807 (setq newend (point))
7808 (org-reinstall-markers-in-region beg)
7809 (setq end (point))
7810 (goto-char beg)
7811 (skip-chars-forward " \t\n\r")
7812 (setq beg (point))
7813 (when (and (org-invisible-p) visp)
7814 (save-excursion (outline-show-heading)))
7815 ;; Shift if necessary.
7816 (unless (= shift 0)
7817 (save-restriction
7818 (narrow-to-region beg end)
7819 (while (not (= shift 0))
7820 (org-map-region func (point-min) (point-max))
7821 (setq shift (+ delta shift)))
7822 (goto-char (point-min))
7823 (setq newend (point-max))))
7824 (when (or for-yank (called-interactively-p 'interactive))
7825 (message "Clipboard pasted as level %d subtree" new-level))
7826 (when (and (not for-yank) ; in this case, org-yank will decide about folding
7827 kill-ring
7828 (equal org-subtree-clip (current-kill 0))
7829 org-subtree-clip-folded)
7830 ;; The tree was folded before it was killed/copied
7831 (org-flag-subtree t))
7832 (when for-yank (goto-char newend))
7833 (when remove (pop kill-ring)))))
7113 (org-fold-core-ignore-fragility-checks
7114 (let* ((visp (not (org-invisible-p)))
7115 (txt tree)
7116 (old-level (if (string-match org-outline-regexp-bol txt)
7117 (- (match-end 0) (match-beginning 0) 1)
7118 -1))
7119 (force-level
7120 (cond
7121 (level (prefix-numeric-value level))
7122 ;; When point is after the stars in an otherwise empty
7123 ;; headline, use the number of stars as the forced level.
7124 ((and (org-match-line "^\\*+[ \t]*$")
7125 (not (eq ?* (char-after))))
7126 (org-outline-level))
7127 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
7128 (previous-level
7129 (save-excursion
7130 (org-previous-visible-heading 1)
7131 (if (org-at-heading-p) (org-outline-level) 1)))
7132 (next-level
7133 (save-excursion
7134 (if (org-at-heading-p) (org-outline-level)
7135 (org-next-visible-heading 1)
7136 (if (org-at-heading-p) (org-outline-level) 1))))
7137 (new-level (or force-level (max previous-level next-level)))
7138 (shift (if (or (= old-level -1)
7139 (= new-level -1)
7140 (= old-level new-level))
7141 0
7142 (- new-level old-level)))
7143 (delta (if (> shift 0) -1 1))
7144 (func (if (> shift 0) #'org-demote #'org-promote))
7145 (org-odd-levels-only nil)
7146 beg end newend)
7147 ;; Remove the forced level indicator.
7148 (when (and force-level (not level))
7149 (delete-region (line-beginning-position) (point)))
7150 ;; Paste before the next visible heading or at end of buffer,
7151 ;; unless point is at the beginning of a headline.
7152 (unless (and (bolp) (org-at-heading-p))
7153 (org-next-visible-heading 1)
7154 (unless (bolp) (insert "\n")))
7155 (setq beg (point))
7156 ;; Avoid re-parsing cache elements when i.e. level 1 heading
7157 ;; is inserted and then promoted.
7158 (org-combine-change-calls beg beg
7159 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7160 (insert txt)
7161 (unless (string-suffix-p "\n" txt) (insert "\n"))
7162 (setq newend (point))
7163 (org-reinstall-markers-in-region beg)
7164 (setq end (point))
7165 (goto-char beg)
7166 (skip-chars-forward " \t\n\r")
7167 (setq beg (point))
7168 (when (and (org-invisible-p) visp)
7169 (save-excursion (org-fold-heading nil)))
7170 ;; Shift if necessary.
7171 (unless (= shift 0)
7172 (save-restriction
7173 (narrow-to-region beg end)
7174 (while (not (= shift 0))
7175 (org-map-region func (point-min) (point-max))
7176 (setq shift (+ delta shift)))
7177 (goto-char (point-min))
7178 (setq newend (point-max)))))
7179 (when (or for-yank (called-interactively-p 'interactive))
7180 (message "Clipboard pasted as level %d subtree" new-level))
7181 (when (and (not for-yank) ; in this case, org-yank will decide about folding
7182 (equal org-subtree-clip tree)
7183 org-subtree-clip-folded)
7184 ;; The tree was folded before it was killed/copied
7185 (org-fold-subtree t))
7186 (when for-yank (goto-char newend))
7187 (when remove (pop kill-ring))))))
78347188
78357189 (defun org-kill-is-subtree-p (&optional txt)
78367190 "Check if the current kill is an outline subtree, or a set of trees.
78397193 So this will actually accept several entries of equal levels as well,
78407194 which is OK for `org-paste-subtree'.
78417195 If optional TXT is given, check this string instead of the current kill."
7842 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7196 (let* ((kill (or txt (ignore-errors (current-kill 0))))
78437197 (re (org-get-limited-outline-regexp))
78447198 (^re (concat "^" re))
78457199 (start-level (and kill
78917245 (move-marker (car x) (+ beg (cdr x))))
78927246 (setq org-markers-to-move nil))
78937247
7894 (defun org-narrow-to-subtree ()
7248 (defun org-narrow-to-subtree (&optional element)
78957249 "Narrow buffer to the current subtree."
78967250 (interactive)
7897 (save-excursion
7898 (save-match-data
7899 (org-with-limited-levels
7900 (narrow-to-region
7901 (progn (org-back-to-heading t) (point))
7902 (progn (org-end-of-subtree t t)
7903 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7904 (point)))))))
7251 (if (org-element--cache-active-p)
7252 (let* ((heading (org-element-lineage
7253 (or element (org-element-at-point))
7254 '(headline) t))
7255 (end (org-element-property :end heading)))
7256 (if (and heading end)
7257 (narrow-to-region (org-element-property :begin heading)
7258 (if (= end (point-max))
7259 end (1- end)))
7260 (signal 'outline-before-first-heading nil)))
7261 (save-excursion
7262 (save-match-data
7263 (org-with-limited-levels
7264 (narrow-to-region
7265 (progn (org-back-to-heading t) (point))
7266 (progn (org-end-of-subtree t t)
7267 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7268 (point))))))))
79057269
79067270 (defun org-toggle-narrow-to-subtree ()
79077271 "Narrow to the subtree at point or widen a narrowed buffer."
80097373 (insert template)
80107374 (org-mode)
80117375 (goto-char (point-min))
8012 (org-show-subtree)
7376 (org-fold-show-subtree)
80137377 (and idprop (if org-clone-delete-id
80147378 (org-entry-delete nil "ID")
80157379 (org-id-get-create t)))
81287492 (setf (substring fpath (- width 2)) "..")))
81297493 fpath))
81307494
8131 (defun org-display-outline-path (&optional file current separator just-return-string)
7495 (defun org-get-title (&optional buffer-or-file)
7496 "Collect title from the provided `org-mode' BUFFER-OR-FILE.
7497
7498 Returns nil if there are no #+TITLE property."
7499 (let ((buffer (cond ((bufferp buffer-or-file) buffer-or-file)
7500 ((stringp buffer-or-file) (find-file-noselect
7501 buffer-or-file))
7502 (t (current-buffer)))))
7503 (with-current-buffer buffer
7504 (org-macro-initialize-templates)
7505 (let ((title (assoc-default "title" org-macro-templates)))
7506 (unless (string= "" title)
7507 title)))))
7508
7509 (defun org-display-outline-path (&optional file-or-title current separator just-return-string)
81327510 "Display the current outline path in the echo area.
81337511
8134 If FILE is non-nil, prepend the output with the file name.
7512 If FILE-OR-TITLE is `title', prepend outline with file title. If
7513 it is non-nil or title is not present in document, prepend
7514 outline path with the file name.
81357515 If CURRENT is non-nil, append the current heading to the output.
81367516 SEPARATOR is passed through to `org-format-outline-path'. It separates
81377517 the different parts of the path and defaults to \"/\".
81397519 (interactive "P")
81407520 (let* (case-fold-search
81417521 (bfn (buffer-file-name (buffer-base-buffer)))
7522 (title-prop (when (eq file-or-title 'title) (org-get-title)))
81427523 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
81437524 res)
81447525 (when current (setq path (append path
81507531 (org-format-outline-path
81517532 path
81527533 (1- (frame-width))
8153 (and file bfn (concat (file-name-nondirectory bfn) separator))
7534 (and file-or-title bfn (concat (if (and (eq file-or-title 'title) title-prop)
7535 title-prop
7536 (file-name-nondirectory bfn))
7537 separator))
81547538 separator))
81557539 (add-face-text-property 0 (length res)
81567540 `(:height ,(face-attribute 'default :height))
82817665 (point))
82827666 what "children")
82837667 (goto-char start)
8284 (outline-show-subtree)
7668 (org-fold-show-subtree)
82857669 (outline-next-heading))
82867670 (t
82877671 ;; we will sort the top-level entries in this file
82977681 (setq end (point-max))
82987682 (setq what "top-level")
82997683 (goto-char start)
8300 (org-show-all '(headings drawers blocks))))
7684 (org-fold-show-all '(headings drawers blocks))))
83017685
83027686 (setq beg (point))
83037687 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
84057789 (org-time-string-to-seconds (match-string 1))
84067790 (float-time now))))
84077791 ((= dcst ?p)
8408 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7792 (if (re-search-forward org-priority-regexp (line-end-position) t)
84097793 (string-to-char (match-string 2))
84107794 org-priority-default))
84117795 ((= dcst ?r)
84257809 (t (error "Invalid sorting type `%c'" sorting-type))))
84267810 nil
84277811 (cond
8428 ((= dcst ?a) 'org-string-collate-lessp)
7812 ((= dcst ?a) 'string-collate-lessp)
84297813 ((= dcst ?f)
84307814 (or compare-func
84317815 (and interactive?
85257909 ;; string-collate-greaterp in Emacs.
85267910 (defun org-string-collate-greaterp (s1 s2)
85277911 "Return non-nil if S1 is greater than S2 in collation order."
8528 (not (org-string-collate-lessp s1 s2)))
7912 (not (string-collate-lessp s1 s2)))
85297913
85307914 ;;;###autoload
85317915 (defun org-run-like-in-org-mode (cmd)
85347918 Org mode to the values they have in Org mode, and then interactively
85357919 call CMD."
85367920 (org-load-modules-maybe)
8537 (let (binds)
7921 (let (vars vals)
85387922 (dolist (var (org-get-local-variables))
85397923 (when (or (not (boundp (car var)))
85407924 (eq (symbol-value (car var))
85417925 (default-value (car var))))
8542 (push (list (car var) `(quote ,(cadr var))) binds)))
8543 (eval `(let ,binds
8544 (call-interactively (quote ,cmd))))))
7926 (push (car var) vars)
7927 (push (cadr var) vals)))
7928 (cl-progv vars vals
7929 (call-interactively cmd))))
85457930
85467931 (defun org-get-category (&optional pos force-refresh)
85477932 "Get the category applying to position POS."
85487933 (save-match-data
85497934 (when force-refresh (org-refresh-category-properties))
85507935 (let ((pos (or pos (point))))
8551 (or (get-text-property pos 'org-category)
8552 (progn (org-refresh-category-properties)
8553 (get-text-property pos 'org-category))))))
7936 (if (org-element--cache-active-p)
7937 ;; Sync cache.
7938 (org-with-point-at (org-element-property :begin (org-element-at-point pos))
7939 (or (org-entry-get-with-inheritance "CATEGORY")
7940 "???"))
7941 (or (get-text-property pos 'org-category)
7942 (progn
7943 (org-refresh-category-properties)
7944 (get-text-property pos 'org-category)))))))
85547945
85557946 ;;; Refresh properties
85567947
85977988 (org-end-of-subtree t t))
85987989 ((outline-next-heading))
85997990 ((point-max))))))
8600 (if (symbolp tprop)
8601 ;; TPROP is a text property symbol.
8602 (put-text-property start end tprop p)
8603 ;; TPROP is an alist with (property . function) elements.
8604 (pcase-dolist (`(,prop . ,f) tprop)
8605 (put-text-property start end prop (funcall f p)))))))
7991 (with-silent-modifications
7992 (if (symbolp tprop)
7993 ;; TPROP is a text property symbol.
7994 (put-text-property start end tprop p)
7995 ;; TPROP is an alist with (property . function) elements.
7996 (pcase-dolist (`(,prop . ,f) tprop)
7997 (put-text-property start end prop (funcall f p))))))))
86067998
86077999 (defun org-refresh-category-properties ()
86088000 "Refresh category text properties in the buffer."
8609 (let ((case-fold-search t)
8610 (inhibit-read-only t)
8611 (default-category
8612 (cond ((null org-category)
8613 (if buffer-file-name
8614 (file-name-sans-extension
8615 (file-name-nondirectory buffer-file-name))
8616 "???"))
8617 ((symbolp org-category) (symbol-name org-category))
8618 (t org-category))))
8619 (with-silent-modifications
8620 (org-with-wide-buffer
8621 ;; Set buffer-wide property from keyword. Search last #+CATEGORY
8622 ;; keyword. If none is found, fall-back to `org-category' or
8623 ;; buffer file name, or set it by the document property drawer.
8624 (put-text-property
8625 (point-min) (point-max)
8626 'org-category
8627 (catch 'buffer-category
8628 (goto-char (point-max))
8629 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
8630 (let ((element (org-element-at-point)))
8631 (when (eq (org-element-type element) 'keyword)
8632 (throw 'buffer-category
8633 (org-element-property :value element)))))
8634 default-category))
8635 ;; Set categories from the document property drawer or
8636 ;; property drawers in the outline. If category is found in
8637 ;; the property drawer for the whole buffer that value
8638 ;; overrides the keyword-based value set above.
8639 (goto-char (point-min))
8640 (let ((regexp (org-re-property "CATEGORY")))
8641 (while (re-search-forward regexp nil t)
8642 (let ((value (match-string-no-properties 3)))
8643 (when (org-at-property-p)
8644 (put-text-property
8645 (save-excursion (org-back-to-heading-or-point-min t))
8646 (save-excursion (if (org-before-first-heading-p)
8647 (point-max)
8648 (org-end-of-subtree t t)))
8649 'org-category
8650 value)))))))))
8001 (unless (org-element--cache-active-p)
8002 (let ((case-fold-search t)
8003 (inhibit-read-only t)
8004 (default-category
8005 (cond ((null org-category)
8006 (if buffer-file-name
8007 (file-name-sans-extension
8008 (file-name-nondirectory buffer-file-name))
8009 "???"))
8010 ((symbolp org-category) (symbol-name org-category))
8011 (t org-category))))
8012 (let ((category (catch 'buffer-category
8013 (org-with-wide-buffer
8014 (goto-char (point-max))
8015 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
8016 (let ((element (org-element-at-point-no-context)))
8017 (when (eq (org-element-type element) 'keyword)
8018 (throw 'buffer-category
8019 (org-element-property :value element))))))
8020 default-category)))
8021 (with-silent-modifications
8022 (org-with-wide-buffer
8023 ;; Set buffer-wide property from keyword. Search last #+CATEGORY
8024 ;; keyword. If none is found, fall-back to `org-category' or
8025 ;; buffer file name, or set it by the document property drawer.
8026 (put-text-property (point-min) (point-max)
8027 'org-category category)
8028 ;; Set categories from the document property drawer or
8029 ;; property drawers in the outline. If category is found in
8030 ;; the property drawer for the whole buffer that value
8031 ;; overrides the keyword-based value set above.
8032 (goto-char (point-min))
8033 (let ((regexp (org-re-property "CATEGORY")))
8034 (while (re-search-forward regexp nil t)
8035 (let ((value (match-string-no-properties 3)))
8036 (when (org-at-property-p)
8037 (put-text-property
8038 (save-excursion (org-back-to-heading-or-point-min t))
8039 (save-excursion (if (org-before-first-heading-p)
8040 (point-max)
8041 (org-end-of-subtree t t)))
8042 'org-category
8043 value)))))))))))
86518044
86528045 (defun org-refresh-stats-properties ()
86538046 "Refresh stats text properties in the buffer."
86988091 (`windows-nt org-file-apps-windowsnt)
86998092 (_ org-file-apps-gnu)))
87008093
8701 (defun org--file-apps-entry-dlink-p (entry)
8094 (defun org--file-apps-entry-locator-p (entry)
87028095 "Non-nil if ENTRY should be matched against the link by `org-open-file'.
87038096
87048097 It assumes that is the case when the entry uses a regular
87128105 (> (regexp-opt-depth selector) 0)
87138106 (or (and (stringp action)
87148107 (string-match "%[0-9]" action))
8715 (consp action))))
8108 (functionp action))))
87168109 (_ nil)))
87178110
87188111 (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
87358128 (when add-auto-mode
87368129 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
87378130
8131 (defun org--open-file-format-command
8132 (mailcap-command file link match-data)
8133 "Format MAILCAP-COMMAND to launch viewer for the FILE.
8134
8135 MAILCAP-COMMAND may be an entry from the `org-file-apps' list or viewer
8136 field from mailcap file loaded to `mailcap-mime-data'. See \"RFC
8137 1524. A User Agent Configuration Mechanism For Multimedia Mail Format
8138 Information\" (URL `https://www.rfc-editor.org/rfc/rfc1524.html') for
8139 details, man page `mailcap(5)' for brief summary, and Info node
8140 `(emacs-mime) mailcap' for specific related to Emacs. Only a part of
8141 mailcap specification is supported.
8142
8143 The following substitutions are interpolated in the MAILCAP-COMMAND
8144 string:
8145
8146 - \"%s\" to FILE name passed through
8147 `convert-standard-filename', so it must be absolute path.
8148
8149 - \"%1\" to \"%9\" groups from MATCH-DATA found in the LINK string by
8150 the regular expression in the key part of the `org-file-apps' entry.
8151 (performed by caller). Not recommended, consider a lisp function
8152 instead of a shell command. For example, the following link in an
8153 Org file
8154
8155 <file:///usr/share/doc/bash/bashref.pdf::#Redirections::allocate a file>
8156
8157 may be handled by an `org-file-apps' entry like
8158
8159 (\"\\\\.pdf\\\\(?:\\\\.[gx]z\\\\|\\\\.bz2\\\\)?::\\\\(#[^:]+\\\\)::\\\\(.+\\\\)\\\\\\='\"
8160 . \"okular --find %2 %s%1\")
8161
8162 Use backslash \"\\\" to quote percent \"%\" or any other character
8163 including backslash itself.
8164
8165 In addition, each argument is passed through `shell-quote-argument',
8166 so quotes around substitutions should not be used. For compliance
8167 with mailcap files shipped e.g. in Debian GNU/Linux, single or double
8168 quotes around substitutions are stripped. It deviates from mailcap
8169 specification that requires file name to be safe for shell and for the
8170 application."
8171 (let ((spec (list (cons ?s (convert-standard-filename file))))
8172 (ngroups (min 9 (- (/ (length match-data) 2) 1))))
8173 (when (> ngroups 0)
8174 (set-match-data match-data)
8175 (dolist (i (number-sequence 1 ngroups))
8176 (push (cons (+ ?0 i) (match-string-no-properties i link)) spec)))
8177 (replace-regexp-in-string
8178 (rx (or (and "\\" (or (group anything) string-end))
8179 (and (optional (group (any "'\"")))
8180 "%"
8181 (or (group anything) string-end)
8182 (optional (group (backref 2))))))
8183 (lambda (fmt)
8184 (let* ((backslash (match-string-no-properties 1 fmt))
8185 (key (match-string 3 fmt))
8186 (value (and key (alist-get (string-to-char key) spec))))
8187 (cond
8188 (backslash)
8189 (value (let ((quot (match-string 2 fmt))
8190 (subst (shell-quote-argument value)))
8191 ;; Remove quotes around the file name - we use
8192 ;; `shell-quote-argument'.
8193 (if (match-string 4 fmt)
8194 subst
8195 (concat quot subst))))
8196 (t (error "Invalid format `%s'" fmt)))))
8197 mailcap-command nil 'literal)))
8198
87388199 ;;;###autoload
87398200 (defun org-open-file (path &optional in-emacs line search)
87408201 "Open the file at PATH.
87618222 (let* ((file (if (equal path "") buffer-file-name
87628223 (substitute-in-file-name (expand-file-name path))))
87638224 (file-apps (append org-file-apps (org--file-default-apps)))
8764 (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
8765 (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
8766 file-apps))
8225 (apps (cl-remove-if #'org--file-apps-entry-locator-p file-apps))
8226 (apps-locator (cl-remove-if-not #'org--file-apps-entry-locator-p
8227 file-apps))
87678228 (remp (and (assq 'remote apps) (file-remote-p file)))
87688229 (dirp (unless remp (file-directory-p file)))
87698230 (file (if (and dirp org-open-directory-means-index-dot-org)
87768237 (link (cond (line (concat file "::" (number-to-string line)))
87778238 (search (concat file "::" search))
87788239 (t file)))
8779 (dlink (downcase link))
87808240 (ext
87818241 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
87828242 (match-string 1 dfile)))
87988258 (t
87998259 (setq cmd (or (and remp (cdr (assq 'remote apps)))
88008260 (and dirp (cdr (assq 'directory apps)))
8801 ;; First, try matching against apps-dlink if we
8261 ;; First, try matching against apps-locator if we
88028262 ;; get a match here, store the match data for
88038263 ;; later.
8804 (let ((match (assoc-default dlink apps-dlink
8805 'string-match)))
8264 (let* ((case-fold-search t)
8265 (match (assoc-default link apps-locator
8266 'string-match)))
88068267 (if match
88078268 (progn (setq link-match-data (match-data))
88088269 match)
88098270 (progn (setq in-emacs (or in-emacs line search))
8810 nil))) ; if we have no match in apps-dlink,
8271 nil))) ; if we have no match in apps-locator,
88118272 ; always open the file in emacs if line or search
88128273 ; is given (for backwards compatibility)
88138274 (assoc-default dfile
88328293 (not org-open-non-existing-files))
88338294 (user-error "No such file: %s" file))
88348295 (cond
8835 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8836 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8837 (while (string-match "['\"]%s['\"]" cmd)
8838 (setq cmd (replace-match "%s" t t cmd)))
8839 (setq cmd (replace-regexp-in-string
8840 "%s"
8841 (shell-quote-argument (convert-standard-filename file))
8842 cmd
8843 nil t))
8844
8845 ;; Replace "%1", "%2" etc. in command with group matches from regex
8846 (save-match-data
8847 (let ((match-index 1)
8848 (number-of-groups (- (/ (length link-match-data) 2) 1)))
8849 (set-match-data link-match-data)
8850 (while (<= match-index number-of-groups)
8851 (let ((regex (concat "%" (number-to-string match-index)))
8852 (replace-with (match-string match-index dlink)))
8853 (while (string-match regex cmd)
8854 (setq cmd (replace-match replace-with t t cmd))))
8855 (setq match-index (+ match-index 1)))))
8296 ((org-string-nw-p cmd)
8297 (setq cmd (org--open-file-format-command cmd file link link-match-data))
88568298
88578299 (save-window-excursion
88588300 (message "Running %s...done" cmd)
88728314 (funcall (cdr (assq 'file org-link-frame-setup)) file)
88738315 (widen)
88748316 (cond (line (org-goto-line line)
8875 (when (derived-mode-p 'org-mode) (org-reveal)))
8317 (when (derived-mode-p 'org-mode) (org-fold-reveal)))
88768318 (search (condition-case err
88778319 (org-link-search search)
88788320 ;; Save position before error-ing out so user
89298371 they must return nil.")
89308372
89318373 (defun org-open-at-point (&optional arg)
8932 "Open link, timestamp, footnote or tags at point.
8374 "Open thing at point.
8375 The thing can be a link, citation, timestamp, footnote, src-block or
8376 tags.
89338377
89348378 When point is on a link, follow it. Normally, files will be
89358379 opened by an appropriate application. If the optional prefix
89438387 When point is a footnote definition, move to the first reference
89448388 found. If it is on a reference, move to the associated
89458389 definition.
8390
8391 When point is on a src-block of inline src-block, open its result.
8392
8393 When point is on a citation, follow it.
89468394
89478395 When point is on a headline, display a list of every link in the
89488396 entry, so it is possible to pick one, or all, of them. If point
90028450 (dolist (link (if (stringp links) (list links) links))
90038451 (search-forward link nil links-end)
90048452 (goto-char (match-beginning 0))
9005 (org-open-at-point arg)))))))
8453 ;; When opening file link, current buffer may be
8454 ;; altered.
8455 (save-current-buffer
8456 (org-open-at-point arg))))))))
90068457 ;; On a footnote reference or at definition's label.
90078458 ((or (eq type 'footnote-reference)
90088459 (and (eq type 'footnote-definition)
90628513 (org-back-to-heading t)
90638514 (setq end (save-excursion (outline-next-heading) (point)))
90648515 (while (re-search-forward org-link-any-re end t)
9065 (push (match-string 0) links))
8516 ;; Only consider valid links or links openable via
8517 ;; `org-open-at-point'.
8518 (when (memq (org-element-type (org-element-context)) '(link comment comment-block node-property keyword))
8519 (push (match-string 0) links)))
90668520 (setq links (org-uniquify (reverse links))))
90678521 (cond
90688522 ((null links)
91688622 (setq m (car p))
91698623 (pop-to-buffer-same-window (marker-buffer m))
91708624 (goto-char m)
9171 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8625 (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
91728626
91738627 ;;; Following specific links
91748628
91778631 (defvar org-agenda-buffer-name)
91788632 (defun org-follow-timestamp-link ()
91798633 "Open an agenda view for the time-stamp date/range at point."
8634 (require 'org-agenda)
91808635 ;; Avoid changing the global value.
91818636 (let ((org-agenda-buffer-name org-agenda-buffer-name))
91828637 (cond
92478702 (defun org-create-dblock (plist)
92488703 "Create a dynamic block section, with parameters taken from PLIST.
92498704 PLIST must contain a :name entry which is used as the name of the block."
9250 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
8705 (when (string-match "\\S-" (buffer-substring (line-beginning-position)
8706 (line-end-position)))
92518707 (end-of-line 1)
92528708 (newline))
92538709 (let ((col (current-column))
93178773 "List all defined dynamic block types."
93188774 (mapcar #'car org-dynamic-block-alist))
93198775
8776 ;;;###org-autoload
93208777 (defun org-dynamic-block-define (type func)
93218778 "Define dynamic block TYPE with FUNC.
93228779 TYPE is a string. FUNC is the function creating the dynamic
94218878 (push (nth 1 option-entry) keywords)))))
94228879
94238880 (defconst org-options-keywords
9424 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
9425 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
9426 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
9427 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
9428 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
8881 '("ARCHIVE:" "AUTHOR:" "BIBLIOGRAPHY:" "BIND:" "CATEGORY:" "CITE_EXPORT:"
8882 "COLUMNS:" "CREATOR:" "DATE:" "DESCRIPTION:" "DRAWERS:" "EMAIL:"
8883 "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:" "INDEX:" "KEYWORDS:" "LANGUAGE:"
8884 "MACRO:" "OPTIONS:" "PROPERTY:" "PRINT_BIBLIOGRAPHY" "PRIORITIES:"
8885 "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:" "TITLE:" "TODO:"
8886 "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "EXPORT_FILE_NAME:"))
94298887
94308888 (defcustom org-structure-template-alist
94318889 '(("a" . "export ascii")
94398897 ("s" . "src")
94408898 ("v" . "verse"))
94418899 "An alist of keys and block types.
9442 `org-insert-structure-template' will display a menu with this
9443 list of templates to choose from. The block type is inserted,
9444 with \"#+BEGIN_\" and \"#+END_\" added automatically.
8900 `org-insert-structure-template' will display a menu with this list of
8901 templates to choose from. The block type is inserted, with
8902 \"#+begin_\" and \"#+end_\" added automatically. If the block type
8903 consists of just uppercase letters, \"#+BEGIN_\" and \"#+END_\" are
8904 added instead.
94458905
94468906 The menu keys are defined by the car of each entry in this alist.
94478907 If two entries have the keys \"a\" and \"aa\" respectively, the
94558915 :type '(repeat
94568916 (cons (string :tag "Key")
94578917 (string :tag "Template")))
9458 :package-version '(Org . "9.2"))
8918 :package-version '(Org . "9.6"))
94598919
94608920 (defun org--check-org-structure-template-alist (&optional checklist)
94618921 "Check whether `org-structure-template-alist' is set up correctly.
94628922 In particular, check if the Org 9.2 format is used as opposed to
94638923 previous format."
94648924 (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
9465 (or (eval checklist)
8925 (or (symbol-value checklist)
94668926 org-structure-template-alist))))
94678927 (when elm
94688928 (org-display-warning
95739033 Select a block from `org-structure-template-alist' then type
95749034 either RET, TAB or SPC to write the block type. With an active
95759035 region, wrap the region in the block. Otherwise, insert an empty
9576 block."
9036 block.
9037
9038 When foo is written as FOO, upcase the #+BEGIN/END as well."
95779039 (interactive
95789040 (list (pcase (org--insert-structure-template-mks)
95799041 (`("\t" . ,_) (read-string "Structure type: "))
95809042 (`(,_ ,choice . ,_) choice))))
9581 (let* ((region? (use-region-p))
9043 (let* ((case-fold-search t) ; Make sure that matches are case-insensitive.
9044 (region? (use-region-p))
95829045 (region-start (and region? (region-beginning)))
95839046 (region-end (and region? (copy-marker (region-end))))
95849047 (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
95859048 (verbatim? (string-match-p
9586 (concat "\\`" (regexp-opt '("example" "export" "src")))
9587 type)))
9049 (concat "\\`" (regexp-opt '("example" "export"
9050 "src" "comment")))
9051 type))
9052 (upcase? (string= (car (split-string type))
9053 (upcase (car (split-string type))))))
95889054 (when region? (goto-char region-start))
95899055 (let ((column (current-indentation)))
95909056 (if (save-excursion (skip-chars-backward " \t") (bolp))
95929058 (insert "\n"))
95939059 (save-excursion
95949060 (indent-to column)
9595 (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
9061 (insert (format "#+%s_%s%s\n" (if upcase? "BEGIN" "begin") type (if extended? " " "")))
95969062 (when region?
95979063 (when verbatim? (org-escape-code-in-region (point) region-end))
95989064 (goto-char region-end)
96019067 (end-of-line))
96029068 (unless (bolp) (insert "\n"))
96039069 (indent-to column)
9604 (insert (format "#+end_%s" (car (split-string type))))
9070 (insert (format "#+%s_%s" (if upcase? "END" "end") (car (split-string type))))
96059071 (if (looking-at "[ \t]*$") (replace-match "")
96069072 (insert "\n"))
96079073 (when (and (eobp) (not (bolp))) (insert "\n")))
96569122 (org-use-last-clock-out-time-as-effective-time
96579123 (or (org-clock-get-last-clock-out-time) ct))
96589124 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
9659 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
9125 (org-encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
96609126 (t ct))))
96619127 ct1))
96629128
96649130 "Like `org-todo' but the time of change will be 23:59 of yesterday."
96659131 (interactive "P")
96669132 (if (eq major-mode 'org-agenda-mode)
9667 (apply 'org-agenda-todo-yesterday arg)
9133 (org-agenda-todo-yesterday arg)
96689134 (let* ((org-use-effective-time t)
96699135 (hour (nth 2 (decode-time (org-current-time))))
96709136 (org-extend-today-until (1+ hour)))
96909156 (replace-match "0" t nil nil 1)))))
96919157
96929158 (defvar org-state)
9693 (defvar org-blocked-by-checkboxes)
9159 ;; FIXME: We should refactor this and similar dynamically scoped blocker flags.
9160 (defvar org-blocked-by-checkboxes nil) ; dynamically scoped
96949161 (defun org-todo (&optional arg)
96959162 "Change the TODO state of an item.
96969163
97399206 nil cl
97409207 (when (org-invisible-p) (org-end-of-subtree nil t))))
97419208 (when (equal arg '(16)) (setq arg 'nextset))
9742 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
9209 (when (equal (prefix-numeric-value arg) -1) (org-cancel-repeater) (setq arg nil))
9210 (when (< (prefix-numeric-value arg) -1) (user-error "Prefix argument %d not supported" arg))
97439211 (let ((org-blocker-hook org-blocker-hook)
97449212 commentp
97459213 case-fold-search)
97839251 ((eq arg 'right)
97849252 ;; Next state
97859253 (if this
9786 (if tail (car tail) nil)
9787 (car org-todo-keywords-1)))
9254 (if tail (car tail) nil)
9255 (car org-todo-keywords-1)))
97889256 ((eq arg 'left)
97899257 ;; Previous state
97909258 (unless (equal member org-todo-keywords-1)
9791 (if this
9259 (if this
97929260 (nth (- (length org-todo-keywords-1)
97939261 (length tail) 2)
9794 org-todo-keywords-1)
9795 (org-last org-todo-keywords-1))))
9262 org-todo-keywords-1)
9263 (org-last org-todo-keywords-1))))
97969264 (arg
97979265 ;; User or caller requests a specific state.
97989266 (cond
98009268 ((eq arg 'none) nil)
98019269 ((eq arg 'done) (or done-word (car org-done-keywords)))
98029270 ((eq arg 'nextset)
9803 (or (car (cdr (member head org-todo-heads)))
9271 (or (car (cdr (member head org-todo-heads)))
98049272 (car org-todo-heads)))
98059273 ((eq arg 'previousset)
9806 (let ((org-todo-heads (reverse org-todo-heads)))
9807 (or (car (cdr (member head org-todo-heads)))
9274 (let ((org-todo-heads (reverse org-todo-heads)))
9275 (or (car (cdr (member head org-todo-heads)))
98089276 (car org-todo-heads))))
98099277 ((car (member arg org-todo-keywords-1)))
98109278 ((stringp arg)
9811 (user-error "State `%s' not valid in this file" arg))
9279 (user-error "State `%s' not valid in this file" arg))
98129280 ((nth (1- (prefix-numeric-value arg))
98139281 org-todo-keywords-1))))
98149282 ((and org-todo-key-trigger org-use-fast-todo-selection)
98199287 ((null tail) nil) ;-> first entry
98209288 ((memq interpret '(type priority))
98219289 (if (eq this-command last-command)
9822 (car tail)
9823 (if (> (length tail) 0)
9290 (car tail)
9291 (if (> (length tail) 0)
98249292 (or done-word (car org-done-keywords))
9825 nil)))
9293 nil)))
98269294 (t
98279295 (car tail))))
98289296 (org-state (or
98539321 this org-state block-reason)
98549322 (throw 'exit nil)))))
98559323 (store-match-data match-data)
9856 (replace-match next t t)
9324 (org-fold-core-ignore-modifications
9325 (goto-char (match-beginning 0))
9326 (replace-match "")
9327 ;; We need to use `insert-before-markers-and-inherit'
9328 ;; because: (1) We want to preserve the folding state
9329 ;; text properties; (2) We do not want to make point
9330 ;; move before new todo state when inserting a new todo
9331 ;; into an empty heading. In (2), the above
9332 ;; `save-excursion' is relying on markers saved before.
9333 (insert-before-markers-and-inherit next)
9334 (unless (org-invisible-p (line-beginning-position))
9335 (org-fold-region (line-beginning-position)
9336 (line-end-position)
9337 nil)))
98579338 (cond ((and org-state (equal this org-state))
98589339 (message "TODO state was already %s" (org-trim next)))
98599340 ((not (pos-visible-in-window-p hl-pos))
99109391 (run-hooks 'org-after-todo-state-change-hook)
99119392 (when (and arg (not (member org-state org-done-keywords)))
99129393 (setq head (org-get-todo-sequence-head org-state)))
9913 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9394 (put-text-property (line-beginning-position)
9395 (line-end-position) 'org-todo-head head)
99149396 ;; Do we need to trigger a repeat?
99159397 (when now-done-p
99169398 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
101239605 (beginning-of-line 1)
101249606 (while (re-search-forward
101259607 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10126 (point-at-eol) t)
9608 (line-end-position) t)
101279609 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
101289610 (goto-char pos)
101299611 (move-marker pos nil)))))
101669648 (setq first nil cookie-present nil)
101679649 (unless (and level
101689650 (not (string-match
10169 "\\<checkbox\\>"
10170 (downcase (or (org-entry-get nil "COOKIE_DATA")
10171 "")))))
9651 "\\<checkbox\\>"
9652 (downcase (or (org-entry-get nil "COOKIE_DATA")
9653 "")))))
101729654 (throw 'exit nil))
10173 (while (re-search-forward box-re (point-at-eol) t)
9655 (while (re-search-forward box-re (line-end-position) t)
101749656 (setq cnt-all 0 cnt-done 0 cookie-present t)
101759657 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
101769658 (save-match-data
102339715
102349716 (defun org-summary-todo (n-done n-not-done)
102359717 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10236 (let (org-log-done org-log-states) ; turn off logging
9718 (let (org-log-done org-todo-log-states) ; turn off logging
102379719 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
102389720
102399721 (defvar org-todo-statistics-hook nil
102799761 (let (p)
102809762 (cond
102819763 ((not kwd)
10282 (or (get-text-property (point-at-bol) 'org-todo-head)
9764 (or (get-text-property (line-beginning-position) 'org-todo-head)
102839765 (progn
10284 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10285 nil (point-at-eol)))
9766 (setq p (next-single-property-change (line-beginning-position)
9767 'org-todo-head
9768 nil (line-end-position)))
102869769 (get-text-property p 'org-todo-head))))
102879770 ((not (member kwd org-todo-keywords-1))
102889771 (car org-todo-keywords-1))
104799962 (while (re-search-forward org-clock-line-re end t)
104809963 (when (org-at-clock-log-p) (throw :clock t))))))
104819964 (org-entry-put nil "LAST_REPEAT" (format-time-string
10482 (org-time-stamp-format t t))))
9965 (org-time-stamp-format t t)
9966 (org-current-effective-time))))
104839967 (when org-log-repeat
104849968 (if org-log-setup
104859969 ;; We are already setup for some record.
1053710021 (let ((nshiftmax 10)
1053810022 (nshift 0))
1053910023 (while (or (= nshift 0)
10540 (not (org-time-less-p nil time)))
10024 (not (time-less-p nil time)))
1054110025 (when (= nshiftmax (cl-incf nshift))
1054210026 (or (y-or-n-p
1054310027 (format "%d repeater intervals were not \
1059410078 "Insert DEADLINE or SCHEDULE information in current entry.
1059510079 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
1059610080 `org-schedule' for information about ARG and TIME arguments."
10597 (let* ((deadline? (eq type 'deadline))
10598 (keyword (if deadline? org-deadline-string org-scheduled-string))
10599 (log (if deadline? org-log-redeadline org-log-reschedule))
10600 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
10601 (old-date-time (and old-date (org-time-string-to-time old-date)))
10602 ;; Save repeater cookie from either TIME or current scheduled
10603 ;; time stamp. We are going to insert it back at the end of
10604 ;; the process.
10605 (repeater (or (and (org-string-nw-p time)
10606 ;; We use `org-repeat-re' because we need
10607 ;; to tell the difference between a real
10608 ;; repeater and a time delta, e.g. "+2d".
10609 (string-match org-repeat-re time)
10610 (match-string 1 time))
10611 (and (org-string-nw-p old-date)
10612 (string-match "\\([.+-]+[0-9]+[hdwmy]\
10081 (org-fold-core-ignore-modifications
10082 (let* ((deadline? (eq type 'deadline))
10083 (keyword (if deadline? org-deadline-string org-scheduled-string))
10084 (log (if deadline? org-log-redeadline org-log-reschedule))
10085 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
10086 (old-date-time (and old-date (org-time-string-to-time old-date)))
10087 ;; Save repeater cookie from either TIME or current scheduled
10088 ;; time stamp. We are going to insert it back at the end of
10089 ;; the process.
10090 (repeater (or (and (org-string-nw-p time)
10091 ;; We use `org-ts-regexp-both' because we
10092 ;; need to tell the difference between a
10093 ;; real repeater and a time delta, e.g.
10094 ;; "+2d".
10095 (string-match-p org-ts-regexp-both time)
10096 (string-match "\\([.+-]+[0-9]+[hdwmy]\
1061310097 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
10614 old-date)
10615 (match-string 1 old-date)))))
10616 (pcase arg
10617 (`(4)
10618 (if (not old-date)
10619 (message (if deadline? "Entry had no deadline to remove"
10620 "Entry was not scheduled"))
10621 (when (and old-date log)
10622 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
10623 nil old-date log))
10624 (org-remove-timestamp-with-keyword keyword)
10625 (message (if deadline? "Entry no longer has a deadline."
10626 "Entry is no longer scheduled."))))
10627 (`(16)
10628 (save-excursion
10629 (org-back-to-heading t)
10630 (let ((regexp (if deadline? org-deadline-time-regexp
10631 org-scheduled-time-regexp)))
10632 (if (not (re-search-forward regexp (line-end-position 2) t))
10633 (user-error (if deadline? "No deadline information to update"
10634 "No scheduled information to update"))
10635 (let* ((rpl0 (match-string 1))
10636 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
10637 (msg (if deadline? "Warn starting from" "Delay until")))
10638 (replace-match
10639 (concat keyword
10640 " <" rpl
10641 (format " -%dd"
10642 (abs (- (time-to-days
10643 (save-match-data
10644 (org-read-date
10645 nil t nil msg old-date-time)))
10646 (time-to-days old-date-time))))
10647 ">") t t))))))
10648 (_
10649 (org-add-planning-info type time 'closed)
10650 (when (and old-date
10651 log
10652 (not (equal old-date org-last-inserted-timestamp)))
10653 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
10654 org-last-inserted-timestamp
10655 old-date
10656 log))
10657 (when repeater
10658 (save-excursion
10098 time)
10099 (match-string 1 time))
10100 (and (org-string-nw-p old-date)
10101 (string-match "\\([.+-]+[0-9]+[hdwmy]\
10102 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
10103 old-date)
10104 (match-string 1 old-date)))))
10105 (pcase arg
10106 (`(4)
10107 (if (not old-date)
10108 (message (if deadline? "Entry had no deadline to remove"
10109 "Entry was not scheduled"))
10110 (when (and old-date log)
10111 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
10112 nil old-date log))
10113 (org-remove-timestamp-with-keyword keyword)
10114 (message (if deadline? "Entry no longer has a deadline."
10115 "Entry is no longer scheduled."))))
10116 (`(16)
10117 (save-excursion
1065910118 (org-back-to-heading t)
10660 (when (re-search-forward
10661 (concat keyword " " org-last-inserted-timestamp)
10662 (line-end-position 2)
10663 t)
10664 (goto-char (1- (match-end 0)))
10665 (insert " " repeater)
10666 (setq org-last-inserted-timestamp
10667 (concat (substring org-last-inserted-timestamp 0 -1)
10668 " " repeater
10669 (substring org-last-inserted-timestamp -1))))))
10670 (message (if deadline? "Deadline on %s" "Scheduled to %s")
10671 org-last-inserted-timestamp)))))
10119 (let ((regexp (if deadline? org-deadline-time-regexp
10120 org-scheduled-time-regexp)))
10121 (if (not (re-search-forward regexp (line-end-position 2) t))
10122 (user-error (if deadline? "No deadline information to update"
10123 "No scheduled information to update"))
10124 (let* ((rpl0 (match-string 1))
10125 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
10126 (msg (if deadline? "Warn starting from" "Delay until")))
10127 (replace-match
10128 (concat keyword
10129 " <" rpl
10130 (format " -%dd"
10131 (abs (- (time-to-days
10132 (save-match-data
10133 (org-read-date
10134 nil t nil msg old-date-time)))
10135 (time-to-days old-date-time))))
10136 ">") t t))))))
10137 (_
10138 (org-add-planning-info type time 'closed)
10139 (when (and old-date
10140 log
10141 (not (equal old-date org-last-inserted-timestamp)))
10142 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
10143 org-last-inserted-timestamp
10144 old-date
10145 log))
10146 (when repeater
10147 (save-excursion
10148 (org-back-to-heading t)
10149 (when (re-search-forward
10150 (concat keyword " " org-last-inserted-timestamp)
10151 (line-end-position 2)
10152 t)
10153 (goto-char (1- (match-end 0)))
10154 (insert-and-inherit " " repeater)
10155 (setq org-last-inserted-timestamp
10156 (concat (substring org-last-inserted-timestamp 0 -1)
10157 " " repeater
10158 (substring org-last-inserted-timestamp -1))))))
10159 (message (if deadline? "Deadline on %s" "Scheduled to %s")
10160 org-last-inserted-timestamp))))))
1067210161
1067310162 (defun org-deadline (arg &optional time)
1067410163 "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
1073810227 (outline-next-heading)
1073910228 (while (re-search-backward re beg t)
1074010229 (replace-match "")
10741 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10230 (if (and (string-match "\\S-" (buffer-substring (line-beginning-position) (point)))
1074210231 (equal (char-before) ?\ ))
10743 (backward-delete-char 1)
10232 (delete-char -1)
1074410233 (when (string-match "^[ \t]*$" (buffer-substring
10745 (point-at-bol) (point-at-eol)))
10746 (delete-region (point-at-bol)
10747 (min (point-max) (1+ (point-at-eol))))))))))
10234 (line-beginning-position) (line-end-position)))
10235 (delete-region (line-beginning-position)
10236 (min (point-max) (1+ (line-end-position))))))))))
1074810237
1074910238 (defvar org-time-was-given) ; dynamically scoped parameter
1075010239 (defvar org-end-time-was-given) ; dynamically scoped parameter
1075310242 "Non-nil when point is on a planning info line."
1075410243 ;; This is as accurate and faster than `org-element-at-point' since
1075510244 ;; planning info location is fixed in the section.
10756 (org-with-wide-buffer
10757 (beginning-of-line)
10758 (and (looking-at-p org-planning-line-re)
10759 (eq (point)
10760 (ignore-errors
10761 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
10762 (org-back-to-heading t)
10763 (org-with-limited-levels (org-back-to-heading t)))
10764 (line-beginning-position 2))))))
10245 (or (let ((cached (org-element-at-point nil 'cached)))
10246 (and cached
10247 (eq 'planning (org-element-type cached))))
10248 (org-with-wide-buffer
10249 (beginning-of-line)
10250 (and (looking-at-p org-planning-line-re)
10251 (eq (point)
10252 (ignore-errors
10253 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
10254 (org-back-to-heading t)
10255 (org-with-limited-levels (org-back-to-heading t)))
10256 (line-beginning-position 2)))))))
1076510257
1076610258 (defun org-add-planning-info (what &optional time &rest remove)
1076710259 "Insert new timestamp with keyword in the planning line.
1077010262 the time to use. If none is given, the user is prompted for
1077110263 a date. REMOVE indicates what kind of entries to remove. An old
1077210264 WHAT entry will also be removed."
10773 (let (org-time-was-given org-end-time-was-given default-time default-input)
10774 (when (and (memq what '(scheduled deadline))
10775 (or (not time)
10776 (and (stringp time)
10777 (string-match "^[-+]+[0-9]" time))))
10778 ;; Try to get a default date/time from existing timestamp
10779 (save-excursion
10780 (org-back-to-heading t)
10781 (let ((end (save-excursion (outline-next-heading) (point))) ts)
10782 (when (re-search-forward (if (eq what 'scheduled)
10783 org-scheduled-time-regexp
10784 org-deadline-time-regexp)
10785 end t)
10786 (setq ts (match-string 1)
10787 default-time (org-time-string-to-time ts)
10788 default-input (and ts (org-get-compact-tod ts)))))))
10789 (when what
10790 (setq time
10791 (if (stringp time)
10792 ;; This is a string (relative or absolute), set
10793 ;; proper date.
10794 (apply #'encode-time
10795 (org-read-date-analyze
10796 time default-time (decode-time default-time)))
10797 ;; If necessary, get the time from the user
10798 (or time (org-read-date nil 'to-time nil
10799 (cl-case what
10800 (deadline "DEADLINE")
10801 (scheduled "SCHEDULED")
10802 (otherwise nil))
10803 default-time default-input)))))
10804 (org-with-wide-buffer
10805 (org-back-to-heading t)
10806 (let ((planning? (save-excursion
10807 (forward-line)
10808 (looking-at-p org-planning-line-re))))
10809 (cond
10810 (planning?
10811 (forward-line)
10812 ;; Move to current indentation.
10813 (skip-chars-forward " \t")
10814 ;; Check if we have to remove something.
10815 (dolist (type (if what (cons what remove) remove))
10816 (save-excursion
10817 (when (re-search-forward
10818 (cl-case type
10819 (closed org-closed-time-regexp)
10820 (deadline org-deadline-time-regexp)
10821 (scheduled org-scheduled-time-regexp)
10822 (otherwise (error "Invalid planning type: %s" type)))
10823 (line-end-position)
10824 t)
10825 ;; Delete until next keyword or end of line.
10826 (delete-region
10827 (match-beginning 0)
10828 (if (re-search-forward org-keyword-time-not-clock-regexp
10829 (line-end-position)
10830 t)
10831 (match-beginning 0)
10832 (line-end-position))))))
10833 ;; If there is nothing more to add and no more keyword is
10834 ;; left, remove the line completely.
10835 (if (and (looking-at-p "[ \t]*$") (not what))
10836 (delete-region (line-end-position 0)
10837 (line-end-position))
10838 ;; If we removed last keyword, do not leave trailing white
10839 ;; space at the end of line.
10840 (let ((p (point)))
10265 (org-fold-core-ignore-modifications
10266 (let (org-time-was-given org-end-time-was-given default-time default-input)
10267 (when (and (memq what '(scheduled deadline))
10268 (or (not time)
10269 (and (stringp time)
10270 (string-match "^[-+]+[0-9]" time))))
10271 ;; Try to get a default date/time from existing timestamp
10272 (save-excursion
10273 (org-back-to-heading t)
10274 (let ((end (save-excursion (outline-next-heading) (point))) ts)
10275 (when (re-search-forward (if (eq what 'scheduled)
10276 org-scheduled-time-regexp
10277 org-deadline-time-regexp)
10278 end t)
10279 (setq ts (match-string 1)
10280 default-time (org-time-string-to-time ts)
10281 default-input (and ts (org-get-compact-tod ts)))))))
10282 (when what
10283 (setq time
10284 (if (stringp time)
10285 ;; This is a string (relative or absolute), set
10286 ;; proper date.
10287 (org-encode-time
10288 (org-read-date-analyze
10289 time default-time (decode-time default-time)))
10290 ;; If necessary, get the time from the user
10291 (or time (org-read-date nil 'to-time nil
10292 (cl-case what
10293 (deadline "DEADLINE")
10294 (scheduled "SCHEDULED")
10295 (otherwise nil))
10296 default-time default-input)))))
10297 (org-with-wide-buffer
10298 (org-back-to-heading t)
10299 (let ((planning? (save-excursion
10300 (forward-line)
10301 (looking-at-p org-planning-line-re))))
10302 (cond
10303 (planning?
10304 (forward-line)
10305 ;; Move to current indentation.
10306 (skip-chars-forward " \t")
10307 ;; Check if we have to remove something.
10308 (dolist (type (if what (cons what remove) remove))
1084110309 (save-excursion
10842 (end-of-line)
10843 (unless (= (skip-chars-backward " \t" p) 0)
10844 (delete-region (point) (line-end-position)))))))
10845 (what
10846 (end-of-line)
10847 (insert "\n")
10848 (when org-adapt-indentation
10849 (indent-to-column (1+ (org-outline-level)))))
10850 (t nil)))
10851 (when what
10852 ;; Insert planning keyword.
10853 (insert (cl-case what
10854 (closed org-closed-string)
10855 (deadline org-deadline-string)
10856 (scheduled org-scheduled-string)
10857 (otherwise (error "Invalid planning type: %s" what)))
10858 " ")
10859 ;; Insert associated timestamp.
10860 (let ((ts (org-insert-time-stamp
10861 time
10862 (or org-time-was-given
10863 (and (eq what 'closed) org-log-done-with-time))
10864 (eq what 'closed)
10865 nil nil (list org-end-time-was-given))))
10866 (unless (eolp) (insert " "))
10867 ts)))))
10310 (when (re-search-forward
10311 (cl-case type
10312 (closed org-closed-time-regexp)
10313 (deadline org-deadline-time-regexp)
10314 (scheduled org-scheduled-time-regexp)
10315 (otherwise (error "Invalid planning type: %s" type)))
10316 (line-end-position)
10317 t)
10318 ;; Delete until next keyword or end of line.
10319 (delete-region
10320 (match-beginning 0)
10321 (if (re-search-forward org-keyword-time-not-clock-regexp
10322 (line-end-position)
10323 t)
10324 (match-beginning 0)
10325 (line-end-position))))))
10326 ;; If there is nothing more to add and no more keyword is
10327 ;; left, remove the line completely.
10328 (if (and (looking-at-p "[ \t]*$") (not what))
10329 (delete-region (line-end-position 0)
10330 (line-end-position))
10331 ;; If we removed last keyword, do not leave trailing white
10332 ;; space at the end of line.
10333 (let ((p (point)))
10334 (save-excursion
10335 (end-of-line)
10336 (unless (= (skip-chars-backward " \t" p) 0)
10337 (delete-region (point) (line-end-position)))))))
10338 (what
10339 (end-of-line)
10340 (insert-and-inherit "\n")
10341 (when org-adapt-indentation
10342 (indent-to-column (1+ (org-outline-level)))))
10343 (t nil)))
10344 (when what
10345 ;; Insert planning keyword.
10346 (insert-and-inherit (cl-case what
10347 (closed org-closed-string)
10348 (deadline org-deadline-string)
10349 (scheduled org-scheduled-string)
10350 (otherwise (error "Invalid planning type: %s" what)))
10351 " ")
10352 ;; Insert associated timestamp.
10353 (let ((ts (org-insert-time-stamp
10354 time
10355 (or org-time-was-given
10356 (and (eq what 'closed) org-log-done-with-time))
10357 (eq what 'closed)
10358 nil nil (list org-end-time-was-given))))
10359 (unless (eolp) (insert " "))
10360 ts))))))
1086810361
1086910362 (defvar org-log-note-marker (make-marker)
1087010363 "Marker pointing at the entry where the note is to be inserted.")
1087810371 "Remembered current time.
1087910372 So that dynamically scoped `org-extend-today-until' affects
1088010373 timestamps in state change log.")
10374 (defvar org-log-note-this-command
10375 "`this-command' when `org-add-log-setup' is called.")
10376 (defvar org-log-note-recursion-depth
10377 "`recursion-depth' when `org-add-log-setup' is called.")
1088110378
1088210379 (defvar org-log-post-message nil
1088310380 "Message to be displayed after a log note has been stored.
1091410411 (throw 'exit nil))))
1091510412 ;; No drawer found. Create one, if permitted.
1091610413 (when create
10917 (unless (bolp) (insert "\n"))
10918 (let ((beg (point)))
10919 (insert ":" drawer ":\n:END:\n")
10920 (org-indent-region beg (point))
10921 (org-flag-region (line-end-position -1)
10922 (1- (point)) t 'outline))
10923 (end-of-line -1)))))
10414 ;; Unless current heading is the last heading in buffer
10415 ;; and does not have a newline, `org-end-of-meta-data'
10416 ;; should move us somewhere below the heading.
10417 ;; Avoid situation when we insert drawer right before
10418 ;; first "*". Otherwise, if the previous heading is
10419 ;; folded, we are inserting after visible newline at
10420 ;; the end of the fold, thus breaking the fold
10421 ;; continuity.
10422 (unless (eobp)
10423 (when (org-at-heading-p) (backward-char)))
10424 (org-fold-core-ignore-modifications
10425 (unless (bolp) (insert-and-inherit "\n"))
10426 (let ((beg (point)))
10427 (insert-and-inherit ":" drawer ":\n:END:\n")
10428 (org-indent-region beg (point))
10429 (org-fold-region (line-end-position -1) (1- (point)) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline)))))
10430 (end-of-line -1))))
1092410431 (t
1092510432 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
10926 (skip-chars-forward " \t\n")
10927 (beginning-of-line)
10928 (unless org-log-states-order-reversed
10929 (org-skip-over-state-notes)
10930 (skip-chars-backward " \t\n")
10931 (forward-line)))))
10433 (let ((endpos (point)))
10434 (skip-chars-forward " \t\n")
10435 (beginning-of-line)
10436 (unless org-log-states-order-reversed
10437 (org-skip-over-state-notes)
10438 (skip-chars-backward " \t\n")
10439 (beginning-of-line 2))
10440 ;; When current headline is at the end of buffer and does not
10441 ;; end with trailing newline the above can move to the
10442 ;; beginning of the headline.
10443 (when (< (point) endpos) (goto-char endpos))))))
1093210444 (if (bolp) (point) (line-beginning-position 2))))
1093310445
1093410446 (defun org-add-log-setup (&optional purpose state prev-state how extra)
1094310455 org-log-note-how how
1094410456 org-log-note-extra extra
1094510457 org-log-note-effective-time (org-current-effective-time)
10458 org-log-note-this-command this-command
10459 org-log-note-recursion-depth (recursion-depth)
1094610460 org-log-setup t)
1094710461 (add-hook 'post-command-hook 'org-add-log-note 'append))
1094810462
1097110485
1097210486 (defun org-add-log-note (&optional _purpose)
1097310487 "Pop up a window for taking a note, and add this note later."
10974 (remove-hook 'post-command-hook 'org-add-log-note)
10975 (setq org-log-setup nil)
10976 (setq org-log-note-window-configuration (current-window-configuration))
10977 (delete-other-windows)
10978 (move-marker org-log-note-return-to (point))
10979 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
10980 (goto-char org-log-note-marker)
10981 (org-switch-to-buffer-other-window "*Org Note*")
10982 (erase-buffer)
10983 (if (memq org-log-note-how '(time state))
10984 (org-store-log-note)
10985 (let ((org-inhibit-startup t)) (org-mode))
10986 (insert (format "# Insert note for %s.
10488 (when (and (equal org-log-note-this-command this-command)
10489 (= org-log-note-recursion-depth (recursion-depth)))
10490 (remove-hook 'post-command-hook 'org-add-log-note)
10491 (setq org-log-setup nil)
10492 (setq org-log-note-window-configuration (current-window-configuration))
10493 (delete-other-windows)
10494 (move-marker org-log-note-return-to (point))
10495 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
10496 (goto-char org-log-note-marker)
10497 (org-switch-to-buffer-other-window "*Org Note*")
10498 (erase-buffer)
10499 (if (memq org-log-note-how '(time state))
10500 (org-store-log-note)
10501 (let ((org-inhibit-startup t)) (org-mode))
10502 (insert (format "# Insert note for %s.
1098710503 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10988 (cl-case org-log-note-purpose
10989 (clock-out "stopped clock")
10990 (done "closed todo item")
10991 (reschedule "rescheduling")
10992 (delschedule "no longer scheduled")
10993 (redeadline "changing deadline")
10994 (deldeadline "removing deadline")
10995 (refile "refiling")
10996 (note "this entry")
10997 (state
10998 (format "state change from \"%s\" to \"%s\""
10999 (or org-log-note-previous-state "")
11000 (or org-log-note-state "")))
11001 (t (error "This should not happen")))))
11002 (when org-log-note-extra (insert org-log-note-extra))
11003 (setq-local org-finish-function 'org-store-log-note)
11004 (run-hooks 'org-log-buffer-setup-hook)))
10504 (cl-case org-log-note-purpose
10505 (clock-out "stopped clock")
10506 (done "closed todo item")
10507 (reschedule "rescheduling")
10508 (delschedule "no longer scheduled")
10509 (redeadline "changing deadline")
10510 (deldeadline "removing deadline")
10511 (refile "refiling")
10512 (note "this entry")
10513 (state
10514 (format "state change from \"%s\" to \"%s\""
10515 (or org-log-note-previous-state "")
10516 (or org-log-note-state "")))
10517 (t (error "This should not happen")))))
10518 (when org-log-note-extra (insert org-log-note-extra))
10519 (setq-local org-finish-function 'org-store-log-note)
10520 (run-hooks 'org-log-buffer-setup-hook))))
1100510521
1100610522 (defvar org-note-abort nil) ; dynamically scoped
1100710523 (defun org-store-log-note ()
1105410570 (push note lines))
1105510571 (when (and lines (not org-note-abort))
1105610572 (with-current-buffer (marker-buffer org-log-note-marker)
11057 (org-with-wide-buffer
11058 ;; Find location for the new note.
11059 (goto-char org-log-note-marker)
11060 (set-marker org-log-note-marker nil)
11061 ;; Note associated to a clock is to be located right after
11062 ;; the clock. Do not move point.
11063 (unless (eq org-log-note-purpose 'clock-out)
11064 (goto-char (org-log-beginning t)))
11065 ;; Make sure point is at the beginning of an empty line.
11066 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11067 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
11068 ;; In an existing list, add a new item at the top level.
11069 ;; Otherwise, indent line like a regular one.
11070 (let ((itemp (org-in-item-p)))
11071 (if itemp
11072 (indent-line-to
11073 (let ((struct (save-excursion
11074 (goto-char itemp) (org-list-struct))))
11075 (org-list-get-ind (org-list-get-top-point struct) struct)))
11076 (org-indent-line)))
11077 (insert (org-list-bullet-string "-") (pop lines))
11078 (let ((ind (org-list-item-body-column (line-beginning-position))))
11079 (dolist (line lines)
11080 (insert "\n")
11081 (indent-line-to ind)
11082 (insert line)))
11083 (message "Note stored")
11084 (org-back-to-heading t)))))
10573 (org-fold-core-ignore-modifications
10574 (org-with-wide-buffer
10575 ;; Find location for the new note.
10576 (goto-char org-log-note-marker)
10577 (set-marker org-log-note-marker nil)
10578 ;; Note associated to a clock is to be located right after
10579 ;; the clock. Do not move point.
10580 (unless (eq org-log-note-purpose 'clock-out)
10581 (goto-char (org-log-beginning t)))
10582 ;; Make sure point is at the beginning of an empty line.
10583 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
10584 ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
10585 ;; In an existing list, add a new item at the top level.
10586 ;; Otherwise, indent line like a regular one.
10587 (let ((itemp (org-in-item-p)))
10588 (if itemp
10589 (indent-line-to
10590 (let ((struct (save-excursion
10591 (goto-char itemp) (org-list-struct))))
10592 (org-list-get-ind (org-list-get-top-point struct) struct)))
10593 (org-indent-line)))
10594 (insert-and-inherit (org-list-bullet-string "-") (pop lines))
10595 (let ((ind (org-list-item-body-column (line-beginning-position))))
10596 (dolist (line lines)
10597 (insert-and-inherit "\n")
10598 (unless (string-empty-p line)
10599 (indent-line-to ind)
10600 (insert-and-inherit line))))
10601 (message "Note stored")
10602 (org-back-to-heading t))))))
1108510603 ;; Don't add undo information when called from `org-agenda-todo'.
1108610604 (set-window-configuration org-log-note-window-configuration)
1108710605 (with-current-buffer (marker-buffer org-log-note-return-to)
1116110679
1116210680 (defvar-local org-occur-highlights nil
1116310681 "List of overlays used for occur matches.")
10682 (put 'org-occur-highlights 'permanent-local t)
1116410683 (defvar-local org-occur-parameters nil
1116510684 "Parameters of the active org-occur calls.
1116610685 This is a list, each call to org-occur pushes as cons cell,
1117610695 "Make a compact tree showing all matches of REGEXP.
1117710696
1117810697 The tree will show the lines where the regexp matches, and any other context
11179 defined in `org-show-context-detail', which see.
10698 defined in `org-fold-show-context-detail', which see.
1118010699
1118110700 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
1118210701 done by a previous call to `org-occur' will be kept, to allow stacking of
1119810717 (when (or (not keep-previous) ; do not want to keep
1119910718 (not org-occur-highlights)) ; no previous matches
1120010719 ;; hide everything
11201 (org-overview))
10720 (org-cycle-overview))
1120210721 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
1120310722 (isearch-no-upper-case-p regexp t)
1120410723 org-occur-case-fold-search)))
1120810727 (setq cnt (1+ cnt))
1120910728 (when org-highlight-sparse-tree-matches
1121010729 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11211 (org-show-context 'occur-tree)))))
10730 (org-fold-show-context 'occur-tree)))))
1121210731 (when org-remove-highlights-with-change
1121310732 (add-hook 'before-change-functions 'org-remove-occur-highlights
1121410733 nil 'local))
1121510734 (unless org-sparse-tree-open-archived-trees
11216 (org-hide-archived-subtrees (point-min) (point-max)))
10735 (org-fold-hide-archived-subtrees (point-min) (point-max)))
1121710736 (run-hooks 'org-occur-hook)
1121810737 (when (called-interactively-p 'interactive)
1121910738 (message "%d match(es) for regexp %s" cnt regexp))
1147210991 ;; Get the correct level to match
1147310992 (concat "\\*\\{" (number-to-string start-level) "\\} ")
1147410993 org-outline-regexp)
11475 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
10994 " *\\(?:\\(" (regexp-opt org-todo-keywords-1 t) "\\) \\)?"
1147610995 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
1147710996 (props (list 'face 'default
1147810997 'done-face 'org-agenda-done
1149711016 (save-excursion
1149811017 (goto-char (point-min))
1149911018 (when (eq action 'sparse-tree)
11500 (org-overview)
11019 (org-cycle-overview)
1150111020 (org-remove-occur-highlights))
11502 (while (let (case-fold-search)
11503 (re-search-forward re nil t))
11504 (setq org-map-continue-from nil)
11505 (catch :skip
11506 ;; Ignore closing parts of inline tasks.
11507 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
11508 (throw :skip t))
11509 (setq todo (and (match-end 1) (match-string-no-properties 1)))
11510 (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
11511 (goto-char (setq lspos (match-beginning 0)))
11512 (setq level (org-reduced-level (org-outline-level))
11513 category (org-get-category))
11514 (when (eq action 'agenda)
11515 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
11516 ts-date (car ts-date-pair)
11517 ts-date-type (cdr ts-date-pair)))
11518 (setq i llast llast level)
11519 ;; remove tag lists from same and sublevels
11520 (while (>= i level)
11521 (when (setq entry (assoc i tags-alist))
11522 (setq tags-alist (delete entry tags-alist)))
11523 (setq i (1- i)))
11524 ;; add the next tags
11525 (when tags
11526 (setq tags (org-split-string tags ":")
11527 tags-alist
11528 (cons (cons level tags) tags-alist)))
11529 ;; compile tags for current headline
11530 (setq tags-list
11531 (if org-use-tag-inheritance
11532 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11533 tags)
11534 org-scanner-tags tags-list)
11535 (when org-use-tag-inheritance
11536 (setcdr (car tags-alist)
11537 (mapcar (lambda (x)
11538 (setq x (copy-sequence x))
11539 (org-add-prop-inherited x))
11540 (cdar tags-alist))))
11541 (when (and tags org-use-tag-inheritance
11542 (or (not (eq t org-use-tag-inheritance))
11543 org-tags-exclude-from-inheritance))
11544 ;; Selective inheritance, remove uninherited ones.
11545 (setcdr (car tags-alist)
11546 (org-remove-uninherited-tags (cdar tags-alist))))
11547 (when (and
11548
11549 ;; eval matcher only when the todo condition is OK
11550 (and (or (not todo-only) (member todo org-todo-keywords-1))
11551 (if (functionp matcher)
11552 (let ((case-fold-search t) (org-trust-scanner-tags t))
11553 (funcall matcher todo tags-list level))
11554 matcher))
11555
11556 ;; Call the skipper, but return t if it does not
11557 ;; skip, so that the `and' form continues evaluating.
11558 (progn
11559 (unless (eq action 'sparse-tree) (org-agenda-skip))
11560 t)
11561
11562 ;; Check if timestamps are deselecting this entry
11563 (or (not todo-only)
11564 (and (member todo org-todo-keywords-1)
11565 (or (not org-agenda-tags-todo-honor-ignore-options)
11566 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
11567
11568 ;; select this headline
11569 (cond
11570 ((eq action 'sparse-tree)
11571 (and org-highlight-sparse-tree-matches
11572 (org-get-heading) (match-end 0)
11573 (org-highlight-new-match
11574 (match-beginning 1) (match-end 1)))
11575 (org-show-context 'tags-tree))
11576 ((eq action 'agenda)
11577 (setq txt (org-agenda-format-item
11578 ""
11579 (concat
11580 (if (eq org-tags-match-list-sublevels 'indented)
11581 (make-string (1- level) ?.) "")
11582 (org-get-heading))
11583 (make-string level ?\s)
11584 category
11585 tags-list)
11586 priority (org-get-priority txt))
11587 (goto-char lspos)
11588 (setq marker (org-agenda-new-marker))
11589 (org-add-props txt props
11590 'org-marker marker 'org-hd-marker marker 'org-category category
11591 'todo-state todo
11592 'ts-date ts-date
11593 'priority priority
11594 'type (concat "tagsmatch" ts-date-type))
11595 (push txt rtn))
11596 ((functionp action)
11597 (setq org-map-continue-from nil)
11598 (save-excursion
11599 (setq rtn1 (funcall action))
11600 (push rtn1 rtn)))
11601 (t (user-error "Invalid action")))
11602
11603 ;; if we are to skip sublevels, jump to end of subtree
11604 (unless org-tags-match-list-sublevels
11605 (org-end-of-subtree t)
11606 (backward-char 1))))
11607 ;; Get the correct position from where to continue
11608 (if org-map-continue-from
11609 (goto-char org-map-continue-from)
11610 (and (= (point) lspos) (end-of-line 1)))))
11021 (if (org-element--cache-active-p)
11022 (let ((fast-re (concat "^"
11023 (if start-level
11024 ;; Get the correct level to match
11025 (concat "\\*\\{" (number-to-string start-level) "\\} ")
11026 org-outline-regexp))))
11027 (org-element-cache-map
11028 (lambda (el)
11029 (goto-char (org-element-property :begin el))
11030 (setq todo (org-element-property :todo-keyword el)
11031 level (org-element-property :level el)
11032 category (org-entry-get-with-inheritance "CATEGORY" nil el)
11033 tags-list (org-get-tags el)
11034 org-scanner-tags tags-list)
11035 (when (eq action 'agenda)
11036 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
11037 ts-date (car ts-date-pair)
11038 ts-date-type (cdr ts-date-pair)))
11039 (catch :skip
11040 (when (and
11041
11042 ;; eval matcher only when the todo condition is OK
11043 (and (or (not todo-only) (member todo org-todo-keywords-1))
11044 (if (functionp matcher)
11045 (let ((case-fold-search t) (org-trust-scanner-tags t))
11046 (funcall matcher todo tags-list level))
11047 matcher))
11048
11049 ;; Call the skipper, but return t if it does not
11050 ;; skip, so that the `and' form continues evaluating.
11051 (progn
11052 (unless (eq action 'sparse-tree) (org-agenda-skip el))
11053 t)
11054
11055 ;; Check if timestamps are deselecting this entry
11056 (or (not todo-only)
11057 (and (member todo org-todo-keywords-1)
11058 (or (not org-agenda-tags-todo-honor-ignore-options)
11059 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
11060
11061 ;; select this headline
11062 (cond
11063 ((eq action 'sparse-tree)
11064 (and org-highlight-sparse-tree-matches
11065 (org-get-heading) (match-end 0)
11066 (org-highlight-new-match
11067 (match-beginning 1) (match-end 1)))
11068 (org-fold-show-context 'tags-tree))
11069 ((eq action 'agenda)
11070 (let* ((effort (org-entry-get (point) org-effort-property))
11071 (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
11072 (setq txt (org-agenda-format-item
11073 ""
11074 ;; Add `effort' and `effort-minutes'
11075 ;; properties for prefix format.
11076 (org-add-props
11077 (concat
11078 (if (eq org-tags-match-list-sublevels 'indented)
11079 (make-string (1- level) ?.) "")
11080 (org-get-heading))
11081 nil
11082 'effort effort
11083 'effort-minutes effort-minutes)
11084 (make-string level ?\s)
11085 category
11086 tags-list)
11087 priority (org-get-priority txt))
11088 ;; Now add `effort' and `effort-minutes' to
11089 ;; full agenda line.
11090 (setq txt (org-add-props txt nil
11091 'effort effort
11092 'effort-minutes effort-minutes)))
11093 (goto-char (org-element-property :begin el))
11094 (setq marker (org-agenda-new-marker))
11095 (org-add-props txt props
11096 'org-marker marker 'org-hd-marker marker 'org-category category
11097 'todo-state todo
11098 'ts-date ts-date
11099 'priority priority
11100 'type (concat "tagsmatch" ts-date-type))
11101 (push txt rtn))
11102 ((functionp action)
11103 (setq org-map-continue-from nil)
11104 (save-excursion
11105 (setq rtn1 (funcall action))
11106 (push rtn1 rtn)))
11107 (t (user-error "Invalid action")))
11108
11109 ;; if we are to skip sublevels, jump to end of subtree
11110 (unless org-tags-match-list-sublevels
11111 (goto-char (1- (org-element-property :end el))))))
11112 ;; Get the correct position from where to continue
11113 (when org-map-continue-from
11114 (setq org-element-cache-map-continue-from org-map-continue-from)
11115 (goto-char org-map-continue-from))
11116 ;; Return nil.
11117 nil)
11118 :next-re fast-re
11119 :fail-re fast-re
11120 :narrow t))
11121 (while (let (case-fold-search)
11122 (re-search-forward re nil t))
11123 (setq org-map-continue-from nil)
11124 (catch :skip
11125 ;; Ignore closing parts of inline tasks.
11126 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
11127 (throw :skip t))
11128 (setq todo (and (match-end 1) (match-string-no-properties 1)))
11129 (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
11130 (goto-char (setq lspos (match-beginning 0)))
11131 (setq level (org-reduced-level (org-outline-level))
11132 category (org-get-category))
11133 (when (eq action 'agenda)
11134 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
11135 ts-date (car ts-date-pair)
11136 ts-date-type (cdr ts-date-pair)))
11137 (setq i llast llast level)
11138 ;; remove tag lists from same and sublevels
11139 (while (>= i level)
11140 (when (setq entry (assoc i tags-alist))
11141 (setq tags-alist (delete entry tags-alist)))
11142 (setq i (1- i)))
11143 ;; add the next tags
11144 (when tags
11145 (setq tags (org-split-string tags ":")
11146 tags-alist
11147 (cons (cons level tags) tags-alist)))
11148 ;; compile tags for current headline
11149 (setq tags-list
11150 (if org-use-tag-inheritance
11151 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11152 tags)
11153 org-scanner-tags tags-list)
11154 (when org-use-tag-inheritance
11155 (setcdr (car tags-alist)
11156 (mapcar (lambda (x)
11157 (setq x (copy-sequence x))
11158 (org-add-prop-inherited x))
11159 (cdar tags-alist))))
11160 (when (and tags org-use-tag-inheritance
11161 (or (not (eq t org-use-tag-inheritance))
11162 org-tags-exclude-from-inheritance))
11163 ;; Selective inheritance, remove uninherited ones.
11164 (setcdr (car tags-alist)
11165 (org-remove-uninherited-tags (cdar tags-alist))))
11166 (when (and
11167
11168 ;; eval matcher only when the todo condition is OK
11169 (and (or (not todo-only) (member todo org-todo-keywords-1))
11170 (if (functionp matcher)
11171 (let ((case-fold-search t) (org-trust-scanner-tags t))
11172 (funcall matcher todo tags-list level))
11173 matcher))
11174
11175 ;; Call the skipper, but return t if it does not
11176 ;; skip, so that the `and' form continues evaluating.
11177 (progn
11178 (unless (eq action 'sparse-tree) (org-agenda-skip))
11179 t)
11180
11181 ;; Check if timestamps are deselecting this entry
11182 (or (not todo-only)
11183 (and (member todo org-todo-keywords-1)
11184 (or (not org-agenda-tags-todo-honor-ignore-options)
11185 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
11186
11187 ;; select this headline
11188 (cond
11189 ((eq action 'sparse-tree)
11190 (and org-highlight-sparse-tree-matches
11191 (org-get-heading) (match-end 0)
11192 (org-highlight-new-match
11193 (match-beginning 1) (match-end 1)))
11194 (org-fold-show-context 'tags-tree))
11195 ((eq action 'agenda)
11196 (setq txt (org-agenda-format-item
11197 ""
11198 (concat
11199 (if (eq org-tags-match-list-sublevels 'indented)
11200 (make-string (1- level) ?.) "")
11201 (org-get-heading))
11202 (make-string level ?\s)
11203 category
11204 tags-list)
11205 priority (org-get-priority txt))
11206 (goto-char lspos)
11207 (setq marker (org-agenda-new-marker))
11208 (org-add-props txt props
11209 'org-marker marker 'org-hd-marker marker 'org-category category
11210 'todo-state todo
11211 'ts-date ts-date
11212 'priority priority
11213 'type (concat "tagsmatch" ts-date-type))
11214 (push txt rtn))
11215 ((functionp action)
11216 (setq org-map-continue-from nil)
11217 (save-excursion
11218 (setq rtn1 (funcall action))
11219 (push rtn1 rtn)))
11220 (t (user-error "Invalid action")))
11221
11222 ;; if we are to skip sublevels, jump to end of subtree
11223 (unless org-tags-match-list-sublevels
11224 (org-end-of-subtree t)
11225 (backward-char 1))))
11226 ;; Get the correct position from where to continue
11227 (if org-map-continue-from
11228 (goto-char org-map-continue-from)
11229 (and (= (point) lspos) (end-of-line 1))))))
1161111230 (when (and (eq action 'sparse-tree)
1161211231 (not org-sparse-tree-open-archived-trees))
11613 (org-hide-archived-subtrees (point-min) (point-max)))
11232 (org-fold-hide-archived-subtrees (point-min) (point-max)))
1161411233 (nreverse rtn)))
1161511234
1161611235 (defun org-remove-uninherited-tags (tags)
1178711406 (propp
1178811407 (let* ((gv (pcase (upcase (match-string 5 term))
1178911408 ("CATEGORY"
11790 '(get-text-property (point) 'org-category))
11409 '(org-get-category (point)))
1179111410 ("TODO" 'todo)
1179211411 (p `(org-cached-entry-get nil ,p))))
1179311412 (pv (match-string 7 term))
1179411413 (regexp (eq (string-to-char pv) ?{))
1179511414 (strp (eq (string-to-char pv) ?\"))
11796 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
11415 (timep (string-match-p "^\"[[<]\\(?:[0-9]+\\|now\\|today\\|tomorrow\\|[+-][0-9]+[dmwy]\\).*[]>]\"$" pv))
1179711416 (po (org-op-to-function (match-string 6 term)
1179811417 (if timep 'time strp))))
1179911418 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
1202911648 (cond
1203011649 ((equal '(4) arg) (org-align-tags t))
1203111650 ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
12032 (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
11651 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11652 'region-start-level 'region))
11653 org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
1203311654 (org-map-entries
1203411655 #'org-set-tags-command
12035 nil
12036 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12037 'region-start-level
12038 'region)
11656 nil cl
1203911657 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
1204011658 (t
1204111659 (save-excursion
1204211660 (org-back-to-heading)
1204311661 (let* ((all-tags (org-get-tags))
11662 (local-table (or org-current-tag-alist (org-get-buffer-tags)))
1204411663 (table (setq org-last-tags-completion-table
12045 (org--tag-add-to-alist
12046 (and org-complete-tags-always-offer-all-agenda-tags
12047 (org-global-tags-completion-table
12048 (org-agenda-files)))
12049 (or org-current-tag-alist (org-get-buffer-tags)))))
11664 (append
11665 ;; Put local tags in front.
11666 local-table
11667 (cl-set-difference
11668 (org--tag-add-to-alist
11669 (and org-complete-tags-always-offer-all-agenda-tags
11670 (org-global-tags-completion-table
11671 (org-agenda-files)))
11672 local-table)
11673 local-table))))
1205011674 (current-tags
1205111675 (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
1205211676 all-tags))
1208811712 (let ((get-indent-column
1208911713 (lambda ()
1209011714 (let ((offset (if (bound-and-true-p org-indent-mode)
12091 (* (1- org-indent-indentation-per-level)
12092 (1- (org-current-level)))
11715 (save-excursion
11716 (org-back-to-heading-or-point-min)
11717 (length
11718 (get-text-property
11719 (line-end-position)
11720 'line-prefix)))
1209311721 0)))
1209411722 (+ org-tags-column
1209511723 (if (> org-tags-column 0) (- offset) offset))))))
1211211740
1211311741 This function assumes point is on a headline."
1211411742 (org-with-wide-buffer
12115 (let ((tags (pcase tags
12116 ((pred listp) tags)
12117 ((pred stringp) (split-string (org-trim tags) ":" t))
12118 (_ (error "Invalid tag specification: %S" tags))))
12119 (old-tags (org-get-tags nil t))
12120 (tags-change? nil))
12121 (when (functionp org-tags-sort-function)
12122 (setq tags (sort tags org-tags-sort-function)))
12123 (setq tags-change? (not (equal tags old-tags)))
12124 (when tags-change?
12125 ;; Delete previous tags and any trailing white space.
12126 (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
12127 (line-end-position)))
12128 (skip-chars-backward " \t")
12129 (delete-region (point) (line-end-position))
12130 ;; Deleting white spaces may break an otherwise empty headline.
12131 ;; Re-introduce one space in this case.
12132 (unless (org-at-heading-p) (insert " "))
12133 (when tags
12134 (save-excursion (insert " " (org-make-tag-string tags)))
12135 ;; When text is being inserted on an invisible region
12136 ;; boundary, it can be inadvertently sucked into
12137 ;; invisibility.
12138 (unless (org-invisible-p (line-beginning-position))
12139 (org-flag-region (point) (line-end-position) nil 'outline))))
12140 ;; Align tags, if any.
12141 (when tags (org-align-tags))
12142 (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
11743 (org-fold-core-ignore-modifications
11744 (let ((tags (pcase tags
11745 ((pred listp) tags)
11746 ((pred stringp) (split-string (org-trim tags) ":" t))
11747 (_ (error "Invalid tag specification: %S" tags))))
11748 (old-tags (org-get-tags nil t))
11749 (tags-change? nil))
11750 (when (functionp org-tags-sort-function)
11751 (setq tags (sort tags org-tags-sort-function)))
11752 (setq tags-change? (not (equal tags old-tags)))
11753 (when tags-change?
11754 ;; Delete previous tags and any trailing white space.
11755 (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
11756 (line-end-position)))
11757 (skip-chars-backward " \t")
11758 (delete-region (point) (line-end-position))
11759 ;; Deleting white spaces may break an otherwise empty headline.
11760 ;; Re-introduce one space in this case.
11761 (unless (org-at-heading-p) (insert " "))
11762 (when tags
11763 (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
11764 ;; When text is being inserted on an invisible region
11765 ;; boundary, it can be inadvertently sucked into
11766 ;; invisibility.
11767 (unless (org-invisible-p (line-beginning-position))
11768 (org-fold-region (point) (line-end-position) nil 'outline))))
11769 ;; Align tags, if any.
11770 (when tags (org-align-tags))
11771 (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
1214311772
1214411773 (defun org-change-tag-in-region (beg end tag off)
1214511774 "Add or remove TAG for each entry in the region.
1215811787 (progn
1215911788 (message "[s]et or [r]emove? ")
1216011789 (equal (read-char-exclusive) ?r))))
12161 (when (fboundp 'deactivate-mark) (deactivate-mark))
11790 (deactivate-mark)
1216211791 (let ((agendap (equal major-mode 'org-agenda-mode))
1216311792 l1 l2 m buf pos newhead (cnt 0))
1216411793 (goto-char end)
1221811847 (defun org-fast-tag-show-exit (flag)
1221911848 (save-excursion
1222011849 (org-goto-line 3)
12221 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11850 (when (re-search-forward "[ \t]+Next change exits" (line-end-position) t)
1222211851 (replace-match ""))
1222311852 (when flag
1222411853 (end-of-line 1)
1226511894 (setq ov-start (match-beginning 1)
1226611895 ov-end (match-end 1)
1226711896 ov-prefix "")
12268 (setq ov-start (1- (point-at-eol))
11897 (setq ov-start (1- (line-end-position))
1226911898 ov-end (1+ ov-start))
1227011899 (skip-chars-forward "^\n\r")
1227111900 (setq ov-prefix
1231711946 (while (equal (car tbl) '(:newline))
1231811947 (insert "\n")
1231911948 (setq tbl (cdr tbl)))))
12320 ((equal e '(:grouptags)) (insert " : "))
11949 ((equal e '(:grouptags))
11950 (delete-char -3)
11951 (insert " : "))
1232111952 (t
1232211953 (setq tg (copy-sequence (car e)) c2 nil)
1232311954 (if (cdr e)
1233011961 (while (or (rassoc char ntable) (rassoc char table))
1233111962 (setq char (1+ char)))
1233211963 (setq c2 c1))
12333 (setq c (or c2 char)))
11964 (setq c (or c2
11965 (if (> char ?~)
11966 ?\s
11967 char)))
11968 ;; Consider characters A-Z after a-z.
11969 (if (equal char ?z)
11970 (setq char ?A)))
1233411971 (when ingroup (push tg (car groups)))
1233511972 (setq tg (org-add-props tg nil 'face
1233611973 (cond
1238412021 (setq current nil)
1238512022 (when exit-after-next (setq exit-after-next 'now)))
1238612023 ((= c ?\t)
12387 (condition-case nil
12388 (unless tab-tags
12389 (setq tab-tags
12390 (delq nil
12391 (mapcar (lambda (x)
12392 (let ((item (car-safe x)))
12393 (and (stringp item)
12394 (list item))))
12395 (org--tag-add-to-alist
12396 (with-current-buffer buf
12397 (org-get-buffer-tags))
12398 table))))))
12024 (unless tab-tags
12025 (setq tab-tags
12026 (delq nil
12027 (mapcar (lambda (x)
12028 (let ((item (car-safe x)))
12029 (and (stringp item)
12030 (list item))))
12031 (org--tag-add-to-alist
12032 (with-current-buffer buf
12033 (org-get-buffer-tags))
12034 table)))))
1239912035 (setq tg (completing-read "Tag: " tab-tags))
1240012036 (when (string-match "\\S-" tg)
1240112037 (cl-pushnew (list tg) tab-tags :test #'equal)
1242412060 (when (eq exit-after-next 'now) (throw 'exit t))
1242512061 (goto-char (point-min))
1242612062 (beginning-of-line 2)
12427 (delete-region (point) (point-at-eol))
12063 (delete-region (point) (line-end-position))
1242812064 (org-fast-tag-insert "Current" current c-face)
1242912065 (org-set-current-tags-overlay current ov-prefix)
1243012066 (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
1243612072 (cond
1243712073 ((member tag current) c-face)
1243812074 ((member tag inherited) i-face)
12439 (t (get-text-property (match-beginning 1) '
12440 face))))))))
12075 (t 'default)))))))
1244112076 (goto-char (point-min)))))
1244212077 (delete-overlay org-tags-overlay)
1244312078 (if rtn
1245312088 (defun org--get-local-tags ()
1245412089 "Return list of tags for the current headline.
1245512090 Assume point is at the beginning of the headline."
12456 (and (looking-at org-tag-line-re)
12457 (split-string (match-string-no-properties 2) ":" t)))
12458
12459 (defun org-get-tags (&optional pos local)
12091 (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
12092 (cached-tags (org-element-property :tags cached)))
12093 (if cached
12094 ;; If we do not explicitly copy the result, reference would
12095 ;; be returned and cache element might be modified directly.
12096 (mapcar #'copy-sequence cached-tags)
12097 ;; Parse tags manually.
12098 (and (looking-at org-tag-line-re)
12099 (split-string (match-string-no-properties 2) ":" t)))))
12100
12101 (defun org-get-tags (&optional pos-or-element local)
1246012102 "Get the list of tags specified in the current headline.
1246112103
12462 When argument POS is non-nil, retrieve tags for headline at POS.
12104 When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
12105 POS.
1246312106
1246412107 According to `org-use-tag-inheritance', tags may be inherited
1246512108 from parent headlines, and from the whole document, through
1247212115 tags specified at the headline.
1247312116
1247412117 Inherited tags have the `inherited' text property."
12475 (if (and org-trust-scanner-tags
12476 (or (not pos) (eq pos (point)))
12477 (not local))
12478 org-scanner-tags
12479 (org-with-point-at (or pos (point))
12480 (unless (org-before-first-heading-p)
12481 (org-back-to-heading t)
12482 (let ((ltags (org--get-local-tags)) itags)
12118 (save-match-data
12119 (if (and org-trust-scanner-tags
12120 (or (not pos-or-element) (eq pos-or-element (point)))
12121 (not local))
12122 org-scanner-tags
12123 (org-with-point-at (unless (org-element-type pos-or-element)
12124 (or pos-or-element (point)))
12125 (unless (or (org-element-type pos-or-element)
12126 (org-before-first-heading-p))
12127 (org-back-to-heading t))
12128 (let ((ltags (if (org-element-type pos-or-element)
12129 (org-element-property :tags (org-element-lineage pos-or-element '(headline inlinetask) t))
12130 (org--get-local-tags)))
12131 itags)
1248312132 (if (or local (not org-use-tag-inheritance)) ltags
12484 (while (org-up-heading-safe)
12485 (setq itags (nconc (mapcar #'org-add-prop-inherited
12486 (org--get-local-tags))
12487 itags)))
12133 (let ((cached (and (org-element--cache-active-p)
12134 (if (org-element-type pos-or-element)
12135 (org-element-lineage pos-or-element '(headline org-data inlinetask) t)
12136 (org-element-at-point nil 'cached)))))
12137 (if cached
12138 (while (setq cached (org-element-property :parent cached))
12139 (setq itags (nconc (mapcar #'org-add-prop-inherited
12140 ;; If we do explicitly copy the result, reference would
12141 ;; be returned and cache element might be modified directly.
12142 (mapcar #'copy-sequence (org-element-property :tags cached)))
12143 itags)))
12144 (while (org-up-heading-safe)
12145 (setq itags (nconc (mapcar #'org-add-prop-inherited
12146 (org--get-local-tags))
12147 itags)))))
1248812148 (setq itags (append org-file-tags itags))
1248912149 (nreverse
1249012150 (delete-dups
1249212152
1249312153 (defun org-get-buffer-tags ()
1249412154 "Get a table of all tags used in the buffer, for completion."
12495 (org-with-point-at 1
12496 (let (tags)
12497 (while (re-search-forward org-tag-line-re nil t)
12498 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
12499 tags)))
12500 (mapcar #'list (delete-dups (append org-file-tags tags))))))
12155 (if (org-element--cache-active-p)
12156 ;; `org-element-cache-map' is about 2x faster compared to regexp
12157 ;; search.
12158 (let ((hashed (make-hash-table :test #'equal)))
12159 (org-element-cache-map
12160 (lambda (el)
12161 (dolist (tag (org-element-property :tags el))
12162 ;; Do not carry over the text properties. They may look
12163 ;; ugly in the completion.
12164 (puthash (list (substring-no-properties tag)) t hashed))))
12165 (dolist (tag org-file-tags) (puthash (list tag) t hashed))
12166 (hash-table-keys hashed))
12167 (org-with-point-at 1
12168 (let (tags)
12169 (while (re-search-forward org-tag-line-re nil t)
12170 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
12171 tags)))
12172 (mapcar #'list (delete-dups (append org-file-tags tags)))))))
1250112173
1250212174 ;;;; The mapping API
1250312175
1260812280
1260912281 (if (not scope)
1261012282 (progn
12611 (org-agenda-prepare-buffers
12612 (and buffer-file-name (list buffer-file-name)))
12283 ;; Agenda expects a file buffer. Skip over refreshing
12284 ;; agenda cache for non-file buffers.
12285 (when buffer-file-name
12286 (org-agenda-prepare-buffers
12287 (and buffer-file-name (list buffer-file-name))))
1261312288 (setq res
1261412289 (org-scan-tags
1261512290 func matcher org--matcher-tags-todo-only start-level)))
1261612291 ;; Get the right scope
1261712292 (cond
1261812293 ((and scope (listp scope) (symbolp (car scope)))
12619 (setq scope (eval scope)))
12294 (setq scope (eval scope t)))
1262012295 ((eq scope 'agenda)
1262112296 (setq scope (org-agenda-files t)))
1262212297 ((eq scope 'agenda-with-archives)
1265412329 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
1265512330 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
1265612331 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
12657 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12332 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS"
12333 "ORG-IMAGE-ACTUAL-WIDTH")
1265812334 "Some properties that are used by Org mode for various purposes.
1265912335 Being in this list makes sure that they are offered for completion.")
1266012336
1278312459 ;; Maybe update the effort value:
1278412460 (unless (equal current value)
1278512461 (org-entry-put nil org-effort-property value))
12786 (org-refresh-property '((effort . identity)
12787 (effort-minutes . org-duration-to-minutes))
12788 value)
12462 (unless (org-element--cache-active-p)
12463 (org-refresh-property '((effort . identity)
12464 (effort-minutes . org-duration-to-minutes))
12465 value))
1278912466 (when (equal (org-get-heading t t t t)
1279012467 (bound-and-true-p org-clock-current-task))
1279112468 (setq org-clock-effort value)
1299412671 ;; Return value.
1299512672 props)))))
1299612673
12997 (defun org--property-local-values (property literal-nil)
12998 "Return value for PROPERTY in current entry.
12674 (defun org--property-local-values (property literal-nil &optional element)
12675 "Return value for PROPERTY in current entry or ELEMENT.
1299912676 Value is a list whose car is the base value for PROPERTY and cdr
1300012677 a list of accumulated values. Return nil if neither is found in
1300112678 the entry. Also return nil when PROPERTY is set to \"nil\",
1300212679 unless LITERAL-NIL is non-nil."
13003 (let ((range (org-get-property-block)))
13004 (when range
13005 (goto-char (car range))
13006 (let* ((case-fold-search t)
13007 (end (cdr range))
13008 (value
13009 ;; Base value.
13010 (save-excursion
13011 (let ((v (and (re-search-forward
13012 (org-re-property property nil t) end t)
13013 (match-string-no-properties 3))))
13014 (list (if literal-nil v (org-not-nil v)))))))
13015 ;; Find additional values.
13016 (let* ((property+ (org-re-property (concat property "+") nil t)))
13017 (while (re-search-forward property+ end t)
13018 (push (match-string-no-properties 3) value)))
13019 ;; Return final values.
13020 (and (not (equal value '(nil))) (nreverse value))))))
12680 (let ((element (or element
12681 (and (org-element--cache-active-p)
12682 (org-element-at-point nil 'cached)))))
12683 (if element
12684 (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
12685 (base-value (org-element-property (intern (concat ":" (upcase property))) element))
12686 (base-value (if literal-nil base-value (org-not-nil base-value)))
12687 (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
12688 (extra-value (if (listp extra-value) extra-value (list extra-value)))
12689 (value (cons base-value extra-value)))
12690 (and (not (equal value '(nil))) value))
12691 (let ((range (org-get-property-block)))
12692 (when range
12693 (goto-char (car range))
12694 (let* ((case-fold-search t)
12695 (end (cdr range))
12696 (value
12697 ;; Base value.
12698 (save-excursion
12699 (let ((v (and (re-search-forward
12700 (org-re-property property nil t) end t)
12701 (match-string-no-properties 3))))
12702 (list (if literal-nil v (org-not-nil v)))))))
12703 ;; Find additional values.
12704 (let* ((property+ (org-re-property (concat property "+") nil t)))
12705 (while (re-search-forward property+ end t)
12706 (push (match-string-no-properties 3) value)))
12707 ;; Return final values.
12708 (and (not (equal value '(nil))) (nreverse value))))))))
1302112709
1302212710 (defun org--property-global-or-keyword-value (property literal-nil)
1302312711 "Return value for PROPERTY as defined by global properties or by keyword.
1305812746 (org-entry-get-with-inheritance property literal-nil))
1305912747 (t
1306012748 (let* ((local (org--property-local-values property literal-nil))
13061 (value (and local (mapconcat #'identity (delq nil local) " "))))
12749 (value (and local (mapconcat #'identity
12750 (delq nil local)
12751 (org--property-get-separator property)))))
1306212752 (if literal-nil value (org-not-nil value)))))))
1306312753
1306412754 (defun org-property-or-variable-value (var &optional inherit)
1315512845 Note that also `org-entry-get' calls this function, if the INHERIT flag
1315612846 is set.")
1315712847
13158 (defun org-entry-get-with-inheritance (property &optional literal-nil)
12848 (defun org-entry-get-with-inheritance (property &optional literal-nil element)
1315912849 "Get PROPERTY of entry or content at point, search higher levels if needed.
1316012850 The search will stop at the first ancestor which has the property defined.
1316112851 If the value found is \"nil\", return nil to show that the property
1316312853 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
1316412854 (move-marker org-entry-property-inherited-from nil)
1316512855 (org-with-wide-buffer
13166 (let (value)
12856 (let (value at-bob-no-heading)
1316712857 (catch 'exit
13168 (while t
13169 (let ((v (org--property-local-values property literal-nil)))
13170 (when v
13171 (setq value
13172 (concat (mapconcat #'identity (delq nil v) " ")
13173 (and value " ")
13174 value)))
13175 (cond
13176 ((car v)
13177 (org-back-to-heading-or-point-min t)
13178 (move-marker org-entry-property-inherited-from (point))
13179 (throw 'exit nil))
13180 ((org-up-heading-or-point-min))
13181 (t
13182 (let ((global (org--property-global-or-keyword-value property literal-nil)))
13183 (cond ((not global))
13184 (value (setq value (concat global " " value)))
13185 (t (setq value global))))
13186 (throw 'exit nil))))))
12858 (let ((element (or element
12859 (and (org-element--cache-active-p)
12860 (org-element-at-point nil 'cached))))
12861 (separator (org--property-get-separator property)))
12862 (if element
12863 (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
12864 (while t
12865 (let* ((v (org--property-local-values property literal-nil element))
12866 (v (if (listp v) v (list v))))
12867 (when v
12868 (setq value
12869 (concat (mapconcat #'identity (delq nil v) separator)
12870 (and value separator)
12871 value)))
12872 (cond
12873 ((car v)
12874 (move-marker org-entry-property-inherited-from (org-element-property :begin element))
12875 (throw 'exit nil))
12876 ((org-element-property :parent element)
12877 (setq element (org-element-property :parent element)))
12878 (t
12879 (let ((global (org--property-global-or-keyword-value property literal-nil)))
12880 (cond ((not global))
12881 (value (setq value (concat global separator value)))
12882 (t (setq value global))))
12883 (throw 'exit nil))))))
12884 (while t
12885 (let ((v (org--property-local-values property literal-nil)))
12886 (when v
12887 (setq value
12888 (concat (mapconcat #'identity (delq nil v) separator)
12889 (and value separator)
12890 value)))
12891 (cond
12892 ((car v)
12893 (org-back-to-heading-or-point-min t)
12894 (move-marker org-entry-property-inherited-from (point))
12895 (throw 'exit nil))
12896 ((or (org-up-heading-safe)
12897 (and (not (bobp))
12898 (goto-char (point-min))
12899 nil)
12900 ;; `org-up-heading-safe' returned nil. We are at low
12901 ;; level heading or bob. If there is headline
12902 ;; there, do not try to fetch its properties.
12903 (and (bobp)
12904 (not at-bob-no-heading)
12905 (not (org-at-heading-p))
12906 (setq at-bob-no-heading t))))
12907 (t
12908 (let ((global (org--property-global-or-keyword-value property literal-nil)))
12909 (cond ((not global))
12910 (value (setq value (concat global separator value)))
12911 (t (setq value global))))
12912 (throw 'exit nil))))))))
1318712913 (if literal-nil value (org-not-nil value)))))
1318812914
1318912915 (defvar org-property-changed-functions nil
1325212978 ((member property org-special-properties)
1325312979 (error "The %s property cannot be set with `org-entry-put'" property))
1325412980 (t
13255 (let* ((range (org-get-property-block beg 'force))
13256 (end (cdr range))
13257 (case-fold-search t))
13258 (goto-char (car range))
13259 (if (re-search-forward (org-re-property property nil t) end t)
13260 (progn (delete-region (match-beginning 0) (match-end 0))
13261 (goto-char (match-beginning 0)))
13262 (goto-char end)
13263 (insert "\n")
13264 (backward-char))
13265 (insert ":" property ":")
13266 (when value (insert " " value))
13267 (org-indent-line)))))
12981 (org-fold-core-ignore-modifications
12982 (let* ((range (org-get-property-block beg 'force))
12983 (end (cdr range))
12984 (case-fold-search t))
12985 (goto-char (car range))
12986 (if (re-search-forward (org-re-property property nil t) end t)
12987 (progn (delete-region (match-beginning 0) (match-end 0))
12988 (goto-char (match-beginning 0)))
12989 (goto-char end)
12990 (insert-and-inherit "\n")
12991 (backward-char))
12992 (insert-and-inherit ":" property ":")
12993 (when value (insert-and-inherit " " value))
12994 (org-indent-line))))))
1326812995 (run-hook-with-args 'org-property-changed-functions property value))))
1326912996
1327012997 (defun org-buffer-property-keys (&optional specials defaults columns)
1336613093 (org-with-limited-levels (org-back-to-heading-or-point-min t)))
1336713094 (if (org-before-first-heading-p)
1336813095 (while (and (org-at-comment-p) (bolp)) (forward-line))
13369 (progn
13370 (forward-line)
13371 (when (looking-at-p org-planning-line-re) (forward-line))))
13096 (forward-line)
13097 (when (looking-at-p org-planning-line-re) (forward-line)))
1337213098 (unless (looking-at-p org-property-drawer-re)
1337313099 ;; Make sure we start editing a line from current entry, not from
1337413100 ;; next one. It prevents extending text properties or overlays
1337813104 (inhibit-read-only t))
1337913105 (unless (bobp) (insert "\n"))
1338013106 (insert ":PROPERTIES:\n:END:")
13381 (org-flag-region (line-end-position 0) (point) t 'outline)
13107 (org-fold-region (line-end-position 0) (point) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
1338213108 (when (or (eobp) (= begin (point-min))) (insert "\n"))
1338313109 (org-indent-region begin (point))))))
1338413110
1368713413 (beginning-of-line 1)
1368813414 (skip-chars-forward " \t")
1368913415 (when (equal prop org-effort-property)
13690 (org-refresh-property
13691 '((effort . identity)
13692 (effort-minutes . org-duration-to-minutes))
13693 nval)
13416 (unless (org-element--cache-active-p)
13417 (org-refresh-property
13418 '((effort . identity)
13419 (effort-minutes . org-duration-to-minutes))
13420 nval))
1369413421 (when (string= org-clock-current-task heading)
1369513422 (setq org-clock-effort nval)
1369613423 (org-clock-update-mode-line)))
1395013677 While prompting, a calendar is popped up - you can also select the
1395113678 date with the mouse (button 1). The calendar shows a period of three
1395213679 months. To scroll it to other months, use the keys `>' and `<'.
13680 There are many other calendar navigation commands available, see
13681 Info node `(org) The date/time prompt' for a full list.
13682
1395313683 If you don't like the calendar, turn it off with
1395413684 (setq org-read-date-popup-calendar nil)
1395513685
1398513715 (when (< (nth 2 org-defdecode) org-extend-today-until)
1398613716 (setf (nth 2 org-defdecode) -1)
1398713717 (setf (nth 1 org-defdecode) 59)
13988 (setq org-def (apply #'encode-time org-defdecode))
13718 (setq org-def (org-encode-time org-defdecode))
1398913719 (setq org-defdecode (decode-time org-def)))
1399013720 (let* ((timestr (format-time-string
1399113721 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
1405813788 "range representable on this machine"))
1405913789 (ding))
1406013790
14061 (setq final (apply #'encode-time final))
13791 (setq final (org-encode-time final))
1406213792
1406313793 (setq org-read-date-final-answer ans)
1406413794
1408113811 (save-excursion
1408213812 (end-of-line 1)
1408313813 (while (not (equal (buffer-substring
14084 (max (point-min) (- (point) 4)) (point))
14085 " "))
13814 (max (point-min) (- (point) 4)) (point))
13815 " "))
1408613816 (insert " ")))
14087 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13817 (let* ((ans (concat (buffer-substring (line-beginning-position)
13818 (point-max))
1408813819 " " (or org-ans1 org-ans2)))
1408913820 (org-end-time-was-given nil)
1409013821 (f (org-read-date-analyze ans org-def org-defdecode))
14091 (fmts (if org-display-custom-times
14092 org-time-stamp-custom-formats
14093 org-time-stamp-formats))
14094 (fmt (if (or org-with-time
14095 (and (boundp 'org-time-was-given) org-time-was-given))
14096 (cdr fmts)
14097 (car fmts)))
14098 (txt (format-time-string fmt (apply #'encode-time f)))
14099 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
13822 (fmt (org-time-stamp-format
13823 (or org-with-time
13824 (and (boundp 'org-time-was-given) org-time-was-given))
13825 org-read-date-inactive
13826 org-display-custom-times))
13827 (txt (format-time-string fmt (org-encode-time f)))
1410013828 (txt (concat "=> " txt)))
1410113829 (when (and org-end-time-was-given
1410213830 (string-match org-plain-time-of-day-regexp txt))
1410613834 (when org-read-date-analyze-futurep
1410713835 (setq txt (concat txt " (=>F)")))
1410813836 (setq org-read-date-overlay
14109 (make-overlay (1- (point-at-eol)) (point-at-eol)))
13837 (make-overlay (1- (line-end-position)) (line-end-position)))
1411013838 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
1411113839
1411213840 (defun org-read-date-analyze (ans def defdecode)
1430614034 (unless deltadef
1430714035 (let ((now (decode-time)))
1430814036 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14309 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14310 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14311 ((equal deltaw "m") (setq month (+ month deltan)))
14312 ((equal deltaw "y") (setq year (+ year deltan)))))
14037 (cond ((member deltaw '("h" ""))
14038 (when (boundp 'org-time-was-given)
14039 (setq org-time-was-given t))
14040 (setq hour (+ hour deltan)))
14041 ((member deltaw '("d" "")) (setq day (+ day deltan)))
14042 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14043 ((equal deltaw "m") (setq month (+ month deltan)))
14044 ((equal deltaw "y") (setq year (+ year deltan)))))
1431314045 ((and wday (not (nth 3 tl)))
1431414046 ;; Weekday was given, but no day, so pick that day in the week
1431514047 ;; on or after the derived date.
14316 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14048 (setq wday1 (nth 6 (decode-time (org-encode-time 0 0 0 day month year))))
1431714049 (unless (equal wday wday1)
1431814050 (setq day (+ day (% (- wday wday1 -7) 7))))))
1431914051 (when (and (boundp 'org-time-was-given)
1432814060 (when (> year 2037)
1432914061 (setq year 2037 org-read-date-analyze-forced-year t)))
1433014062 (condition-case nil
14331 (ignore (encode-time second minute hour day month year))
14063 (ignore (org-encode-time second minute hour day month year))
1433214064 (error
1433314065 (setq year (nth 5 org-defdecode))
1433414066 (setq org-read-date-analyze-forced-year t))))
1433514067 (setq org-read-date-analyze-futurep futurep)
14336 (list second minute hour day month year)))
14068 (list second minute hour day month year nil -1 nil)))
1433714069
1433814070 (defvar parse-time-weekdays)
1433914071 (defun org-read-date-get-relative (s today default)
1434614078 the DEFAULT date rather than TODAY."
1434714079 (require 'parse-time)
1434814080 (when (and
14349 (string-match
14350 (concat
14351 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14352 "\\([0-9]+\\)?"
14353 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14354 "\\([ \t]\\|$\\)") s)
14081 ;; Force case-insensitive.
14082 (let ((case-fold-search t))
14083 (string-match
14084 (concat
14085 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14086 "\\([0-9]+\\)?"
14087 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14088 "\\([ \t]\\|$\\)") s))
1435514089 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
1435614090 (let* ((dir (if (> (match-end 1) (match-beginning 1))
1435714091 (string-to-char (substring (match-string 1 s) -1))
1439014124 (let ((sf (selected-frame))
1439114125 (sw (selected-window)))
1439214126 (select-window (get-buffer-window "*Calendar*" t))
14393 (eval form)
14127 (eval form t)
1439414128 (when (and (not keepdate) (calendar-cursor-to-date))
1439514129 (let* ((date (calendar-cursor-to-date))
14396 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14130 (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
1439714131 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
1439814132 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
1439914133 (select-window sw)
1440514139 (interactive)
1440614140 (when (calendar-cursor-to-date)
1440714141 (let* ((date (calendar-cursor-to-date))
14408 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14142 (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
1440914143 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
1441014144 (when (active-minibuffer-window) (exit-minibuffer))))
1441114145
1441814152 PRE and POST are optional strings to be inserted before and after the
1441914153 stamp.
1442014154 The command returns the inserted time stamp."
14421 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14422 stamp)
14423 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14424 (insert-before-markers (or pre ""))
14425 (when (listp extra)
14426 (setq extra (car extra))
14427 (if (and (stringp extra)
14428 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14429 (setq extra (format "-%02d:%02d"
14430 (string-to-number (match-string 1 extra))
14431 (string-to-number (match-string 2 extra))))
14432 (setq extra nil)))
14433 (when extra
14434 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14435 (insert-before-markers (setq stamp (format-time-string fmt time)))
14436 (insert-before-markers (or post ""))
14437 (setq org-last-inserted-timestamp stamp)))
14155 (org-fold-core-ignore-modifications
14156 (let ((fmt (org-time-stamp-format with-hm inactive))
14157 stamp)
14158 (insert-before-markers-and-inherit (or pre ""))
14159 (when (listp extra)
14160 (setq extra (car extra))
14161 (if (and (stringp extra)
14162 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14163 (setq extra (format "-%02d:%02d"
14164 (string-to-number (match-string 1 extra))
14165 (string-to-number (match-string 2 extra))))
14166 (setq extra nil)))
14167 (when extra
14168 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14169 (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
14170 (insert-before-markers-and-inherit (or post ""))
14171 (setq org-last-inserted-timestamp stamp))))
1443814172
1443914173 (defun org-toggle-time-stamp-overlays ()
1444014174 "Toggle the use of custom time stamp formats."
1446514199 (setq off (- (match-end 0) (match-beginning 0)))))
1446614200 (setq end (- end off))
1446714201 (setq with-hm (and (nth 1 t1) (nth 2 t1))
14468 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14202 tf (org-time-stamp-format with-hm 'no-brackets 'custom)
1446914203 time (org-fix-decoded-time t1)
1447014204 str (org-add-props
14471 (format-time-string
14472 (substring tf 1 -1) (apply 'encode-time time))
14205 (format-time-string tf (org-encode-time time))
1447314206 nil 'mouse-face 'highlight))
1447414207 (put-text-property beg end 'display str)))
1447514208
1452314256 (mouse-set-point ev)
1452414257 (when (calendar-cursor-to-date)
1452514258 (let* ((date (calendar-cursor-to-date))
14526 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14259 (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
1452714260 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
1452814261 (when (active-minibuffer-window) (exit-minibuffer))))
1452914262
1465614389 (org-clock-update-time-maybe)
1465714390 (save-excursion
1465814391 (unless (org-at-date-range-p t)
14659 (goto-char (point-at-bol))
14660 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14392 (goto-char (line-beginning-position))
14393 (re-search-forward org-tr-regexp-both (line-end-position) t))
1466114394 (unless (org-at-date-range-p t)
1466214395 (user-error "Not at a time-stamp range, and none found in current line")))
1466314396 (let* ((ts1 (match-string 1))
1472414457
1472514458 (defun org-time-string-to-time (s)
1472614459 "Convert timestamp string S into internal time."
14727 (apply #'encode-time (org-parse-time-string s)))
14460 (org-encode-time (org-parse-time-string s)))
1472814461
1472914462 (defun org-time-string-to-seconds (s)
1473014463 "Convert a timestamp string S into a number of seconds."
1473114464 (float-time (org-time-string-to-time s)))
1473214465
14733 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
14466 (define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
1473414467
1473514468 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
1473614469 "Convert time stamp S to an absolute day number.
1478714520 "Return the time corresponding to date D.
1478814521 D may be an absolute day number, or a calendar-type list (month day year)."
1478914522 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14790 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14523 (org-encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
1479114524
1479214525 (defvar org-agenda-current-date)
1479314526 (defun org-calendar-holiday ()
1479614529 (let ((hl (calendar-check-holidays org-agenda-current-date)))
1479714530 (and hl (mapconcat #'identity hl "; "))))
1479814531
14532 (defvar org--diary-sexp-entry-cache (make-hash-table :test #'equal)
14533 "Hash table holding return values of `org-diary-sexp-entry'.")
1479914534 (defun org-diary-sexp-entry (sexp entry d)
1480014535 "Process a SEXP diary ENTRY for date D."
1480114536 (require 'diary-lib)
1480214537 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
1480314538 ;; dynamically.
14804 (let* ((sexp `(let ((entry ,entry)
14805 (date ',d))
14806 ,(car (read-from-string sexp))))
14807 (result (if calendar-debug-sexp (eval sexp)
14808 (condition-case nil
14809 (eval sexp)
14810 (error
14811 (beep)
14812 (message "Bad sexp at line %d in %s: %s"
14813 (org-current-line)
14814 (buffer-file-name) sexp)
14815 (sleep-for 2))))))
14816 (cond ((stringp result) (split-string result "; "))
14817 ((and (consp result)
14818 (not (consp (cdr result)))
14819 (stringp (cdr result))) (cdr result))
14820 ((and (consp result)
14821 (stringp (car result))) result)
14822 (result entry))))
14539 (let ((cached (gethash (list sexp entry d) org--diary-sexp-entry-cache 'none)))
14540 (if (not (eq 'none cached)) cached
14541 (puthash (list sexp entry d)
14542 (let* ((sexp `(let ((entry ,entry)
14543 (date ',d))
14544 ,(car (read-from-string sexp))))
14545 ;; FIXME: Do not use (eval ... t) in the following sexp as
14546 ;; diary vars are still using dynamic scope.
14547 (result (if calendar-debug-sexp (eval sexp)
14548 (condition-case nil
14549 (eval sexp)
14550 (error
14551 (beep)
14552 (message "Bad sexp at line %d in %s: %s"
14553 (org-current-line)
14554 (buffer-file-name) sexp)
14555 (sleep-for 2))))))
14556 (cond ((stringp result) (split-string result "; "))
14557 ((and (consp result)
14558 (not (consp (cdr result)))
14559 (stringp (cdr result)))
14560 (cdr result))
14561 ((and (consp result)
14562 (stringp (car result)))
14563 result)
14564 (result entry)))
14565 org--diary-sexp-entry-cache))))
1482314566
1482414567 (defun org-diary-to-ical-string (frombuf)
1482514568 "Get iCalendar entries from diary entries in buffer FROMBUF.
1501014753 When at a timestamp, return the position of the point as a symbol
1501114754 among `bracket', `after', `year', `month', `hour', `minute',
1501214755 `day' or a number of character from the last know part of the
15013 time stamp.
14756 time stamp. If diary sexp timestamps, any point inside the timestamp
14757 is considered `day' (i.e. only `bracket', `day', and `after' return
14758 values are possible).
1501414759
1501514760 When matching, the match groups are the following:
15016 group 1: year
15017 group 2: month
15018 group 3: day number
15019 group 4: day name
14761 group 1: year, if any
14762 group 2: month, if any
14763 group 3: day number, if any
14764 group 4: day name, if any
1502014765 group 5: hours, if any
1502114766 group 6: minutes, if any"
15022 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
14767 (let* ((regexp
14768 (if extended
14769 (if (eq extended 'agenda)
14770 (rx-to-string
14771 `(or (regexp ,org-ts-regexp3)
14772 (regexp ,org-element--timestamp-regexp)))
14773 org-ts-regexp3)
14774 org-ts-regexp2))
1502314775 (pos (point))
1502414776 (match?
1502514777 (let ((boundaries (org-in-regexp regexp)))
1505014802 ((org-pos-in-match-range pos 8) 'minute)
1505114803 ((or (org-pos-in-match-range pos 4)
1505214804 (org-pos-in-match-range pos 5)) 'day)
15053 ((and (> pos (or (match-end 8) (match-end 5)))
14805 ((and (or (match-end 8) (match-end 5))
14806 (> pos (or (match-end 8) (match-end 5)))
1505414807 (< pos (match-end 0)))
1505514808 (- pos (or (match-end 8) (match-end 5))))
1505614809 (t 'day))))
1512914882 (setcar (cdr time0) (+ (nth 1 time0)
1513014883 (if (> n 0) (- rem) (- dm rem))))))
1513114884 (setq time
15132 (apply #'encode-time
15133 (or (car time0) 0)
15134 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
15135 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
15136 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
15137 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
15138 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
15139 (nthcdr 6 time0)))
14885 (org-encode-time
14886 (apply #'list
14887 (or (car time0) 0)
14888 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
14889 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
14890 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
14891 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
14892 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
14893 (nthcdr 6 time0))))
1514014894 (when (and (memq timestamp? '(hour minute))
1514114895 extra
1514214896 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
1515414908 (setcar time0 (or (car time0) 0))
1515514909 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
1515614910 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15157 (setq time (apply 'encode-time time0))))
14911 (setq time (org-encode-time time0))))
1515814912 ;; Insert the new time-stamp, and ensure point stays in the same
1515914913 ;; category as before (i.e. not after the last position in that
1516014914 ;; category).
1520814962 (message "No clock to adjust")
1520914963 (save-excursion
1521014964 (org-goto-marker-or-bmk clfixpos)
15211 (org-show-subtree)
14965 (org-fold-show-subtree)
1521214966 (when (re-search-forward clrgx nil t)
1521314967 (goto-char (match-beginning 1))
1521414968 (let (org-clock-adjust-closest)
1530015054 (org-timestamp-change 0 'calendar)
1530115055 (let ((cal-date (org-get-date-from-calendar)))
1530215056 (org-insert-time-stamp
15303 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15057 (org-encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
1530415058
1530515059 (defcustom org-image-actual-width t
1530615060 "When non-nil, use the actual width of images when inlining them.
1541015164 (completing-read "Org buffer: "
1541115165 (mapcar #'list (mapcar #'buffer-name blist))
1541215166 nil t))))
15413
15414 (defun org-buffer-list (&optional predicate exclude-tmp)
15415 "Return a list of Org buffers.
15416 PREDICATE can be `export', `files' or `agenda'.
15417
15418 export restrict the list to Export buffers.
15419 files restrict the list to buffers visiting Org files.
15420 agenda restrict the list to buffers visiting agenda files.
15421
15422 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15423 (let* ((bfn nil)
15424 (agenda-files (and (eq predicate 'agenda)
15425 (mapcar 'file-truename (org-agenda-files t))))
15426 (filter
15427 (cond
15428 ((eq predicate 'files)
15429 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
15430 ((eq predicate 'export)
15431 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
15432 ((eq predicate 'agenda)
15433 (lambda (b)
15434 (with-current-buffer b
15435 (and (derived-mode-p 'org-mode)
15436 (setq bfn (buffer-file-name b))
15437 (member (file-truename bfn) agenda-files)))))
15438 (t (lambda (b) (with-current-buffer b
15439 (or (derived-mode-p 'org-mode)
15440 (string-match "\\*Org .*Export"
15441 (buffer-name b)))))))))
15442 (delq nil
15443 (mapcar
15444 (lambda(b)
15445 (if (and (funcall filter b)
15446 (or (not exclude-tmp)
15447 (not (string-match "tmp" (buffer-name b)))))
15448 b
15449 nil))
15450 (buffer-list)))))
1545115167
1545215168 (defun org-agenda-files (&optional unrestricted archives)
1545315169 "Get the list of agenda files.
1565815374 (defun org-agenda-prepare-buffers (files)
1565915375 "Create buffers for all agenda files, protect archived trees and comments."
1566015376 (interactive)
15661 (let ((pa '(:org-archived t))
15662 (pc '(:org-comment t))
15663 (pall '(:org-archived t :org-comment t))
15664 (inhibit-read-only t)
15377 (let ((inhibit-read-only t)
1566515378 (org-inhibit-startup org-agenda-inhibit-startup)
15666 (rea (org-make-tag-string (list org-archive-tag)))
15667 re pos)
15379 ;; Do not refresh list of agenda files in the menu when
15380 ;; opening every new file.
15381 (org-agenda-file-menu-enabled nil))
1566815382 (setq org-tag-alist-for-agenda nil
1566915383 org-tag-groups-alist-for-agenda nil)
15670 (save-excursion
15671 (save-restriction
15672 (dolist (file files)
15673 (catch 'nextfile
15674 (if (bufferp file)
15675 (set-buffer file)
15676 (org-check-agenda-file file)
15677 (set-buffer (org-get-agenda-file-buffer file)))
15678 (widen)
15679 (org-set-regexps-and-options 'tags-only)
15680 (setq pos (point))
15681 (or (memq 'category org-agenda-ignore-properties)
15682 (org-refresh-category-properties))
15683 (or (memq 'stats org-agenda-ignore-properties)
15684 (org-refresh-stats-properties))
15685 (or (memq 'effort org-agenda-ignore-properties)
15686 (org-refresh-effort-properties))
15687 (or (memq 'appt org-agenda-ignore-properties)
15688 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
15689 (setq org-todo-keywords-for-agenda
15690 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15691 (setq org-done-keywords-for-agenda
15692 (append org-done-keywords-for-agenda org-done-keywords))
15693 (setq org-todo-keyword-alist-for-agenda
15694 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15695 (setq org-tag-alist-for-agenda
15696 (org--tag-add-to-alist
15697 org-tag-alist-for-agenda
15698 org-current-tag-alist))
15699 ;; Merge current file's tag groups into global
15700 ;; `org-tag-groups-alist-for-agenda'.
15701 (when org-group-tags
15702 (dolist (alist org-tag-groups-alist)
15703 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
15704 (if old
15705 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
15706 (push alist org-tag-groups-alist-for-agenda)))))
15707 (with-silent-modifications
15708 (save-excursion
15709 (remove-text-properties (point-min) (point-max) pall)
15710 (when org-agenda-skip-archived-trees
15711 (goto-char (point-min))
15712 (while (re-search-forward rea nil t)
15713 (when (org-at-heading-p t)
15714 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15715 (goto-char (point-min))
15716 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
15717 (while (re-search-forward re nil t)
15718 (when (save-match-data (org-in-commented-heading-p t))
15719 (add-text-properties
15720 (match-beginning 0) (org-end-of-subtree t) pc)))))
15721 (goto-char pos)))))
15722 (setq org-todo-keywords-for-agenda
15723 (org-uniquify org-todo-keywords-for-agenda))
15724 (setq org-todo-keyword-alist-for-agenda
15725 (org-uniquify org-todo-keyword-alist-for-agenda))))
15384 (dolist (file files)
15385 (catch 'nextfile
15386 (with-current-buffer
15387 (if (bufferp file)
15388 file
15389 (org-check-agenda-file file)
15390 (org-get-agenda-file-buffer file))
15391 (org-with-wide-buffer
15392 (org-set-regexps-and-options 'tags-only)
15393 (or (memq 'category org-agenda-ignore-properties)
15394 (org-refresh-category-properties))
15395 (or (memq 'stats org-agenda-ignore-properties)
15396 (org-refresh-stats-properties))
15397 (or (memq 'effort org-agenda-ignore-properties)
15398 (unless org-element-use-cache
15399 (org-refresh-effort-properties)))
15400 (or (memq 'appt org-agenda-ignore-properties)
15401 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
15402 (dolist (el org-todo-keywords-1)
15403 (unless (member el org-todo-keywords-for-agenda)
15404 (push el org-todo-keywords-for-agenda)))
15405 (dolist (el org-done-keywords)
15406 (unless (member el org-done-keywords-for-agenda)
15407 (push el org-done-keywords-for-agenda)))
15408 (setq org-todo-keyword-alist-for-agenda
15409 (org--tag-add-to-alist
15410 org-todo-key-alist
15411 org-todo-keyword-alist-for-agenda))
15412 (setq org-tag-alist-for-agenda
15413 (org--tag-add-to-alist
15414 org-current-tag-alist
15415 org-tag-alist-for-agenda))
15416 ;; Merge current file's tag groups into global
15417 ;; `org-tag-groups-alist-for-agenda'.
15418 (when org-group-tags
15419 (dolist (alist org-tag-groups-alist)
15420 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
15421 (if old
15422 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
15423 (push alist org-tag-groups-alist-for-agenda)))))))))
15424 ;; Refresh the menu once after loading all the agenda buffers.
15425 (when org-agenda-file-menu-enabled
15426 (org-install-agenda-files-menu))))
1572615427
1572715428
1572815429 ;;;; CDLaTeX minor mode
1575115452 (cdlatex-compute-tables))
1575215453 (unless org-cdlatex-texmathp-advice-is-done
1575315454 (setq org-cdlatex-texmathp-advice-is-done t)
15754 (defadvice texmathp (around org-math-always-on activate)
15755 "Always return t in Org buffers.
15455 (advice-add 'texmathp :around #'org--math-always-on)))
15456
15457 (defun org--math-always-on (orig-fun &rest args)
15458 "Always return t in Org buffers.
1575615459 This is because we want to insert math symbols without dollars even outside
1575715460 the LaTeX math segments. If Org mode thinks that point is actually inside
1575815461 an embedded LaTeX fragment, let `texmathp' do its job.
1575915462 `\\[org-cdlatex-mode-map]'"
15760 (interactive)
15761 (let (p)
15762 (cond
15763 ((not (derived-mode-p 'org-mode)) ad-do-it)
15764 ((eq this-command 'cdlatex-math-symbol)
15765 (setq ad-return-value t
15766 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15767 (t
15768 (let ((p (org-inside-LaTeX-fragment-p)))
15769 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15770 (setq ad-return-value t
15771 texmathp-why '("Org mode embedded math" . 0))
15772 (when p ad-do-it)))))))))
15463 (interactive)
15464 (cond
15465 ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
15466 ((eq this-command 'cdlatex-math-symbol)
15467 (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
15468 t)
15469 (t
15470 (let ((p (org-inside-LaTeX-fragment-p)))
15471 (when p ;; FIXME: Shouldn't we return t when `p' is nil?
15472 (if (member (car p)
15473 (plist-get org-format-latex-options :matchers))
15474 (progn
15475 (setq texmathp-why '("Org mode embedded math" . 0))
15476 t)
15477 (apply orig-fun args)))))))
1577315478
1577415479 (defun turn-on-org-cdlatex ()
1577515480 "Unconditionally turn on `org-cdlatex-mode'."
1597215677 If the cursor is on a LaTeX fragment, create the image and
1597315678 overlay it over the source code, if there is none. Remove it
1597415679 otherwise. If there is no fragment at point, display images for
15975 all fragments in the current section.
15680 all fragments in the current section. With an active region,
15681 display images for all fragments in the region.
1597615682
1597715683 With a `\\[universal-argument]' prefix argument ARG, clear images \
1597815684 for all fragments
1600015706 ;; Clear current section.
1600115707 ((equal arg '(4))
1600215708 (org-clear-latex-preview
16003 (if (org-before-first-heading-p) (point-min)
16004 (save-excursion
16005 (org-with-limited-levels (org-back-to-heading t) (point))))
16006 (org-with-limited-levels (org-entry-end-position))))
15709 (if (use-region-p)
15710 (region-beginning)
15711 (if (org-before-first-heading-p) (point-min)
15712 (save-excursion
15713 (org-with-limited-levels (org-back-to-heading t) (point)))))
15714 (if (use-region-p)
15715 (region-end)
15716 (org-with-limited-levels (org-entry-end-position)))))
15717 ((use-region-p)
15718 (message "Creating LaTeX previews in region...")
15719 (org--latex-preview-region (region-beginning) (region-end))
15720 (message "Creating LaTeX previews in region... done."))
1600715721 ;; Toggle preview on LaTeX code at point.
1600815722 ((let ((datum (org-element-context)))
1600915723 (and (memq (org-element-type datum) '(latex-environment latex-fragment))
1630416018 org-format-latex-header
1630516019 'snippet)))
1630616020 (latex-compiler (plist-get processing-info :latex-compiler))
16307 (image-converter (plist-get processing-info :image-converter))
1630816021 (tmpdir temporary-file-directory)
1630916022 (texfilebase (make-temp-name
1631016023 (expand-file-name "orgtex" tmpdir)))
1631316026 '(1.0 . 1.0)))
1631416027 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
1631516028 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
16316 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
16029 (dpi (* scale (if (and buffer (display-graphic-p)) (org--get-display-dpi) 140.0)))
1631716030 (fg (or (plist-get options (if buffer :foreground :html-foreground))
1631816031 "Black"))
1631916032 (bg (or (plist-get options (if buffer :background :html-background))
1632016033 "Transparent"))
16321 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
16034 (image-converter
16035 (or (and (string= bg "Transparent")
16036 (plist-get processing-info :transparent-image-converter))
16037 (plist-get processing-info :image-converter)))
16038 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
1632216039 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
1632316040 (dolist (program programs)
1632416041 (org-check-external-command program error-message))
1644916166 ;; Image display
1645016167
1645116168 (defvar-local org-inline-image-overlays nil)
16452
16453 (defun org-toggle-inline-images (&optional include-linked)
16169 ;; Preserve when switching modes or when restarting Org.
16170 ;; If we clear the overlay list and later enable Or mode, the existing
16171 ;; image overlays will never be cleared by `org-toggle-inline-images'.
16172 (put 'org-inline-image-overlays 'permanent-local t)
16173
16174 (defun org--inline-image-overlays (&optional beg end)
16175 "Return image overlays between BEG and END."
16176 (let* ((beg (or beg (point-min)))
16177 (end (or end (point-max)))
16178 (overlays (overlays-in beg end))
16179 result)
16180 (dolist (ov overlays result)
16181 (when (memq ov org-inline-image-overlays)
16182 (push ov result)))))
16183
16184 (defun org-toggle-inline-images (&optional include-linked beg end)
1645416185 "Toggle the display of inline images.
1645516186 INCLUDE-LINKED is passed to `org-display-inline-images'."
1645616187 (interactive "P")
16457 (if org-inline-image-overlays
16188 (if (org--inline-image-overlays beg end)
1645816189 (progn
16459 (org-remove-inline-images)
16460 (when (called-interactively-p 'interactive)
16190 (org-remove-inline-images beg end)
16191 (when (called-interactively-p 'interactive)
1646116192 (message "Inline image display turned off")))
16462 (org-display-inline-images include-linked)
16193 (org-display-inline-images include-linked nil beg end)
1646316194 (when (called-interactively-p 'interactive)
16464 (message (if org-inline-image-overlays
16465 (format "%d images displayed inline"
16466 (length org-inline-image-overlays))
16467 "No images to display inline")))))
16195 (let ((new (org--inline-image-overlays beg end)))
16196 (message (if new
16197 (format "%d images displayed inline"
16198 (length new))
16199 "No images to display inline"))))))
1646816200
1646916201 (defun org-redisplay-inline-images ()
1647016202 "Assure display of inline images and refresh them."
1647416206 (org-toggle-inline-images)))
1647516207
1647616208 ;; For without-x builds.
16477 (declare-function image-refresh "image" (spec &optional frame))
16209 (declare-function image-flush "image" (spec &optional frame))
1647816210
1647916211 (defcustom org-display-remote-inline-images 'skip
1648016212 "How to display remote inline images.
1651916251 width
1652016252 'imagemagick)
1652116253 remote?
16522 :width width))))
16254 :width width :scale 1))))
1652316255
1652416256 (defun org-display-inline-images (&optional include-linked refresh beg end)
1652516257 "Display inline images.
1653216264
1653316265 2. Its description consists in a single link of the previous
1653416266 type. In this case, that link must be a well-formed plain
16535 or angle link, i.e., it must have an explicit \"file\" type.
16267 or angle link, i.e., it must have an explicit \"file\" or
16268 \"attachment\" type.
1653616269
1653716270 Equip each image with the key-map `image-map'.
1653816271
1654916282 buffer boundaries with possible narrowing."
1655016283 (interactive "P")
1655116284 (when (display-graphic-p)
16552 (unless refresh
16553 (org-remove-inline-images)
16285 (when refresh
16286 (org-remove-inline-images beg end)
1655416287 (when (fboundp 'clear-image-cache) (clear-image-cache)))
1655516288 (let ((end (or end (point-max))))
1655616289 (org-with-point-at (or beg (point-min))
1656316296 ;; "file:" links. Also check link abbreviations since
1656416297 ;; some might expand to "file" links.
1656516298 (file-types-re
16566 (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
16299 (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?\\(?:file\\|attachment\\):\\)"
1656716300 (if (not link-abbrevs) ""
1656816301 (concat "\\|" (regexp-opt link-abbrevs))))))
1656916302 (while (re-search-forward file-types-re end t)
1660216335 ;; description.
1660316336 (= (org-element-property :contents-end link)
1660416337 (match-end 0))
16605 (match-string 2)))))))
16338 (progn
16339 (setq linktype (match-string 1))
16340 (match-string 2))))))))
1660616341 (when (and path (string-match-p file-extension-re path))
1660716342 (let ((file (if (equal "attachment" linktype)
1660816343 (progn
1661516350 (org-element-property :begin link)
1661616351 'org-image-overlay)))
1661716352 (if (and (car-safe old) refresh)
16618 (image-refresh (overlay-get (cdr old) 'display))
16353 (image-flush (overlay-get (cdr old) 'display))
1661916354 (let ((image (org--create-inline-image file width)))
1662016355 (when image
1662116356 (let ((ov (make-overlay
1662516360 (org-element-property :end link))
1662616361 (skip-chars-backward " \t")
1662716362 (point)))))
16363 ;; FIXME: See bug#59902. We cannot rely
16364 ;; on Emacs to update image if the file
16365 ;; has changed.
16366 (image-flush image)
1662816367 (overlay-put ov 'display image)
1662916368 (overlay-put ov 'face 'default)
1663016369 (overlay-put ov 'org-image-overlay t)
1664816387 If the value is a float between 0 and 2, it interpreted as that proportion
1664916388 of the text width in the buffer."
1665016389 ;; Apply `org-image-actual-width' specifications.
16651 (cond
16652 ((eq org-image-actual-width t) nil)
16653 ((listp org-image-actual-width)
16654 (let* ((case-fold-search t)
16655 (par (org-element-lineage link '(paragraph)))
16656 (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
16657 (par-end (org-element-property :post-affiliated par))
16658 ;; Try to find an attribute providing a :width.
16659 (attr-width
16660 (when (and par (org-with-point-at
16661 (org-element-property :begin par)
16662 (re-search-forward attr-re par-end t)))
16663 (match-string 1)))
16664 (attr-width-val
16665 (cond
16666 ((null attr-width) nil)
16667 ((string-match-p "\\`[0-9.]+%" attr-width)
16668 (/ (string-to-number attr-width) 100.0))
16669 (t (string-to-number attr-width))))
16670 ;; Fallback to `org-image-actual-width' if no explicit width is given.
16671 (width (or attr-width-val (car org-image-actual-width))))
16672 (if (and (floatp width) (<= 0.0 width 2.0))
16673 ;; A float in [0,2] should be interpereted as this portion of
16674 ;; the text width in the window. This works well with cases like
16675 ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
16676 ;; as the "0.X" is pulled out as a float. We use 2 as the upper
16677 ;; bound as cases such as 1.2\linewidth are feasible.
16678 (round (* width
16679 (window-pixel-width)
16680 (/ (or (and (bound-and-true-p visual-fill-column-mode)
16681 (or visual-fill-column-width auto-fill-function))
16682 (when auto-fill-function fill-column)
16683 (window-text-width))
16684 (float (window-total-width)))))
16685 width)))
16686 ((numberp org-image-actual-width)
16687 org-image-actual-width)
16688 (t nil)))
16390 ;; Support subtree-level property "ORG-IMAGE-ACTUAL-WIDTH" specified
16391 ;; width.
16392 (let ((org-image-actual-width (org-property-or-variable-value 'org-image-actual-width)))
16393 (cond
16394 ((eq org-image-actual-width t) nil)
16395 ((listp org-image-actual-width)
16396 (let* ((case-fold-search t)
16397 (par (org-element-lineage link '(paragraph)))
16398 (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
16399 (par-end (org-element-property :post-affiliated par))
16400 ;; Try to find an attribute providing a :width.
16401 (attr-width
16402 (when (and par (org-with-point-at
16403 (org-element-property :begin par)
16404 (re-search-forward attr-re par-end t)))
16405 (match-string 1)))
16406 (width
16407 (cond
16408 ;; Treat :width t as if `org-image-actual-width' were t.
16409 ((string= attr-width "t") nil)
16410 ;; Fallback to `org-image-actual-width' if no interprable width is given.
16411 ((or (null attr-width)
16412 (string-match-p "\\`[^0-9]" attr-width))
16413 (car org-image-actual-width))
16414 ;; Convert numeric widths to numbers, converting percentages.
16415 ((string-match-p "\\`[0-9.]+%" attr-width)
16416 (/ (string-to-number attr-width) 100.0))
16417 (t (string-to-number attr-width)))))
16418 (if (and (floatp width) (<= 0.0 width 2.0))
16419 ;; A float in [0,2] should be interpereted as this portion of
16420 ;; the text width in the window. This works well with cases like
16421 ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
16422 ;; as the "0.X" is pulled out as a float. We use 2 as the upper
16423 ;; bound as cases such as 1.2\linewidth are feasible.
16424 (round (* width
16425 (window-pixel-width)
16426 (/ (or (and (bound-and-true-p visual-fill-column-mode)
16427 (or visual-fill-column-width auto-fill-function))
16428 (when auto-fill-function fill-column)
16429 (- (window-text-width) (line-number-display-width)))
16430 (float (window-total-width)))))
16431 width)))
16432 ((numberp org-image-actual-width)
16433 org-image-actual-width)
16434 (t nil))))
1668916435
1669016436 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
1669116437 "Remove inline-display overlay if a corresponding region is modified."
16692 (let ((inhibit-modification-hooks t))
16693 (when (and ov after)
16694 (delete ov org-inline-image-overlays)
16695 (delete-overlay ov))))
16696
16697 (defun org-remove-inline-images ()
16438 (when (and ov after)
16439 (delete ov org-inline-image-overlays)
16440 ;; Clear image from cache to avoid image not updating upon
16441 ;; changing on disk. See Emacs bug#59902.
16442 (when (overlay-get ov 'org-image-overlay)
16443 (image-flush (overlay-get ov 'display)))
16444 (delete-overlay ov)))
16445
16446 (defun org-remove-inline-images (&optional beg end)
1669816447 "Remove inline display of images."
1669916448 (interactive)
16700 (mapc #'delete-overlay org-inline-image-overlays)
16701 (setq org-inline-image-overlays nil))
16449 (let* ((beg (or beg (point-min)))
16450 (end (or end (point-max)))
16451 (overlays (overlays-in beg end)))
16452 (dolist (ov overlays)
16453 (when (memq ov org-inline-image-overlays)
16454 (setq org-inline-image-overlays (delq ov org-inline-image-overlays))
16455 (delete-overlay ov)))
16456 ;; Clear removed overlays.
16457 (dolist (ov org-inline-image-overlays)
16458 (unless (overlay-buffer ov)
16459 (setq org-inline-image-overlays (delq ov org-inline-image-overlays))))))
1670216460
1670316461 (defvar org-self-insert-command-undo-counter 0)
1670416462 (defvar org-speed-command nil)
16463
16464 (defun org-fix-tags-on-the-fly ()
16465 "Align tags in headline at point.
16466 Unlike `org-align-tags', this function does nothing if point is
16467 either not currently on a tagged headline or on a tag."
16468 (when (and (org-match-line org-tag-line-re)
16469 (< (point) (match-beginning 1)))
16470 (org-align-tags)))
1670516471
1670616472 (defun org-self-insert-command (N)
1670716473 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
1670816474 If the cursor is in a table looking at whitespace, the whitespace is
1670916475 overwritten, and the table is not marked as requiring realignment."
1671016476 (interactive "p")
16711 (org-check-before-invisible-edit 'insert)
16477 (org-fold-check-before-invisible-edit 'insert)
1671216478 (cond
1671316479 ((and org-use-speed-commands
1671416480 (let ((kv (this-command-keys-vector)))
1672216488 (call-interactively org-speed-command))
1672316489 ((functionp org-speed-command)
1672416490 (funcall org-speed-command))
16725 ((and org-speed-command (listp org-speed-command))
16726 (eval org-speed-command))
16491 ((consp org-speed-command)
16492 (eval org-speed-command t))
1672716493 (t (let (org-use-speed-commands)
1672816494 (call-interactively 'org-self-insert-command)))))
1672916495 ((and
1677016536 (setq org-self-insert-command-undo-counter
1677116537 (1+ org-self-insert-command-undo-counter))))))))
1677216538
16773 (defun org-check-before-invisible-edit (kind)
16774 "Check if editing kind KIND would be dangerous with invisible text around.
16775 The detailed reaction depends on the user option `org-catch-invisible-edits'."
16776 ;; First, try to get out of here as quickly as possible, to reduce overhead
16777 (when (and org-catch-invisible-edits
16778 (or (not (boundp 'visible-mode)) (not visible-mode))
16779 (or (get-char-property (point) 'invisible)
16780 (get-char-property (max (point-min) (1- (point))) 'invisible)))
16781 ;; OK, we need to take a closer look. Do not consider
16782 ;; invisibility obtained through text properties (e.g., link
16783 ;; fontification), as it cannot be toggled.
16784 (let* ((invisible-at-point
16785 (pcase (get-char-property-and-overlay (point) 'invisible)
16786 (`(,_ . ,(and (pred overlayp) o)) o)))
16787 ;; Assume that point cannot land in the middle of an
16788 ;; overlay, or between two overlays.
16789 (invisible-before-point
16790 (and (not invisible-at-point)
16791 (not (bobp))
16792 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
16793 (`(,_ . ,(and (pred overlayp) o)) o))))
16794 (border-and-ok-direction
16795 (or
16796 ;; Check if we are acting predictably before invisible
16797 ;; text.
16798 (and invisible-at-point
16799 (memq kind '(insert delete-backward)))
16800 ;; Check if we are acting predictably after invisible text
16801 ;; This works not well, and I have turned it off. It seems
16802 ;; better to always show and stop after invisible text.
16803 ;; (and (not invisible-at-point) invisible-before-point
16804 ;; (memq kind '(insert delete)))
16805 )))
16806 (when (or invisible-at-point invisible-before-point)
16807 (when (eq org-catch-invisible-edits 'error)
16808 (user-error "Editing in invisible areas is prohibited, make them visible first"))
16809 (if (and org-custom-properties-overlays
16810 (y-or-n-p "Display invisible properties in this buffer? "))
16811 (org-toggle-custom-properties-visibility)
16812 ;; Make the area visible
16813 (save-excursion
16814 (when invisible-before-point
16815 (goto-char
16816 (previous-single-char-property-change (point) 'invisible)))
16817 ;; Remove whatever overlay is currently making yet-to-be
16818 ;; edited text invisible. Also remove nested invisibility
16819 ;; related overlays.
16820 (delete-overlay (or invisible-at-point invisible-before-point))
16821 (let ((origin (if invisible-at-point (point) (1- (point)))))
16822 (while (pcase (get-char-property-and-overlay origin 'invisible)
16823 (`(,_ . ,(and (pred overlayp) o))
16824 (delete-overlay o)
16825 t)))))
16826 (cond
16827 ((eq org-catch-invisible-edits 'show)
16828 ;; That's it, we do the edit after showing
16829 (message
16830 "Unfolding invisible region around point before editing")
16831 (sit-for 1))
16832 ((and (eq org-catch-invisible-edits 'smart)
16833 border-and-ok-direction)
16834 (message "Unfolding invisible region around point before editing"))
16835 (t
16836 ;; Don't do the edit, make the user repeat it in full visibility
16837 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
16838
16839 (defun org-fix-tags-on-the-fly ()
16840 "Align tags in headline at point.
16841 Unlike `org-align-tags', this function does nothing if point is
16842 either not currently on a tagged headline or on a tag."
16843 (when (and (org-match-line org-tag-line-re)
16844 (< (point) (match-beginning 1)))
16845 (org-align-tags)))
16846
1684716539 (defun org-delete-backward-char (N)
1684816540 "Like `delete-backward-char', insert whitespace at field end in tables.
1684916541 When deleting backwards, in tables this function will insert whitespace in
1685216544 because, in this case the deletion might narrow the column."
1685316545 (interactive "p")
1685416546 (save-match-data
16855 (org-check-before-invisible-edit 'delete-backward)
16547 (org-fold-check-before-invisible-edit 'delete-backward)
1685616548 (if (and (= N 1)
1685716549 (not overwrite-mode)
1685816550 (not (org-region-active-p))
1686116553 (looking-at-p ".*?|")
1686216554 (org-at-table-p))
1686316555 (progn (forward-char -1) (org-delete-char 1))
16864 (backward-delete-char N)
16556 (funcall-interactively #'backward-delete-char N)
1686516557 (org-fix-tags-on-the-fly))))
1686616558
1686716559 (defun org-delete-char (N)
1687216564 because, in this case the deletion might narrow the column."
1687316565 (interactive "p")
1687416566 (save-match-data
16875 (org-check-before-invisible-edit 'delete)
16567 (org-fold-check-before-invisible-edit 'delete)
1687616568 (cond
1687716569 ((or (/= N 1)
1687816570 (eq (char-after) ?|)
1695416646 must check if the context is appropriate for it to act. If yes,
1695516647 it should do its thing and then return a non-nil value. If the
1695616648 context is wrong, just do nothing and return nil.")
16957
16958 (defvar org-tab-first-hook nil
16959 "Hook for functions to attach themselves to TAB.
16960 See `org-ctrl-c-ctrl-c-hook' for more information.
16961 This hook runs as the first action when TAB is pressed, even before
16962 `org-cycle' messes around with the `outline-regexp' to cater for
16963 inline tasks and plain list item folding.
16964 If any function in this hook returns t, any other actions that
16965 would have been caused by TAB (such as table field motion or visibility
16966 cycling) will not occur.")
1696716649
1696816650 (defvar org-tab-after-check-for-table-hook nil
1696916651 "Hook for functions to attach themselves to TAB.
1706816750 ((integerp arg)
1706916751 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
1707016752 (message "Content view to level: %d" arg)
17071 (org-content (prefix-numeric-value arg2))
16753 (org-cycle-content (prefix-numeric-value arg2))
1707216754 (org-cycle-show-empty-lines t)
1707316755 (setq org-cycle-global-status 'overview)
1707416756 (run-hook-with-args 'org-cycle-hook 'overview)))
17075 (t (call-interactively 'org-global-cycle))))
16757 (t (call-interactively 'org-cycle-global))))
1707616758
1707716759 (defun org-shiftmetaleft ()
1707816760 "Promote subtree or delete table column.
1708116763 individual commands for more information."
1708216764 (interactive)
1708316765 (cond
16766 ((and (eq system-type 'darwin)
16767 (or (eq org-support-shift-select 'always)
16768 (and org-support-shift-select (org-region-active-p))))
16769 (org-call-for-shift-select 'backward-char))
1708416770 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
1708516771 ((org-at-table-p) (call-interactively 'org-table-delete-column))
1708616772 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
1709716783 individual commands for more information."
1709816784 (interactive)
1709916785 (cond
16786 ((and (eq system-type 'darwin)
16787 (or (eq org-support-shift-select 'always)
16788 (and org-support-shift-select (org-region-active-p))))
16789 (org-call-for-shift-select 'forward-char))
1710016790 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
1710116791 ((org-at-table-p) (call-interactively 'org-table-insert-column))
1710216792 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
1722316913 (save-excursion
1722416914 (catch 'exit
1722516915 (unless (org-region-active-p)
17226 (setq beg (point-at-bol))
16916 (setq beg (line-beginning-position))
1722716917 (beginning-of-line 2)
1722816918 (while (and (not (eobp)) ;; this is like `next-line'
17229 (get-char-property (1- (point)) 'invisible))
16919 (org-invisible-p (1- (point))))
1723016920 (beginning-of-line 2))
1723116921 (setq end (point))
1723216922 (goto-char beg)
17233 (goto-char (point-at-eol))
16923 (goto-char (line-end-position))
1723416924 (setq end (max end (point)))
1723516925 (while (re-search-forward re end t)
17236 (when (get-char-property (match-beginning 0) 'invisible)
16926 (when (org-invisible-p (match-beginning 0))
1723716927 (throw 'exit t))))
1723816928 nil))))
1723916929
1724716937 ((run-hook-with-args-until-success 'org-metaup-hook))
1724816938 ((org-region-active-p)
1724916939 (let* ((a (save-excursion
17250 (goto-char (min (region-beginning) (region-end)))
16940 (goto-char (region-beginning))
1725116941 (line-beginning-position)))
1725216942 (b (save-excursion
17253 (goto-char (max (region-beginning) (region-end)))
16943 (goto-char (region-end))
1725416944 (if (bolp) (1- (point)) (line-end-position))))
1725516945 (c (save-excursion
1725616946 (goto-char a)
1728016970 ((run-hook-with-args-until-success 'org-metadown-hook))
1728116971 ((org-region-active-p)
1728216972 (let* ((a (save-excursion
17283 (goto-char (min (region-beginning) (region-end)))
16973 (goto-char (region-beginning))
1728416974 (line-beginning-position)))
1728516975 (b (save-excursion
17286 (goto-char (max (region-beginning) (region-end)))
16976 (goto-char (region-end))
1728716977 (if (bolp) (1- (point)) (line-end-position))))
1728816978 (c (save-excursion
1728916979 (goto-char b)
1752117211 (interactive "r")
1752217212 (let ((result ""))
1752317213 (while (/= beg end)
17524 (when (get-char-property beg 'invisible)
17525 (setq beg (next-single-char-property-change beg 'invisible nil end)))
17526 (let ((next (next-single-char-property-change beg 'invisible nil end)))
17527 (setq result (concat result (buffer-substring beg next)))
17528 (setq beg next)))
17529 (setq deactivate-mark t)
17214 (if (eq org-fold-core-style 'text-properties)
17215 (progn
17216 (while (org-invisible-p beg)
17217 (setq beg (org-fold-next-visibility-change beg end)))
17218 (let ((next (org-fold-next-visibility-change beg end)))
17219 (setq result (concat result (buffer-substring beg next)))
17220 (setq beg next)))
17221 (when (invisible-p beg)
17222 (setq beg (next-single-char-property-change beg 'invisible nil end)))
17223 (let ((next (next-single-char-property-change beg 'invisible nil end)))
17224 (setq result (concat result (buffer-substring beg next)))
17225 (setq beg next))))
17226 ;; Prevent Emacs from adding full selected text to `kill-ring'
17227 ;; when `select-enable-primary' is non-nil. This special value of
17228 ;; `deactivate-mark' only works since Emacs 29.
17229 (setq deactivate-mark 'dont-save)
1753017230 (kill-new result)
1753117231 (message "Visible strings have been copied to the kill ring.")))
1753217232
1756117261 When in a source code block, call `org-edit-src-code'.
1756217262 When in a fixed-width region, call `org-edit-fixed-width-region'.
1756317263 When in an export block, call `org-edit-export-block'.
17264 When in a comment block, call `org-edit-comment-block'.
1756417265 When in a LaTeX environment, call `org-edit-latex-environment'.
1756517266 When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
1756617267 When at a footnote reference, call `org-edit-footnote-reference'.
1760717308 (`table-row (call-interactively 'org-table-edit-formulas))
1760817309 (`example-block (org-edit-src-code))
1760917310 (`export-block (org-edit-export-block))
17311 (`comment-block (org-edit-comment-block))
1761017312 (`fixed-width (org-edit-fixed-width-region))
1761117313 (`latex-environment (org-edit-latex-environment))
1761217314 (`planning
1773217434 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
1773317435 ((or `babel-call `inline-babel-call)
1773417436 (let ((info (org-babel-lob-get-info context)))
17735 (when info (org-babel-execute-src-block nil info))))
17736 (`clock (org-clock-update-time-maybe))
17437 (when info (org-babel-execute-src-block nil info nil type))))
17438 (`clock
17439 (if (org-at-timestamp-p 'lax)
17440 ;; Update the timestamp as well. `org-timestamp-change'
17441 ;; will call `org-clock-update-time-maybe'.
17442 (org-timestamp-change 0 'day)
17443 (org-clock-update-time-maybe)))
1773717444 (`dynamic-block
1773817445 (save-excursion
1773917446 (goto-char (org-element-property :post-affiliated context))
1789317600 (org-reset-file-cache))
1789417601 (message "%s restarted" major-mode))
1789517602
17896 (defun org-flag-above-first-heading (&optional arg)
17897 "Hide from bob up to the first heading.
17898 Move point to the beginning of first heading or end of buffer."
17899 (goto-char (point-min))
17900 (unless (org-at-heading-p)
17901 (outline-next-heading))
17902 (unless (bobp)
17903 (org-flag-region 1 (1- (point)) (not arg) 'outline)))
17904
17905 (defun org-show-branches-buffer ()
17906 "Show all branches in the buffer."
17907 (org-flag-above-first-heading)
17908 (outline-hide-sublevels 1)
17909 (unless (eobp)
17910 (outline-show-branches)
17911 (while (outline-get-next-sibling)
17912 (outline-show-branches)))
17913 (goto-char (point-min)))
17914
1791517603 (defun org-kill-note-or-show-branches ()
1791617604 "Abort storing current note, or show just branches."
1791717605 (interactive)
1791817606 (cond (org-finish-function
1791917607 (let ((org-note-abort t)) (funcall org-finish-function)))
1792017608 ((org-before-first-heading-p)
17921 (org-show-branches-buffer)
17922 (org-hide-archived-subtrees (point-min) (point-max)))
17609 (org-fold-show-branches-buffer)
17610 (org-fold-hide-archived-subtrees (point-min) (point-max)))
1792317611 (t
1792417612 (let ((beg (progn (org-back-to-heading) (point)))
1792517613 (end (save-excursion (org-end-of-subtree t t) (point))))
17926 (outline-hide-subtree)
17927 (outline-show-branches)
17928 (org-hide-archived-subtrees beg end)))))
17614 (org-fold-hide-subtree)
17615 (org-fold-show-branches)
17616 (org-fold-hide-archived-subtrees beg end)))))
1792917617
1793017618 (defun org-delete-indentation (&optional arg)
1793117619 "Join current line to previous and fix whitespace at join.
1797917667 indent unconditionally; otherwise, call `newline' with ARG and
1798017668 INTERACTIVE, which can trigger indentation if
1798117669 `electric-indent-mode' is enabled."
17670 (when interactive
17671 (org-fold-check-before-invisible-edit 'insert))
1798217672 (if indent
1798317673 (org-newline-and-indent arg)
1798417674 (newline arg interactive)))
1804817738 (org-auto-align-tags (org-align-tags))
1804917739 (t (org--align-tags-here tags-column))) ;preserve tags column
1805017740 (end-of-line)
18051 (org-show-entry)
17741 (org-fold-show-entry 'hide-drawers)
1805217742 (org--newline indent arg interactive)
1805317743 (when string (save-excursion (insert (org-trim string))))))
1805417744 ;; In a list, make sure indenting keeps trailing text within.
1808617776 (call-interactively #'org-table-toggle-column-width))
1808717777 ((org-before-first-heading-p)
1808817778 (save-excursion
18089 (org-flag-above-first-heading)
18090 (outline-hide-sublevels (or arg 1))))
17779 (org-fold-flag-above-first-heading)
17780 (org-fold-hide-sublevels (or arg 1))))
1809117781 (t
18092 (outline-hide-subtree)
18093 (org-show-children arg))))
17782 (org-fold-hide-subtree)
17783 (org-fold-show-children arg))))
1809417784
1809517785 (defun org-ctrl-c-star ()
1809617786 "Compute table, or change heading status of lines.
1813817828 universal prefix argument.
1813917829
1814017830 - If it is a plain list item, turn all plain list items into headings.
17831 The checkboxes are converted to appropriate TODO or DONE keywords
17832 (using `car' or `org-done-keywords' and `org-not-done-keywords' when
17833 available).
1814117834
1814217835 When converting a line into a heading, the number of stars is chosen
1814317836 such that the lines become children of the current entry. However,
1815217845 (goto-char pos)
1815317846 (while (org-at-comment-p) (forward-line))
1815417847 (skip-chars-forward " \r\t\n")
18155 (point-at-bol))))
17848 (line-beginning-position))))
1815617849 beg end toggled)
1815717850 ;; Determine boundaries of changes. If a universal prefix has
1815817851 ;; been given, put the list in a region. If region ends at a bol,
1816617859 (setq beg (funcall skip-blanks (region-beginning))
1816717860 end (copy-marker (save-excursion
1816817861 (goto-char (region-end))
18169 (if (bolp) (point) (point-at-eol)))))
18170 (setq beg (funcall skip-blanks (point-at-bol))
18171 end (copy-marker (point-at-eol))))
17862 (if (bolp) (point) (line-end-position)))))
17863 (setq beg (funcall skip-blanks (line-beginning-position))
17864 end (copy-marker (line-end-position))))
1817217865 ;; Ensure inline tasks don't count as headings.
1817317866 (org-with-limited-levels
1817417867 (save-excursion
1817717870 ;; Case 1. Started at an heading: de-star headings.
1817817871 ((org-at-heading-p)
1817917872 (while (< (point) end)
18180 (when (org-at-heading-p t)
17873 (when (org-at-heading-p)
1818117874 (looking-at org-outline-regexp) (replace-match "")
1818217875 (setq toggled t))
1818317876 (forward-line)))
1819617889 (org-list-to-lisp t)
1819717890 (pcase (org-current-level)
1819817891 (`nil 1)
18199 (l (1+ (org-reduced-level l)))))
17892 (l (1+ (org-reduced-level l))))
17893 ;; Keywords to replace checkboxes.
17894 (list
17895 ;; [X]
17896 :cbon (concat (or (car org-done-keywords) "DONE") " ")
17897 ;; [ ]
17898 :cboff (concat (or (car org-not-done-keywords) "TODO") " ")
17899 ;; [-]
17900 :cbtrans (concat (or (car org-not-done-keywords) "TODO") " ")))
1820017901 "\n")))
1820117902 (setq toggled t))
1820217903 (forward-line)))
1822517926 `org-table-wrap-region', depending on context. When called with
1822617927 an argument, unconditionally call `org-insert-heading'."
1822717928 (interactive "P")
18228 (org-check-before-invisible-edit 'insert)
17929 (org-fold-check-before-invisible-edit 'insert)
1822917930 (or (run-hook-with-args-until-success 'org-metareturn-hook)
1823017931 (call-interactively (cond (arg #'org-insert-heading)
1823117932 ((org-at-table-p) #'org-table-wrap-region)
1824517946 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
1824617947 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
1824717948 ["Sparse Tree..." org-sparse-tree t]
18248 ["Reveal Context" org-reveal t]
18249 ["Show All" org-show-all t]
17949 ["Reveal Context" org-fold-reveal t]
17950 ["Show All" org-fold-show-all t]
1825017951 "--"
1825117952 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
1825217953 "--"
1855118252 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
1855218253 (and
1855318254 (get v 'custom-type) (get v 'standard-value)
18554 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18255 (not (equal (symbol-value v)
18256 (eval (car (get v 'standard-value)) t)))))
1855518257 (push v list)))))
1855618258 (kill-buffer (get-buffer "*Warn about privacy*"))
1855718259 list))
1856618268 (save-excursion
1856718269 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
1856818270 (replace-match "\\1[BUG] \\3 [\\2]")))))
18569
1857018271
1857118272 (defun org-install-agenda-files-menu ()
1857218273 "Install agenda file menu."
1860618307 (require 'loadhist)
1860718308 (let* ((org-dir (org-find-library-dir "org"))
1860818309 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
18609 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
18310 (feature-re "^\\(org\\|ob\\|ox\\|ol\\|oc\\)\\(-.*\\)?")
1861018311 (remove-re (format "\\`%s\\'"
1861118312 (regexp-opt '("org" "org-loaddefs" "org-version"))))
1861218313 (feats (delete-dups
1862618327 feats)))
1862718328 'string-lessp)
1862818329 (list "org-version" "org")))
18629 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
1863018330 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
1863118331 load-uncore load-misses)
1863218332 (setq load-misses
18633 (delq 't
18333 (delq t
1863418334 (mapcar (lambda (f)
1863518335 (or (org-load-noerror-mustsuffix (concat org-dir f))
1863618336 (and (string= org-dir contrib-dir)
1863718337 (org-load-noerror-mustsuffix (concat contrib-dir f)))
1863818338 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
1863918339 (push f load-uncore)
18640 't)
18340 t)
1864118341 f))
1864218342 lfeat)))
1864318343 (when load-uncore
1870418404 (when (or (> marker (point-max)) (< marker (point-min)))
1870518405 (widen))
1870618406 (goto-char marker)
18707 (org-show-context 'org-goto))
18407 (org-fold-show-context 'org-goto))
1870818408 (if bookmark
1870918409 (bookmark-jump bookmark)
1871018410 (error "Cannot find location"))))
1873018430 "Is S an ID created by UUIDGEN?"
1873118431 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
1873218432
18733 (defun org-in-src-block-p (&optional inside)
18433 (defun org-in-src-block-p (&optional inside element)
1873418434 "Whether point is in a code source block.
1873518435 When INSIDE is non-nil, don't consider we are within a source
18736 block when point is at #+BEGIN_SRC or #+END_SRC."
18737 (let ((case-fold-search t))
18738 (or (and (eq (get-char-property (point) 'src-block) t))
18739 (and (not inside)
18740 (save-match-data
18741 (save-excursion
18742 (beginning-of-line)
18743 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
18436 block when point is at #+BEGIN_SRC or #+END_SRC.
18437 When ELEMENT is provided, it is considered to be element at point."
18438 (save-match-data (setq element (or element (org-element-at-point))))
18439 (when (eq 'src-block (org-element-type element))
18440 (or (not inside)
18441 (not (or (= (line-beginning-position)
18442 (org-element-property :post-affiliated element))
18443 (= (1+ (line-end-position))
18444 (- (org-element-property :end element)
18445 (org-element-property :post-blank element))))))))
1874418446
1874518447 (defun org-context ()
1874618448 "Return a list of contexts of the current cursor position.
1877618478 (p (point)) clist o)
1877718479 ;; First the large context
1877818480 (cond
18779 ((org-at-heading-p t)
18780 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18481 ((org-at-heading-p)
18482 (push (list :headline (line-beginning-position)
18483 (line-end-position))
18484 clist)
1878118485 (when (progn
1878218486 (beginning-of-line 1)
1878318487 (looking-at org-todo-line-tags-regexp))
1879118495
1879218496 ((org-at-item-p)
1879318497 (push (org-point-in-group p 2 :item-bullet) clist)
18794 (push (list :item (point-at-bol)
18498 (push (list :item (line-beginning-position)
1879518499 (save-excursion (org-end-of-item) (point)))
1879618500 clist)
1879718501 (and (org-at-item-checkbox-p)
1891418618 (throw 'exit n)))))
1891518619 nil)))
1891618620
18621 ;; Defined in org-agenda.el
18622 (defvar org-agenda-restrict)
18623 (defvar org-agenda-restrict-begin)
18624 (defvar org-agenda-restrict-end)
1891718625 (defun org-occur-in-agenda-files (regexp &optional _nlines)
1891818626 "Call `multi-occur' with buffers for all agenda files."
1891918627 (interactive "sOrg-files matching: ")
1893918647 regexp)))
1894018648
1894118649 (add-hook 'occur-mode-find-occurrence-hook
18942 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
18650 (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
1894318651
1894418652 (defun org-occur-link-in-agenda-files ()
1894518653 "Create a link and search for it in the agendas.
1899018698 (cond
1899118699 ((eq major-mode 'calendar-mode)
1899218700 (setq date (calendar-cursor-to-date)
18993 defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
18994 (nth 1 date) (nth 0 date) (nth 2 date))))
18701 defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
18702 (nth 1 date) (nth 0 date) (nth 2 date))))
1899518703 ((eq major-mode 'org-agenda-mode)
1899618704 (setq day (get-text-property (point) 'day))
1899718705 (when day
1899818706 (setq date (calendar-gregorian-from-absolute day)
18999 defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
19000 (nth 1 date) (nth 0 date) (nth 2 date))))))
18707 defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
18708 (nth 1 date) (nth 0 date) (nth 2 date))))))
1900118709 (or defd (current-time))))
1900218710
1900318711 (defun org-mark-subtree (&optional up)
1901718725
1901818726 ;;; Indentation
1901918727
18728 (defun org--at-headline-data-p (&optional beg element)
18729 "Return non-nil when `point' or BEG is inside headline metadata.
18730
18731 Metadata is planning line, properties drawer, logbook drawer right
18732 after property drawer, or clock log line immediately following
18733 properties drawer/planning line/ heading.
18734
18735 Optional argument ELEMENT contains element at BEG."
18736 (org-with-wide-buffer
18737 (when beg (goto-char beg))
18738 (setq element (or element (org-element-at-point)))
18739 (if (or (eq (org-element-type element) 'headline)
18740 (not (org-element-lineage element '(headline inlinetask))))
18741 nil ; Not inside heading.
18742 ;; Skip to top-level parent in section.
18743 (while (not (eq 'section (org-element-type (org-element-property :parent element))))
18744 (setq element (org-element-property :parent element)))
18745 (pcase (org-element-type element)
18746 ((or `planning `property-drawer)
18747 t)
18748 (`drawer
18749 ;; LOGBOOK drawer with appropriate name.
18750 (equal
18751 (org-log-into-drawer)
18752 (org-element-property :drawer-name element)))
18753 (`clock
18754 ;; Previous element must be headline metadata or headline.
18755 (goto-char (1- (org-element-property :begin element)))
18756 (or (org-at-heading-p)
18757 (org--at-headline-data-p)))))))
18758
1902018759 (defvar org-element-greater-elements)
1902118760 (defun org--get-expected-indentation (element contentsp)
1902218761 "Expected indentation column for current line, according to ELEMENT.
1903118770 (contentsp
1903218771 (cl-case type
1903318772 ((diary-sexp footnote-definition) 0)
18773 (section
18774 (org--get-expected-indentation
18775 (org-element-property :parent element)
18776 t))
1903418777 ((headline inlinetask nil)
1903518778 (if (not org-adapt-indentation) 0
1903618779 (let ((level (org-current-level)))
1905118794 (org-element-property :parent element) t))
1905218795 ;; At first line: indent according to previous sibling, if any,
1905318796 ;; ignoring footnote definitions and inline tasks, or parent's
19054 ;; contents.
19055 ((and ( = (line-beginning-position) start)
19056 (eq org-adapt-indentation t))
18797 ;; contents. If `org-adapt-indentation' is `headline-data', ignore
18798 ;; previous headline data siblings.
18799 ((= (line-beginning-position) start)
1905718800 (catch 'exit
1905818801 (while t
1905918802 (if (= (point-min) start) (throw 'exit 0)
1907018813 ((memq (org-element-type previous)
1907118814 '(footnote-definition inlinetask))
1907218815 (setq start (org-element-property :begin previous)))
18816 ;; Do not indent like previous when the previous
18817 ;; element is headline data and `org-adapt-indentation'
18818 ;; is set to `headline-data'.
18819 ((and (eq 'headline-data org-adapt-indentation)
18820 (not (org--at-headline-data-p start element))
18821 (or (org-at-heading-p)
18822 (org--at-headline-data-p (1- start) previous)))
18823 (throw 'exit 0))
1907318824 (t (goto-char (org-element-property :begin previous))
1907418825 (throw 'exit
1907518826 (if (bolp) (current-indentation)
1913018881 (when (save-excursion
1913118882 (beginning-of-line)
1913218883 (looking-at org-property-re))
19133 (replace-match
19134 (concat (match-string 4)
19135 (org-trim
19136 (format org-property-format (match-string 1) (match-string 3))))
19137 t t)))
18884 (org-combine-change-calls (match-beginning 0) (match-end 0)
18885 (let ((newtext (concat (match-string 4)
18886 (org-trim
18887 (format org-property-format (match-string 1) (match-string 3))))))
18888 ;; Do not use `replace-match' here as we want to inherit folding
18889 ;; properties if inside fold.
18890 (delete-region (match-beginning 0) (match-end 0))
18891 (insert-and-inherit newtext)))))
1913818892
1913918893 (defun org-indent-line ()
1914018894 "Indent line depending on context.
1918018934
1918118935 Also align node properties according to `org-property-format'."
1918218936 (interactive)
19183 (unless (or (org-at-heading-p)
19184 (and (eq org-adapt-indentation 'headline-data)
19185 (not (or (org-at-clock-log-p)
19186 (org-at-planning-p)))
19187 (save-excursion
19188 (beginning-of-line 1)
19189 (skip-chars-backward "\n")
19190 (or (org-at-heading-p)
19191 (looking-back ":END:.*" (point-at-bol))))))
19192 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
19193 (type (org-element-type element)))
18937 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
18938 (type (org-element-type element)))
18939 (unless (or (org-at-heading-p)
18940 (and (eq org-adapt-indentation 'headline-data)
18941 (not (org--at-headline-data-p nil element))
18942 (save-excursion
18943 (goto-char (1- (org-element-property :begin element)))
18944 (or (org-at-heading-p)
18945 (org--at-headline-data-p)))))
1919418946 (cond ((and (memq type '(plain-list item))
1919518947 (= (line-beginning-position)
1919618948 (org-element-property :post-affiliated element)))
1921718969 (let ((element (org-element-at-point))
1921818970 block-content-ind some-ind)
1921918971 (org-with-point-at (org-element-property :begin element)
19220 (setq block-content-ind (+ (current-indentation)
18972 (setq block-content-ind (+ (org-current-text-indentation)
1922118973 org-edit-src-content-indentation))
1922218974 (forward-line)
1922318975 (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
1922418976 (backward-char)
1922518977 (setq some-ind (if (looking-at-p "#\\+end_src")
19226 block-content-ind (current-indentation))))
18978 block-content-ind (org-current-text-indentation))))
1922718979 (indent-line-to (min block-content-ind some-ind))))
1922818980 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
1922918981 (t
1933219084 ;; might break the list as a whole. On the other
1933319085 ;; hand, when at a plain list, indent it as a whole.
1933419086 (cond ((eq type 'plain-list)
19335 (let ((offset (- ind (current-indentation))))
19087 (let ((offset (- ind (org-current-text-indentation))))
1933619088 (unless (zerop offset)
1933719089 (indent-rigidly (org-element-property :begin element)
1933819090 (org-element-property :end element)
1936819120 (beginning-of-line)
1936919121 (looking-at-p org-drawer-regexp))
1937019122 (user-error "Not at a drawer"))
19371 (let ((element (org-element-at-point)))
19123 (let ((element (org-element-at-point-no-context)))
1937219124 (unless (memq (org-element-type element) '(drawer property-drawer))
1937319125 (user-error "Not at a drawer"))
1937419126 (org-with-wide-buffer
1938419136 (let ((case-fold-search t))
1938519137 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
1938619138 (user-error "Not at a block"))
19387 (let ((element (org-element-at-point)))
19139 (let ((element (org-element-at-point-no-context)))
1938819140 (unless (memq (org-element-type element)
1938919141 '(comment-block center-block dynamic-block example-block
1939019142 export-block quote-block special-block
1941219164 ;; `org-setup-filling' installs filling and auto-filling related
1941319165 ;; variables during `org-mode' initialization.
1941419166
19167 (defvar org--single-lines-list-is-paragraph) ; defined later
19168
1941519169 (defun org-setup-filling ()
1941619170 (require 'org-element)
1941719171 ;; Prevent auto-fill from inserting unwanted new items.
19418 (when (boundp 'fill-nobreak-predicate)
19419 (setq-local
19420 fill-nobreak-predicate
19421 (org-uniquify
19422 (append fill-nobreak-predicate
19423 '(org-fill-line-break-nobreak-p
19424 org-fill-n-macro-as-item-nobreak-p
19425 org-fill-paragraph-with-timestamp-nobreak-p)))))
19172 (setq-local fill-nobreak-predicate
19173 (org-uniquify
19174 (append fill-nobreak-predicate
19175 '(org-fill-line-break-nobreak-p
19176 org-fill-n-macro-as-item-nobreak-p
19177 org-fill-paragraph-with-timestamp-nobreak-p))))
1942619178 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
1942719179 (setq-local paragraph-start paragraph-ending)
1942819180 (setq-local paragraph-separate paragraph-ending))
1942919181 (setq-local fill-paragraph-function 'org-fill-paragraph)
19182 (setq-local fill-forward-paragraph-function
19183 (lambda (&optional arg)
19184 (let ((org--single-lines-list-is-paragraph nil))
19185 (org-forward-paragraph arg))))
1943019186 (setq-local auto-fill-inhibit-regexp nil)
1943119187 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
1943219188 (setq-local normal-auto-fill-function 'org-auto-fill-function)
1953119287 ;; the buffer. In that case, ignore filling.
1953219288 (cl-case (org-element-type element)
1953319289 ;; Use major mode filling function is source blocks.
19534 (src-block (org-babel-do-in-edit-buffer
19535 (push-mark (point-min))
19536 (goto-char (point-max))
19537 (setq mark-active t)
19538 (funcall-interactively #'fill-paragraph justify 'region)))
19290 (src-block
19291 (let ((regionp (region-active-p)))
19292 (org-babel-do-in-edit-buffer
19293 ;; `org-babel-do-in-edit-buffer' will preserve region if it
19294 ;; is within src block contents. Otherwise, the region
19295 ;; crosses src block boundaries. We re-fill the whole src
19296 ;; block in such scenario.
19297 (when (and regionp (not (region-active-p)))
19298 (push-mark (point-min))
19299 (goto-char (point-max))
19300 (setq mark-active t))
19301 (funcall-interactively #'fill-paragraph justify 'region))))
1953919302 ;; Align Org tables, leave table.el tables as-is.
1954019303 (table-row (org-table-align) t)
1954119304 (table
1965619419 (progn
1965719420 (goto-char (region-end))
1965819421 (skip-chars-backward " \t\n")
19659 (while (> (point) start)
19660 (org-fill-element justify)
19661 (org-backward-paragraph)))
19422 (let ((org--single-lines-list-is-paragraph nil))
19423 (while (> (point) start)
19424 (org-fill-element justify)
19425 (org-backward-paragraph)
19426 (skip-chars-backward " \t\n"))))
1966219427 (goto-char origin)
1966319428 (set-marker origin nil))))
1966419429 (t
1968919454 "Break line at point and indent, continuing comment if within one.
1969019455 The inserted newline is marked hard if variable
1969119456 `use-hard-newlines' is true, unless optional argument SOFT is
19692 non-nil."
19693 (if soft (insert-and-inherit ?\n) (newline 1))
19694 (save-excursion (forward-char -1) (delete-horizontal-space))
19695 (delete-horizontal-space)
19696 (indent-to-left-margin)
19697 (insert-before-markers-and-inherit fill-prefix))
19457 non-nil.
19458
19459 This function is a simplified version of `comment-indent-new-line'
19460 that bypasses the complex Emacs machinery dealing with comments.
19461 We instead rely on Org parser, utilizing `org-adaptive-fill-function'"
19462 (let ((fill-prefix (org-adaptive-fill-function)))
19463 (if soft (insert-and-inherit ?\n) (newline 1))
19464 (save-excursion (forward-char -1) (delete-horizontal-space))
19465 (delete-horizontal-space)
19466 (indent-to-left-margin)
19467 (when fill-prefix
19468 (insert-before-markers-and-inherit fill-prefix))))
1969819469
1969919470
1970019471 ;;; Fixed Width Areas
1978619557 (catch 'zerop
1978719558 (while (< (point) end)
1978819559 (unless (looking-at-p "[ \t]*$")
19789 (let ((ind (current-indentation)))
19560 (let ((ind (org-current-text-indentation)))
1979019561 (setq min-ind (min min-ind ind))
1979119562 (when (zerop ind) (throw 'zerop t))))
1979219563 (forward-line)))))
1987119642 (cl-decf count))))
1987219643 (if (= count 0)
1987319644 (prog1 (goto-char (org-element-property :post-affiliated last-element))
19874 (save-match-data (org-show-context)))
19645 (save-match-data (org-fold-show-context)))
1987519646 (goto-char origin)
1987619647 (user-error "No %s code blocks" (if backward "previous" "further")))))
1987719648
1992819699 (point))))
1992919700 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
1993019701 (beginning-of-line)
19931 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
19702 (if (looking-at "\\s-*$") (delete-region (point) (line-end-position))
1993219703 (open-line 1))
1993319704 (org-indent-line)
1993419705 (insert "# ")))
1994619717 (line-end-position))
1994719718 beg)
1994819719 (>= (save-excursion
19949 (goto-char (org-element-property :end element))
19950 (skip-chars-backward " \r\t\n")
19951 (line-beginning-position))
19952 end)))
19720 (goto-char (org-element-property :end element))
19721 (skip-chars-backward " \r\t\n")
19722 (line-beginning-position))
19723 end)))
1995319724 ;; Translate region boundaries for the Org buffer to the source
1995419725 ;; buffer.
1995519726 (let ((offset (- end beg)))
1999219763 (goto-char (point-min))
1999319764 (while (and (not (eobp)) (not (zerop min-indent)))
1999419765 (unless (looking-at "[ \t]*$")
19995 (setq min-indent (min min-indent (current-indentation))))
19766 (setq min-indent (min min-indent (org-current-text-indentation))))
1999619767 (forward-line)))
1999719768 ;; Then loop over all lines.
1999819769 (save-excursion
2005519826 "Convert TIMESTAMP object into an Emacs internal time value.
2005619827 Use end of date range or time range when END is non-nil.
2005719828 Otherwise, use its start."
20058 (apply #'encode-time 0
20059 (mapcar
20060 (lambda (prop) (or (org-element-property prop timestamp) 0))
20061 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
20062 '(:minute-start :hour-start :day-start :month-start
20063 :year-start)))))
19829 (org-encode-time
19830 (append '(0)
19831 (mapcar
19832 (lambda (prop) (or (org-element-property prop timestamp) 0))
19833 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
19834 '(:minute-start :hour-start :day-start :month-start
19835 :year-start)))
19836 '(nil -1 nil))))
2006419837
2006519838 (defun org-timestamp-has-time-p (timestamp)
2006619839 "Non-nil when TIMESTAMP has a time specified."
2006719840 (org-element-property :hour-start timestamp))
2006819841
20069 (defun org-timestamp-format (timestamp format &optional end utc)
19842 (defun org-format-timestamp (timestamp format &optional end utc)
2007019843 "Format a TIMESTAMP object into a string.
2007119844
2007219845 FORMAT is a format specifier to be passed to
2012719900 (let ((type (org-element-property :type timestamp)))
2012819901 (if (or (not org-display-custom-times) (eq type 'diary))
2012919902 (org-element-interpret-data timestamp)
20130 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
20131 org-time-stamp-custom-formats)))
19903 (let ((fmt (org-time-stamp-format
19904 (org-timestamp-has-time-p timestamp) nil 'custom)))
2013219905 (if (and (not boundary) (memq type '(active-range inactive-range)))
20133 (concat (org-timestamp-format timestamp fmt)
19906 (concat (org-format-timestamp timestamp fmt)
2013419907 "--"
20135 (org-timestamp-format timestamp fmt t))
20136 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
19908 (org-format-timestamp timestamp fmt t))
19909 (org-format-timestamp timestamp fmt (eq boundary 'end)))))))
2013719910
2013819911 ;;; Other stuff
2013919912
2034620119 (call-interactively #'forward-sentence)))))))
2034720120
2034820121 (defun org-kill-line (&optional _arg)
20349 "Kill line, to tags or end of line."
20122 "Kill line, to tags or end of line.
20123
20124 The behavior of this command depends on the user options
20125 `org-special-ctrl-k' and `org-ctrl-k-protect-subtree' (which
20126 see)."
2035020127 (interactive)
2035120128 (cond
2035220129 ((or (not org-special-ctrl-k)
2035320130 (bolp)
2035420131 (not (org-at-heading-p)))
20355 (when (and (get-char-property (line-end-position) 'invisible)
20132 (when (and (org-invisible-p (line-end-position))
2035620133 org-ctrl-k-protect-subtree
2035720134 (or (eq org-ctrl-k-protect-subtree 'error)
2035820135 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
2042120198 (and (looking-at "[ \t]*$")
2042220199 (string-match
2042320200 "\\`\\*+\\'"
20424 (buffer-substring (point-at-bol) (point)))))))
20201 (buffer-substring (line-beginning-position) (point)))))))
2042520202 swallowp)
2042620203 (cond
2042720204 ((and subtreep org-yank-folded-subtrees)
2044020217 (or (looking-at org-outline-regexp)
2044120218 (re-search-forward org-outline-regexp-bol end t))
2044220219 (while (and (< (point) end) (looking-at org-outline-regexp))
20443 (org-flag-subtree t)
20220 (org-fold-subtree t)
2044420221 (org-cycle-show-empty-lines 'folded)
2044520222 (condition-case nil
2044620223 (outline-forward-same-level 1)
2045420231 (beginning-of-line 1)
2045520232 (push-mark beg 'nomsg)))
2045620233 ((and subtreep org-yank-adjusted-subtrees)
20457 (let ((beg (point-at-bol)))
20234 (let ((beg (line-beginning-position)))
2045820235 (org-paste-subtree nil nil 'for-yank)
2045920236 (push-mark beg 'nomsg)))
2046020237 (t
2047620253 (<= (org-outline-level) level))))))))
2047720254
2047820255 (defun org-back-to-heading (&optional invisible-ok)
20479 "Call `outline-back-to-heading', but provide a better error message."
20480 (condition-case nil
20481 (outline-back-to-heading invisible-ok)
20482 (error
20483 (user-error "Before first headline at position %d in buffer %s"
20484 (point) (current-buffer)))))
20256 "Go back to beginning of heading."
20257 (beginning-of-line)
20258 (or (and (org-at-heading-p (not invisible-ok))
20259 (not (and (featurep 'org-inlinetask)
20260 (fboundp 'org-inlinetask-end-p)
20261 (org-inlinetask-end-p))))
20262 (if (org-element--cache-active-p)
20263 (let ((heading (org-element-lineage (org-element-at-point)
20264 '(headline inlinetask)
20265 'include-self)))
20266 (when heading
20267 (goto-char (org-element-property :begin heading)))
20268 (while (and (not invisible-ok)
20269 heading
20270 (org-fold-folded-p))
20271 (goto-char (org-fold-core-previous-visibility-change))
20272 (setq heading (org-element-lineage (org-element-at-point)
20273 '(headline inlinetask)
20274 'include-self))
20275 (when heading
20276 (goto-char (org-element-property :begin heading))))
20277 (unless heading
20278 (user-error "Before first headline at position %d in buffer %s"
20279 (point) (current-buffer)))
20280 (point))
20281 (let (found)
20282 (save-excursion
20283 ;; At inlinetask end. Move to bol, so that the following
20284 ;; search goes to the beginning of the inlinetask.
20285 (when (and (featurep 'org-inlinetask)
20286 (fboundp 'org-inlinetask-end-p)
20287 (org-inlinetask-end-p))
20288 (goto-char (line-beginning-position)))
20289 (while (not found)
20290 (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
20291 nil t)
20292 (user-error "Before first headline at position %d in buffer %s"
20293 (point) (current-buffer)))
20294 ;; Skip inlinetask end.
20295 (if (and (featurep 'org-inlinetask)
20296 (fboundp 'org-inlinetask-end-p)
20297 (org-inlinetask-end-p))
20298 (org-inlinetask-goto-beginning)
20299 (setq found (and (or invisible-ok (not (org-fold-folded-p)))
20300 (point))))))
20301 (goto-char found)
20302 found))))
2048520303
2048620304 (defun org-back-to-heading-or-point-min (&optional invisible-ok)
2048720305 "Go back to heading or first point in buffer.
2048820306 If point is before first heading go to first point in buffer
2048920307 instead of back to heading."
20490 (condition-case nil
20491 (outline-back-to-heading invisible-ok)
20492 (error
20493 (goto-char (point-min)))))
20308 (if (org-before-first-heading-p)
20309 (goto-char (point-min))
20310 (org-back-to-heading invisible-ok)))
2049420311
2049520312 (defun org-before-first-heading-p ()
20496 "Before first heading?"
20497 (org-with-limited-levels
20498 (save-excursion
20499 (end-of-line)
20500 (null (re-search-backward org-outline-regexp-bol nil t)))))
20501
20502 (defun org-at-heading-p (&optional _)
20503 "Non-nil when on a headline."
20504 (outline-on-heading-p t))
20505
20506 (defun org-in-commented-heading-p (&optional no-inheritance)
20313 "Before first heading?
20314 Respect narrowing."
20315 (let ((cached (org-element-at-point nil 'cached)))
20316 (if cached
20317 (let ((cached-headline (org-element-lineage cached '(headline) t)))
20318 (or (not cached-headline)
20319 (< (org-element-property :begin cached-headline) (point-min))))
20320 (org-with-limited-levels
20321 (save-excursion
20322 (end-of-line)
20323 (null (re-search-backward org-outline-regexp-bol nil t)))))))
20324
20325 (defun org-at-heading-p (&optional invisible-not-ok)
20326 "Return t if point is on a (possibly invisible) heading line.
20327 If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
20328 (save-excursion
20329 (beginning-of-line)
20330 (and (bolp) (or (not invisible-not-ok) (not (org-fold-folded-p)))
20331 (looking-at outline-regexp))))
20332
20333 (defun org-in-commented-heading-p (&optional no-inheritance element)
2050720334 "Non-nil if point is under a commented heading.
2050820335 This function also checks ancestors of the current headline,
20509 unless optional argument NO-INHERITANCE is non-nil."
20336 unless optional argument NO-INHERITANCE is non-nil.
20337
20338 Optional argument ELEMENT contains element at point."
20339 (save-match-data
20340 (let ((el (or element
20341 (org-element-at-point nil 'cached)
20342 (org-with-wide-buffer
20343 (org-back-to-heading-or-point-min t)
20344 (org-element-at-point)))))
20345 (catch :found
20346 (setq el (org-element-lineage el '(headline inlinetask) 'include-self))
20347 (if no-inheritance
20348 (org-element-property :commentedp el)
20349 (while el
20350 (when (org-element-property :commentedp el)
20351 (throw :found t))
20352 (setq el (org-element-property :parent el))))))))
20353
20354 (defun org-in-archived-heading-p (&optional no-inheritance element)
20355 "Non-nil if point is under an archived heading.
20356 This function also checks ancestors of the current headline,
20357 unless optional argument NO-INHERITANCE is non-nil.
20358
20359 Optional argument ELEMENT contains element at point."
2051020360 (cond
20511 ((org-before-first-heading-p) nil)
20512 ((let ((headline (nth 4 (org-heading-components))))
20513 (and headline
20514 (let ((case-fold-search nil))
20515 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
20516 headline)))))
20361 ((and (not element) (org-before-first-heading-p)) nil)
20362 ((if element
20363 (org-element-property :archivedp element)
20364 (let ((tags (org-get-tags element 'local)))
20365 (and tags
20366 (cl-some (apply-partially #'string= org-archive-tag) tags)))))
2051720367 (no-inheritance nil)
2051820368 (t
20519 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
20520
20521 (defun org-in-archived-heading-p (&optional no-inheritance)
20522 "Non-nil if point is under an archived heading.
20523 This function also checks ancestors of the current headline,
20524 unless optional argument NO-INHERITANCE is non-nil."
20525 (cond
20526 ((org-before-first-heading-p) nil)
20527 ((let ((tags (org-get-tags nil 'local)))
20528 (and tags
20529 (cl-some (apply-partially #'string= org-archive-tag) tags))))
20530 (no-inheritance nil)
20531 (t
20532 (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p))))))
20369 (if (or element (org-element--cache-active-p))
20370 (catch :archived
20371 (unless element (setq element (org-element-at-point)))
20372 (while element
20373 (when (org-element-property :archivedp element)
20374 (throw :archived t))
20375 (setq element (org-element-property :parent element))))
20376 (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
2053320377
2053420378 (defun org-at-comment-p nil
2053520379 "Return t if cursor is in a commented line."
2058920433 Also, this function will be a lot faster than `outline-up-heading',
2059020434 because it relies on stars being the outline starters. This can really
2059120435 make a significant difference in outlines with very many siblings."
20592 (when (ignore-errors (org-back-to-heading t))
20593 (let (level-cache)
20594 (unless org--up-heading-cache
20595 (setq org--up-heading-cache (make-hash-table)))
20596 (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
20597 (setq level-cache (gethash (point) org--up-heading-cache)))
20598 (when (<= (point-min) (car level-cache) (point-max))
20599 ;; Parent is inside accessible part of the buffer.
20600 (progn (goto-char (car level-cache))
20601 (cdr level-cache)))
20602 ;; Buffer modified. Invalidate cache.
20603 (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
20604 (setq-local org--up-heading-cache-tick
20605 (buffer-chars-modified-tick))
20606 (clrhash org--up-heading-cache))
20607 (let* ((level-up (1- (funcall outline-level)))
20608 (pos (point))
20609 (result (and (> level-up 0)
20610 (re-search-backward
20611 (format "^\\*\\{1,%d\\} " level-up) nil t)
20612 (funcall outline-level))))
20613 (when result (puthash pos (cons (point) result) org--up-heading-cache))
20614 result)))))
20436 (let ((element (and (org-element--cache-active-p)
20437 (org-element-at-point nil t))))
20438 (if element
20439 (let* ((current-heading (org-element-lineage element '(headline inlinetask) 'with-self))
20440 (parent (org-element-lineage current-heading '(headline))))
20441 (if (and parent
20442 (<= (point-min) (org-element-property :begin parent)))
20443 (progn
20444 (goto-char (org-element-property :begin parent))
20445 (org-element-property :level parent))
20446 (when (and current-heading
20447 (<= (point-min) (org-element-property :begin current-heading)))
20448 (goto-char (org-element-property :begin current-heading))
20449 nil)))
20450 (when (ignore-errors (org-back-to-heading t))
20451 (let (level-cache)
20452 (unless org--up-heading-cache
20453 (setq org--up-heading-cache (make-hash-table)))
20454 (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
20455 (setq level-cache (gethash (point) org--up-heading-cache)))
20456 (when (<= (point-min) (car level-cache) (point-max))
20457 ;; Parent is inside accessible part of the buffer.
20458 (progn (goto-char (car level-cache))
20459 (cdr level-cache)))
20460 ;; Buffer modified. Invalidate cache.
20461 (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
20462 (setq-local org--up-heading-cache-tick
20463 (buffer-chars-modified-tick))
20464 (clrhash org--up-heading-cache))
20465 (let* ((level-up (1- (funcall outline-level)))
20466 (pos (point))
20467 (result (and (> level-up 0)
20468 (re-search-backward
20469 (format "^\\*\\{1,%d\\} " level-up) nil t)
20470 (funcall outline-level))))
20471 (when result (puthash pos (cons (point) result) org--up-heading-cache))
20472 result)))))))
2061520473
2061620474 (defun org-up-heading-or-point-min ()
2061720475 "Move to the heading line of which the present is a subheading, or point-min.
2062120479 point before the first headline or at point-min."
2062220480 (when (ignore-errors (org-back-to-heading t))
2062320481 (if (< 1 (funcall outline-level))
20624 (org-up-heading-safe)
20482 (or (org-up-heading-safe)
20483 ;; The first heading may not be level 1 heading.
20484 (goto-char (point-min)))
2062520485 (unless (= (point) (point-min)) (goto-char (point-min))))))
2062620486
2062720487 (defun org-first-sibling-p ()
2065820518 (goto-char pos)
2065920519 nil))))
2066020520
20661 (defun org-show-siblings ()
20662 "Show all siblings of the current headline."
20663 (save-excursion
20664 (while (org-goto-sibling) (org-flag-heading nil)))
20665 (save-excursion
20666 (while (org-goto-sibling 'previous)
20667 (org-flag-heading nil))))
20668
20669 (defun org-goto-first-child ()
20521 (defun org-goto-first-child (&optional element)
2067020522 "Goto the first child, even if it is invisible.
2067120523 Return t when a child was found. Otherwise don't move point and
2067220524 return nil."
20673 (let (level (pos (point)) (re org-outline-regexp-bol))
20674 (when (org-back-to-heading-or-point-min t)
20675 (setq level (org-outline-level))
20676 (forward-char 1)
20677 (if (and (re-search-forward re nil t) (> (org-outline-level) level))
20678 (progn (goto-char (match-beginning 0)) t)
20679 (goto-char pos) nil))))
20680
20681 (defun org-show-hidden-entry ()
20682 "Show an entry where even the heading is hidden."
20683 (save-excursion
20684 (org-show-entry)))
20685
20686 (defun org-flag-heading (flag &optional entry)
20687 "Flag the current heading. FLAG non-nil means make invisible.
20688 When ENTRY is non-nil, show the entire entry."
20689 (save-excursion
20690 (org-back-to-heading t)
20691 ;; Check if we should show the entire entry
20692 (if (not entry)
20693 (org-flag-region
20694 (line-end-position 0) (line-end-position) flag 'outline)
20695 (org-show-entry)
20696 (save-excursion
20697 (and (outline-next-heading)
20698 (org-flag-heading nil))))))
20525 (if (org-element--cache-active-p)
20526 (let ((heading (org-element-lineage
20527 (or element (org-element-at-point))
20528 '(headline inlinetask org-data)
20529 t)))
20530 (when heading
20531 (unless (or (eq 'inlinetask (org-element-type heading))
20532 (not (org-element-property :contents-begin heading)))
20533 (let ((pos (point)))
20534 (goto-char (org-element-property :contents-begin heading))
20535 (if (re-search-forward
20536 org-outline-regexp-bol
20537 (org-element-property :end heading)
20538 t)
20539 (progn (goto-char (match-beginning 0)) t)
20540 (goto-char pos) nil)))))
20541 (let (level (pos (point)) (re org-outline-regexp-bol))
20542 (when (org-back-to-heading-or-point-min t)
20543 (setq level (org-outline-level))
20544 (forward-char 1)
20545 (if (and (re-search-forward re nil t) (> (org-outline-level) level))
20546 (progn (goto-char (match-beginning 0)) t)
20547 (goto-char pos) nil)))))
2069920548
2070020549 (defun org-get-next-sibling ()
2070120550 "Move to next heading of the same level, and return point.
2072120570 (unless (< (funcall outline-level) level)
2072220571 (point)))))
2072320572
20724 (defun org-end-of-subtree (&optional invisible-ok to-heading)
20725 "Goto to the end of a subtree."
20573 (defun org-end-of-subtree (&optional invisible-ok to-heading element)
20574 "Goto to the end of a subtree at point or for ELEMENT heading."
2072620575 ;; This contains an exact copy of the original function, but it uses
2072720576 ;; `org-back-to-heading-or-point-min', to make it work also in invisible
2072820577 ;; trees and before first headline. And is uses an invisible-ok argument.
2073020579 ;; Furthermore, when used inside Org, finding the end of a large subtree
2073120580 ;; with many children and grandchildren etc, this can be much faster
2073220581 ;; than the outline version.
20733 (org-back-to-heading-or-point-min invisible-ok)
20734 (let ((first t)
20735 (level (funcall outline-level)))
20736 (cond ((= level 0)
20737 (goto-char (point-max)))
20738 ((and (derived-mode-p 'org-mode) (< level 1000))
20739 ;; A true heading (not a plain list item), in Org
20740 ;; This means we can easily find the end by looking
20741 ;; only for the right number of stars. Using a regexp to do
20742 ;; this is so much faster than using a Lisp loop.
20743 (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
20744 (forward-char 1)
20745 (and (re-search-forward re nil 'move) (beginning-of-line 1))))
20746 (t
20747 ;; something else, do it the slow way
20748 (while (and (not (eobp))
20749 (or first (> (funcall outline-level) level)))
20750 (setq first nil)
20751 (outline-next-heading))))
20752 (unless to-heading
20582 (if element
20583 (setq element (org-element-lineage element '(headline inlinetask) 'include-self))
20584 (org-back-to-heading-or-point-min invisible-ok))
20585 (unless (and (org-element--cache-active-p)
20586 (let ((cached (or element (org-element-at-point nil t))))
20587 (and cached
20588 (eq 'headline (org-element-type cached))
20589 (goto-char (org-element-property
20590 :end cached)))))
20591 (let ((first t)
20592 (level (funcall outline-level)))
20593 (cond ((= level 0)
20594 (goto-char (point-max)))
20595 ((and (derived-mode-p 'org-mode) (< level 1000))
20596 ;; A true heading (not a plain list item), in Org
20597 ;; This means we can easily find the end by looking
20598 ;; only for the right number of stars. Using a regexp to do
20599 ;; this is so much faster than using a Lisp loop.
20600 (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
20601 (forward-char 1)
20602 (and (re-search-forward re nil 'move) (beginning-of-line 1))))
20603 (t
20604 ;; something else, do it the slow way
20605 (while (and (not (eobp))
20606 (or first (> (funcall outline-level) level)))
20607 (setq first nil)
20608 (outline-next-heading))))))
20609 (unless to-heading
20610 (when (memq (preceding-char) '(?\n ?\^M))
20611 ;; Go to end of line before heading
20612 (forward-char -1)
2075320613 (when (memq (preceding-char) '(?\n ?\^M))
20754 ;; Go to end of line before heading
20755 (forward-char -1)
20756 (when (memq (preceding-char) '(?\n ?\^M))
20757 ;; leave blank line before heading
20758 (forward-char -1)))))
20614 ;; leave blank line before heading
20615 (forward-char -1))))
2075920616 (point))
2076020617
2076120618 (defun org-end-of-meta-data (&optional full)
2081520672 (if backward? (goto-char (point-min)) (outline-next-heading))
2081620673 (org-back-to-heading invisible-ok)
2081720674 (unless backward? (end-of-line)) ;do not match current headline
20818 (let ((level (- (match-end 0) (match-beginning 0) 1))
20675 (let ((level (org-current-level))
2081920676 (f (if backward? #'re-search-backward #'re-search-forward))
2082020677 (count (if arg (abs arg) 1))
2082120678 (result (point)))
2085420711 (end-of-line))
2085520712 (while (and (< arg 0) (re-search-backward regexp nil :move))
2085620713 (unless (bobp)
20857 (while (pcase (get-char-property-and-overlay (point) 'invisible)
20858 (`(outline . ,o)
20859 (goto-char (overlay-start o))
20860 (re-search-backward regexp nil :move))
20861 (_ nil))))
20714 (when (org-fold-folded-p)
20715 (goto-char (org-fold-previous-visibility-change))
20716 (unless (looking-at-p regexp)
20717 (re-search-backward regexp nil :mode))))
2086220718 (cl-incf arg))
20863 (while (and (> arg 0) (re-search-forward regexp nil t))
20864 (while (pcase (get-char-property-and-overlay (point) 'invisible)
20865 (`(outline . ,o)
20866 (goto-char (overlay-end o))
20867 (re-search-forward regexp nil :move))
20868 (_
20869 (end-of-line)
20870 nil))) ;leave the loop
20719 (while (and (> arg 0) (re-search-forward regexp nil :move))
20720 (when (org-fold-folded-p)
20721 (goto-char (org-fold-next-visibility-change))
20722 (skip-chars-forward " \t\n")
20723 (end-of-line))
2087120724 (cl-decf arg))
2087220725 (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
2087320726
2092420777 (cl-decf arg))
2092520778 ;; Return moves left.
2092620779 arg))
20780
20781 (defvar org--single-lines-list-is-paragraph t
20782 "Treat plain lists with single line items as a whole paragraph")
2092720783
2092820784 (defun org--paragraph-at-point ()
2092920785 "Return paragraph, or equivalent, element at point.
2098620842 (while (memq (org-element-type (org-element-property :parent l))
2098720843 '(item plain-list))
2098820844 (setq l (org-element-property :parent l)))
20989 (and l
20845 (and l org--single-lines-list-is-paragraph
2099020846 (org-with-point-at (org-element-property :post-affiliated l)
2099120847 (forward-line (length (org-element-property :structure l)))
2099220848 (= (point) (org-element-property :contents-end l)))
2101220868 (cond
2101320869 ((eobp) nil)
2101420870 ;; When inside a folded part, move out of it.
21015 ((pcase (get-char-property-and-overlay (point) 'invisible)
21016 (`(,(or `outline `org-hide-block) . ,o)
21017 (goto-char (overlay-end o))
21018 (forward-line)
21019 t)
21020 (_ nil)))
20871 ((when (org-invisible-p nil t)
20872 (goto-char (cdr (org-fold-get-region-at-point)))
20873 (forward-line)
20874 t))
2102120875 (t
2102220876 (let* ((element (org--paragraph-at-point))
2102320877 (type (org-element-type element))
2102920883 (forward-char)
2103020884 (org--forward-paragraph-once))
2103120885 ;; If the element is folded, skip it altogether.
21032 ((pcase (org-with-point-at post-affiliated
21033 (get-char-property-and-overlay (line-end-position)
21034 'invisible))
21035 (`(,(or `outline `org-hide-block) . ,o)
21036 (goto-char (overlay-end o))
21037 (forward-line)
21038 t)
21039 (_ nil)))
20886 ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
20887 (goto-char (cdr (org-fold-get-region-at-point
20888 nil
20889 (org-with-point-at post-affiliated
20890 (line-end-position)))))
20891 (forward-line)
20892 t))
2104020893 ;; At a greater element, move inside.
2104120894 ((and contents-begin
2104220895 (> contents-begin (point))
2108820941 (save-excursion (skip-chars-backward " \t\n") (bobp)))
2108920942 (goto-char (point-min)))
2109020943 ;; When inside a folded part, move out of it.
21091 ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
21092 (`(,(or `outline `org-hide-block) . ,o)
21093 (goto-char (1- (overlay-start o)))
21094 (org--backward-paragraph-once)
21095 t)
21096 (_ nil)))
20944 ((when (org-invisible-p (1- (point)) t)
20945 (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
20946 (org--backward-paragraph-once)
20947 t))
2109720948 (t
2109820949 (let* ((element (org--paragraph-at-point))
2109920950 (type (org-element-type element))
2111920970 (cond
2112020971 ;; There is a blank line above. Move there.
2112120972 ((and (org-previous-line-empty-p)
21122 (let ((lep (line-end-position 0)))
21123 ;; When the first headline start at point 2, don't choke while
21124 ;; checking with `org-invisible-p'.
21125 (or (= lep 1)
21126 (not (org-invisible-p (1- (line-end-position 0)))))))
20973 (not (org-invisible-p (1- (line-end-position 0)))))
2112720974 (forward-line -1))
2112820975 ;; At the beginning of the first element within a greater
2112920976 ;; element. Move to the beginning of the greater element.
21130 ((and parent (= begin (org-element-property :contents-begin parent)))
20977 ((and parent
20978 (not (eq 'section (org-element-type parent)))
20979 (= begin (org-element-property :contents-begin parent)))
2113120980 (funcall reach (org-element-property :begin parent)))
2113220981 ;; Since we have to move anyway, find the beginning
2113320982 ;; position of the element above.
2114020989 (org-with-point-at begin (not (bolp))))
2114120990 (funcall reach (progn (goto-char begin) (line-beginning-position))))
2114220991 ;; If the element is folded, skip it altogether.
21143 ((org-with-point-at post-affiliated
21144 (org-invisible-p (line-end-position) t))
20992 ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
2114520993 (funcall reach begin))
2114620994 ;; At the end of a greater element, move inside.
2114720995 ((and contents-end
2123621084 (unless (org-up-heading-safe) (user-error "No surrounding element"))
2123721085 (let* ((elem (org-element-at-point))
2123821086 (parent (org-element-property :parent elem)))
21239 (if parent (goto-char (org-element-property :begin parent))
21087 ;; Skip sections
21088 (when (eq 'section (org-element-type parent))
21089 (setq parent (org-element-property :parent parent)))
21090 (if (and parent
21091 (not (eq (org-element-type parent) 'org-data)))
21092 (goto-char (org-element-property :begin parent))
2124021093 (if (org-with-limited-levels (org-before-first-heading-p))
2124121094 (user-error "No surrounding element")
2124221095 (org-with-limited-levels (org-back-to-heading)))))))
2147221325
2147321326 ;;; Finish up
2147421327
21475 (add-hook 'org-mode-hook ;remove overlays when changing major mode
21328 (add-hook 'org-mode-hook ;remove folds when changing major mode
2147621329 (lambda () (add-hook 'change-major-mode-hook
21477 'org-show-all 'append 'local)))
21330 'org-fold-show-all 'append 'local)))
2147821331
2147921332 (provide 'org)
2148021333
00 ;;; ox-ascii.el --- ASCII Back-End for Org Export Engine -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2012-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2012-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
5 ;; Maintainer: Nicolas Goaziou <n.goaziou at gmail dot com>
5 ;; Maintainer: Nicolas Goaziou <mail@nicolasgoaziou.fr>
66 ;; Keywords: outlines, hypermedia, calendar, wp
77
88 ;; This file is part of GNU Emacs.
2727
2828 ;;; Code:
2929
30 (require 'org-macs)
31 (org-assert-version)
32
3033 (require 'ox)
3134 (require 'ox-publish)
3235 (require 'cl-lib)
3437 ;;; Function Declarations
3538
3639 (declare-function aa2u "ext:ascii-art-to-unicode" ())
40 (declare-function org-at-heading-p "org" (&optional _))
41 (declare-function org-back-to-heading "org" (&optional invisible-ok))
42 (declare-function org-next-visible-heading "org" (arg))
3743
3844 ;;; Define Back-End
3945 ;;
455461 among `left', `center', `right' or `full'. A nil value is
456462 equivalent to `left'. For a justification that doesn't also fill
457463 string, see `org-ascii--justify-lines' and
458 `org-ascii--justify-block'.
464 `org-ascii--justify-element'.
459465
460466 Return nil if S isn't a string."
461467 (when (stringp s)
947953 (when description
948954 (let ((dest (if (equal type "fuzzy")
949955 (org-export-resolve-fuzzy-link link info)
950 (org-export-resolve-id-link link info))))
951 (concat
952 (org-ascii--fill-string
953 (format "[%s] %s" anchor (org-ascii--describe-datum dest info))
954 width info)
955 "\n\n"))))
956 ;; Ignore broken links. On broken link,
957 ;; `org-export-resolve-id-link' will throw an
958 ;; error and we will return nil.
959 (condition-case nil
960 (org-export-resolve-id-link link info)
961 (org-link-broken nil)))))
962 (when dest
963 (concat
964 (org-ascii--fill-string
965 (format "[%s] %s" anchor (org-ascii--describe-datum dest info))
966 width info)
967 "\n\n")))))
956968 ;; Do not add a link that cannot be resolved and doesn't have
957969 ;; any description: destination is already visible in the
958970 ;; paragraph.
15361548 keyword info)))))
15371549
15381550
1539 ;;;; Latex Environment
1551 ;;;; LaTeX Environment
15401552
15411553 (defun org-ascii-latex-environment (latex-environment _contents info)
15421554 "Transcode a LATEX-ENVIRONMENT element from Org to ASCII.
15481560 latex-environment info)))
15491561
15501562
1551 ;;;; Latex Fragment
1563 ;;;; LaTeX Fragment
15521564
15531565 (defun org-ascii-latex-fragment (latex-fragment _contents info)
15541566 "Transcode a LATEX-FRAGMENT object from Org to ASCII.
19281940 (org-export-table-cell-alignment table-cell info)))))
19291941 (setq contents
19301942 (concat data
1931 (make-string (- width (string-width (or data ""))) ?\s))))
1943 ;; FIXME: If CONTENTS was transformed by filters,
1944 ;; the whole width calculation can be wrong.
1945 ;; At least, make sure that we do not throw error
1946 ;; when CONTENTS is larger than width.
1947 (make-string (max 0 (- width (string-width (or data "")))) ?\s))))
19321948 ;; Return cell.
19331949 (concat (format " %s " contents)
19341950 (when (memq 'right (org-export-table-cell-borders table-cell info))
00 ;;; ox-beamer.el --- Beamer Back-End for Org Export Engine -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2007-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2007-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik AT gmail DOT com>
55 ;; Nicolas Goaziou <n.goaziou AT gmail DOT com>
6 ;; Maintainer: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Maintainer: Nicolas Goaziou <mail@nicolasgoaziou.fr>
77 ;; Keywords: org, wp, tex
88
99 ;; This file is part of GNU Emacs.
2828 ;; document. See Org manual for more information.
2929
3030 ;;; Code:
31
32 (require 'org-macs)
33 (org-assert-version)
3134
3235 (require 'cl-lib)
3336 (require 'ox-latex)
733736 (or (org-export-custom-protocol-maybe link contents 'beamer info)
734737 ;; Fall-back to LaTeX export. However, prefer "\hyperlink" over
735738 ;; "\hyperref" since the former handles overlay specifications.
736 (let ((latex-link (org-export-with-backend 'latex link contents info)))
737 (if (string-match "\\`\\\\hyperref\\[\\(.*?\\)\\]" latex-link)
738 (replace-match
739 (format "\\\\hyperlink%s{\\1}"
740 (or (org-beamer--element-has-overlay-p link) ""))
741 nil nil latex-link)
742 latex-link))))
739 (let* ((latex-link (org-export-with-backend 'latex link contents info))
740 (parent (org-export-get-parent-element link))
741 (attr (org-export-read-attribute :attr_beamer parent))
742 (overlay (plist-get attr :overlay)))
743 (cond ((string-match "\\`\\\\hyperref\\[\\(.*?\\)\\]" latex-link)
744 (replace-match
745 (format "\\\\hyperlink%s{\\1}"
746 (or (org-beamer--element-has-overlay-p link) ""))
747 nil nil latex-link))
748 ((string-match "\\\\include\\(graphics\\|svg\\)\\([[{]?\\)" latex-link)
749 ;; Check for overlay specification and insert if
750 ;; present.
751 (replace-match
752 (format "\\\\include\\1%s\\2"
753 (if overlay overlay ""))
754 nil nil latex-link))
755 (t latex-link)))))
743756
744757
745758 ;;;; Plain List
856869 (let ((template (plist-get info :latex-hyperref-template)))
857870 (and (stringp template)
858871 (format-spec template (org-latex--format-spec info))))
872 ;; engrave-faces-latex preamble
873 (when (and (eq org-latex-src-block-backend 'engraved)
874 (org-element-map (plist-get info :parse-tree)
875 '(src-block inline-src-block) #'identity
876 info t))
877 (org-latex-generate-engraved-preamble info))
859878 ;; Document start.
860879 "\\begin{document}\n\n"
861880 ;; Title command.
00 ;;; ox-html.el --- HTML Back-End for Org Export Engine -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2011-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2011-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
55 ;; Jambunathan K <kjambunathan at gmail dot com>
6 ;; Maintainer: TEC <tecosaur@gmail.com>
6 ;; Maintainer: TEC <orgmode@tec.tecosaur.net>
77 ;; Keywords: outlines, hypermedia, calendar, wp
88
99 ;; This file is part of GNU Emacs.
2929 ;;; Code:
3030
3131 ;;; Dependencies
32
33 (require 'org-macs)
34 (org-assert-version)
3235
3336 (require 'cl-lib)
3437 (require 'format-spec)
4245 (declare-function org-id-find-id-file "org-id" (id))
4346 (declare-function htmlize-region "ext:htmlize" (beg end))
4447 (declare-function mm-url-decode-entities "mm-url" ())
48 (declare-function org-at-heading-p "org" (&optional _))
49 (declare-function org-back-to-heading "org" (&optional invisible-ok))
50 (declare-function org-next-visible-heading "org" (arg))
4551
4652 (defvar htmlize-css-name-prefix)
4753 (defvar htmlize-output-type)
210216 ("xhtml-frameset" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\"
211217 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">")
212218 ("xhtml-11" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"
213 \"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd\">")
219 \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">")
214220
215221 ("html5" . "<!DOCTYPE html>")
216222 ("xhtml5" . "<!DOCTYPE html>"))
441447 { font-size: 10px; font-weight: bold; white-space: nowrap; }
442448 .org-info-js_search-highlight
443449 { background-color: #ffff00; color: #000000; font-weight: bold; }
444 .org-svg { width: 90%; }
450 .org-svg { }
445451 </style>"
446452 "The default style specification for exported HTML files.
447453 You can use `org-html-head' and `org-html-head-extra' to add to
832838 (recognized by the extension \".org\") should become links to the corresponding
833839 HTML file, assuming that the linked Org file will also be converted to HTML.
834840
841 Links to \"file.org.gpg\" are also converted.
842
835843 When nil, the links still point to the plain \".org\" file."
836844 :group 'org-export-html
837845 :type 'boolean)
888896 in all modes you want. Then, use the command
889897 `\\[org-html-htmlize-generate-css]' to extract class definitions."
890898 :group 'org-export-html
891 :type '(choice (const css) (const inline-css) (const nil)))
899 :type '(choice (const css) (const inline-css) (const nil))
900 :safe #'symbolp)
892901
893902 (defcustom org-html-htmlize-font-prefix "org-"
894903 "The prefix for CSS class names for htmlize font specifications."
11571166 ;;;; Template :: Mathjax
11581167
11591168 (defcustom org-html-mathjax-options
1160 '((path "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML" )
1161 (scale "100")
1169 '((path "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js")
1170 (scale 1.0)
11621171 (align "center")
1163 (font "TeX")
1164 (linebreaks "false")
1165 (autonumber "AMS")
1172 (font "mathjax-modern")
1173 (overflow "overflow")
1174 (tags "ams")
11661175 (indent "0em")
11671176 (multlinewidth "85%")
11681177 (tagindent ".8em")
11691178 (tagside "right"))
11701179 "Options for MathJax setup.
11711180
1172 Alist of the following elements. All values are strings.
1173
1174 path The path to MathJax.
1181 Alist of the following elements.
1182
1183 path The path to MathJax version 3 or later.
11751184 scale Scaling with HTML-CSS, MathML and SVG output engines.
11761185 align How to align display math: left, center, or right.
1177 font The font to use with HTML-CSS and SVG output. As of MathJax 2.5
1178 the following values are understood: \"TeX\", \"STIX-Web\",
1179 \"Asana-Math\", \"Neo-Euler\", \"Gyre-Pagella\",
1180 \"Gyre-Termes\", and \"Latin-Modern\".
1186 font The font to use with HTML-CSS and SVG output. Needs
1187 MathJax version 4+. MathJax 4 provides 11 fonts:
1188 \"mathjax-modern\" Latin-Modern font, default in MathJax 4+
1189 \"mathjax-asana\" Asana-Math font
1190 \"mathjax-bonum\" Gyre Bonum font
1191 \"mathjax-dejavu\" Gyre DejaVu font
1192 \"mathjax-pagella\" Gyre Pagella font
1193 \"mathjax-schola\" Gyre Schola font
1194 \"mathjax-termes\" Gyre Termes font
1195 \"mathjax-stix2\" STIX2 font
1196 \"mathjax-fira\" Fira and Fira-Math fonts
1197 \"mathjax-euler\" Neo Euler font that extends Latin-Modern
1198 \"mathjax-tex\" The original MathJax TeX font
1199 overflow How to break displayed equations when too large. Needs
1200 MathJax 4 or newer. Supported options include
1201 \"overflow\", \"scale\", \"scroll\", \"truncate\",
1202 \"linebreak\", and \"elide\".
11811203 linebreaks Let MathJax perform automatic linebreaks. Valid values
11821204 are \"true\" and \"false\".
1183 indent If align is not center, how far from the left/right side?
1184 Valid values are \"left\" and \"right\"
1205 indent If align is not center, how far from the left/right side? For
1206 example, \"1em\".
11851207 multlinewidth The width of the multline environment.
1186 autonumber How to number equations. Valid values are \"None\",
1187 \"all\" and \"AMS Math\".
1208 tags How to number equations. Valid values are \"none\",
1209 \"all\" and \"ams\".
11881210 tagindent The amount tags are indented.
11891211 tagside Which side to show tags/labels on. Valid values are
11901212 \"left\" and \"right\"
11911213
1192 You can also customize this for each buffer, using something like
1193
1194 #+HTML_MATHJAX: align: left indent: 5em tagside: left font: Neo-Euler
1214 You can also customize this for some buffer, using something like
1215
1216 #+HTML_MATHJAX: align: left indent: 5em tagside: left
11951217
11961218 For further information about MathJax options, see the MathJax documentation:
11971219
1198 https://docs.mathjax.org/"
1199 :group 'org-export-html
1200 :package-version '(Org . "8.3")
1220 https://docs.mathjax.org/
1221
1222 To maintain compatibility with pre-9.6 Org that used MathJax 2,
1223 the following conversions take place.
1224
1225 The legacy \"autonumber\" option, with the value \"AMS\",
1226 \"None\", or \"All\", becomes the \"tags\" option set to the
1227 value \"ams\", \"none\", or \"all\", respectively.
1228
1229 Any legacy values of the \"scale\" option, specified as
1230 percentage strings, become converted to unit-interval numbers.
1231 For example, a legacy scale of \"150\" becomes a scale of 1.5.
1232
1233 The legacy \"linebreaks\" option, with the value \"true\" or
1234 \"false\", becomes the \"overflow\" option set to the value
1235 \"linebreak\" or \"overflow\", respectively.
1236
1237 The legacy values of the \"font\" option, namely \"TeX\",
1238 \"STIX-Web\", \"Asana-Math\", \"Neo-Euler\", \"Gyre-Pagella\",
1239 \"Gyre-Termes\", \"Latin-Modern\", become converted to the
1240 corresponding MathJax 4+ font names.
1241
1242 Legacy options and values always take precedence.
1243 "
1244 :group 'org-export-html
1245 :package-version '(Org . "9.6")
12011246 :type '(list :greedy t
12021247 (list :tag "path (the path from where to load MathJax.js)"
12031248 (const :format " " path) (string))
12041249 (list :tag "scale (scaling for the displayed math)"
1205 (const :format " " scale) (string))
1250 (const :format " " scale) (float))
12061251 (list :tag "align (alignment of displayed equations)"
12071252 (const :format " " align) (string))
1208 (list :tag "font (used to display math)"
1209 (const :format " " font)
1210 (choice (const "TeX")
1211 (const "STIX-Web")
1212 (const "Asana-Math")
1213 (const "Neo-Euler")
1214 (const "Gyre-Pagella")
1215 (const "Gyre-Termes")
1216 (const "Latin-Modern")))
1217 (list :tag "linebreaks (automatic line-breaking)"
1218 (const :format " " linebreaks)
1219 (choice (const "true")
1220 (const "false")))
1221 (list :tag "autonumber (when should equations be numbered)"
1222 (const :format " " autonumber)
1223 (choice (const "AMS")
1224 (const "None")
1225 (const "All")))
1253 (list :tag "font (used to typeset math)"
1254 (const :format " " font)
1255 (choice (const "mathjax-modern")
1256 (const "mathjax-asana")
1257 (const "mathjax-bonum")
1258 (const "mathjax-dejavu")
1259 (const "mathjax-pagella")
1260 (const "mathjax-schola")
1261 (const "mathjax-termes")
1262 (const "mathjax-stix2")
1263 (const "mathjax-fira")
1264 (const "mathjax-euler")
1265 (const "mathjax-tex")))
1266 (list :tag "overflow (how to break displayed math)"
1267 (const :format " " overflow)
1268 (choice (const "overflow")
1269 (const "scale")
1270 (const "scroll")
1271 (const "truncate")
1272 (const "linebreak")
1273 (const "elide")))
1274 (list :tag "tags (whether equations are numbered and how)"
1275 (const :format " " tags)
1276 (choice (const "ams")
1277 (const "none")
1278 (const "all")))
12261279 (list :tag "indent (indentation with left or right alignment)"
12271280 (const :format " " indent) (string))
12281281 (list :tag "multlinewidth (width to use for the multline environment)"
12351288 (const "right")))))
12361289
12371290 (defcustom org-html-mathjax-template
1238 "<script type=\"text/x-mathjax-config\">
1239 MathJax.Hub.Config({
1240 displayAlign: \"%ALIGN\",
1241 displayIndent: \"%INDENT\",
1242
1243 \"HTML-CSS\": { scale: %SCALE,
1244 linebreaks: { automatic: \"%LINEBREAKS\" },
1245 webFont: \"%FONT\"
1246 },
1247 SVG: {scale: %SCALE,
1248 linebreaks: { automatic: \"%LINEBREAKS\" },
1249 font: \"%FONT\"},
1250 NativeMML: {scale: %SCALE},
1251 TeX: { equationNumbers: {autoNumber: \"%AUTONUMBER\"},
1252 MultLineWidth: \"%MULTLINEWIDTH\",
1253 TagSide: \"%TAGSIDE\",
1254 TagIndent: \"%TAGINDENT\"
1255 }
1256 });
1291 "<script>
1292 window.MathJax = {
1293 tex: {
1294 ams: {
1295 multlineWidth: '%MULTLINEWIDTH'
1296 },
1297 tags: '%TAGS',
1298 tagSide: '%TAGSIDE',
1299 tagIndent: '%TAGINDENT'
1300 },
1301 chtml: {
1302 scale: %SCALE,
1303 displayAlign: '%ALIGN',
1304 displayIndent: '%INDENT'
1305 },
1306 svg: {
1307 scale: %SCALE,
1308 displayAlign: '%ALIGN',
1309 displayIndent: '%INDENT'
1310 },
1311 output: {
1312 font: '%FONT',
1313 displayOverflow: '%OVERFLOW'
1314 }
1315 };
12571316 </script>
1258 <script src=\"%PATH\"></script>"
1317
1318 <script
1319 id=\"MathJax-script\"
1320 async
1321 src=\"%PATH\">
1322 </script>"
12591323 "The MathJax template. See also `org-html-mathjax-options'."
12601324 :group 'org-export-html
12611325 :type 'string)
12671331
12681332 When set to `auto', check against the
12691333 `org-export-with-author/email/creator/date' variables to set the
1270 content of the postamble. When set to a string, use this string
1271 as the postamble. When t, insert a string as defined by the
1272 formatting string in `org-html-postamble-format'.
1334 content of the postamble. When t, insert a string as defined by the
1335 formatting string in `org-html-postamble-format'. When set to a
1336 string, use this formatting string instead (see
1337 `org-html-postamble-format' for an example of such a formatting
1338 string).
12731339
12741340 When set to a function, apply this function and insert the
12751341 returned string. The function takes the property list of export
18801946 ;; empty, which is invalid.
18811947 (title (if (org-string-nw-p title) title "&lrm;"))
18821948 (charset (or (and org-html-coding-system
1883 (fboundp 'coding-system-get)
18841949 (symbol-name
18851950 (coding-system-get org-html-coding-system
18861951 'mime-charset)))
19372002 "Insert the user setup into the mathjax template.
19382003 INFO is a plist used as a communication channel."
19392004 (when (and (memq (plist-get info :with-latex) '(mathjax t))
1940 (org-element-map (plist-get info :parse-tree)
1941 '(latex-fragment latex-environment) #'identity info t nil t))
2005 (org-element-map (plist-get info :parse-tree)
2006 '(latex-fragment latex-environment) #'identity info t nil t))
19422007 (let ((template (plist-get info :html-mathjax-template))
1943 (options (plist-get info :html-mathjax-options))
1944 (in-buffer (or (plist-get info :html-mathjax) "")))
2008 (options (let ((options (plist-get info :html-mathjax-options)))
2009 ;; If the user customized some legacy option, set
2010 ;; the corresponding new option to nil, so that
2011 ;; the legacy user choice overrides the default.
2012 ;; Otherwise, the user did not set the legacy
2013 ;; option, in which case still set the legacy
2014 ;; option but to no value, so that the code can
2015 ;; find its in-buffer value, if set.
2016 `((,(if (plist-member options 'autonumber)
2017 'tags 'autonumber)
2018 nil)
2019 (,(if (plist-member options 'linebreaks)
2020 'overflow 'linebreaks)
2021 nil)
2022 ,@options)))
2023 (in-buffer (or (plist-get info :html-mathjax) "")))
19452024 (dolist (e options (org-element-normalize-string template))
1946 (let ((name (car e))
1947 (val (nth 1 e)))
1948 (when (string-match (concat "\\<" (symbol-name name) ":") in-buffer)
1949 (setq val
1950 (car (read-from-string (substring in-buffer (match-end 0))))))
1951 (unless (stringp val) (setq val (format "%s" val)))
1952 (while (string-match (concat "%" (upcase (symbol-name name)))
1953 template)
1954 (setq template (replace-match val t t template))))))))
2025 (let ((symbol (car e))
2026 (value (nth 1 e)))
2027 (when (string-match (concat "\\<" (symbol-name symbol) ":")
2028 in-buffer)
2029 (setq value
2030 (car (split-string (substring in-buffer
2031 (match-end 0))))))
2032 (when value
2033 (pcase symbol
2034 (`font
2035 (when-let
2036 ((value-new
2037 (pcase value
2038 ("TeX" "mathjax-tex")
2039 ("STIX-Web" "mathjax-stix2")
2040 ("Asana-Math" "mathjax-asana")
2041 ("Neo-Euler" "mathjax-euler")
2042 ("Gyre-Pagella" "mathjax-pagella")
2043 ("Gyre-Termes" "mathjax-termes")
2044 ("Latin-Modern" "mathjax-modern"))))
2045 (setq value value-new)))
2046 (`linebreaks
2047 (org-display-warning
2048 "Converting legacy MathJax option: linebreaks")
2049 (setq symbol 'overflow
2050 value (if (string= value "true")
2051 "linebreak"
2052 "overflow")))
2053 (`scale
2054 (when (stringp value)
2055 (let ((value-maybe (string-to-number value)))
2056 (setq value
2057 (if (= value-maybe 0)
2058 (progn
2059 (org-display-warning
2060 (format "Non-numerical MathJax scale: %s"
2061 value))
2062 1.0)
2063 value-maybe))))
2064 (when (>= value 10)
2065 (setq value
2066 (let ((value-new (/ (float value) 100)))
2067 (org-display-warning
2068 (format "Converting legacy MathJax scale: %s to %s"
2069 value
2070 value-new))
2071 value-new))))
2072 (`autonumber
2073 (org-display-warning
2074 "Converting legacy MathJax option: autonumber")
2075 (setq symbol 'tags
2076 value (downcase value))))
2077 (while (string-match (format "\\(%%%s\\)[^A-Z]"
2078 (upcase (symbol-name symbol)))
2079 template)
2080 (setq template
2081 (replace-match (format "%s" value)
2082 t
2083 t template 1)))))))))
19552084
19562085 (defun org-html-format-spec (info)
19572086 "Return format specification for preamble and postamble.
19852114 (if (functionp section) (funcall section info)
19862115 (cond
19872116 ((stringp section) (format-spec section spec))
1988 ((eq section 'auto)
2117 ((and (eq section 'auto) (eq type 'postamble))
19892118 (let ((date (cdr (assq ?d spec)))
19902119 (author (cdr (assq ?a spec)))
19912120 (email (cdr (assq ?e spec)))
20672196 (format "%s\n"
20682197 (format decl
20692198 (or (and org-html-coding-system
2070 (fboundp 'coding-system-get)
2199 ;; FIXME: Use Emacs 22 style here, see `coding-system-get'.
20712200 (coding-system-get org-html-coding-system 'mime-charset))
20722201 "iso-8859-1"))))))
20732202 (org-html-doctype info)
22212350 (funcall lang-mode)
22222351 (insert code)
22232352 ;; Fontify buffer.
2224 (org-font-lock-ensure)
2353 (font-lock-ensure)
22252354 ;; Remove formatting on newline characters.
22262355 (save-excursion
22272356 (let ((beg (point-min))
28392968 ((string= "listings" value) (org-html-list-of-listings info))
28402969 ((string= "tables" value) (org-html-list-of-tables info))))))))
28412970
2842 ;;;; Latex Environment
2971 ;;;; LaTeX Environment
28432972
28442973 (defun org-html-format-latex (latex-frag processing-type info)
28452974 "Format a LaTeX fragment LATEX-FRAG into HTML.
28713000 ;; temporary buffer so that dvipng/imagemagick can properly
28723001 ;; turn the fragment into an image.
28733002 (setq latex-frag (concat latex-header latex-frag))))
2874 (with-temp-buffer
2875 (insert latex-frag)
2876 (org-format-latex cache-relpath nil nil cache-dir nil
2877 "Creating LaTeX Image..." nil processing-type)
2878 (buffer-string))))
3003 (org-export-with-buffer-copy
3004 :to-buffer (get-buffer-create " *Org HTML Export LaTeX*")
3005 :drop-visibility t :drop-narrowing t :drop-contents t
3006 (erase-buffer)
3007 (insert latex-frag)
3008 (org-format-latex cache-relpath nil nil cache-dir nil
3009 "Creating LaTeX Image..." nil processing-type)
3010 (buffer-string))))
28793011
28803012 (defun org-html--wrap-latex-environment (contents _ &optional caption label)
28813013 "Wrap CONTENTS string within appropriate environment for equations.
29083040
29093041 (defun org-html--unlabel-latex-environment (latex-frag)
29103042 "Change environment in LATEX-FRAG string to an unnumbered one.
2911 For instance, change an 'equation' environment to 'equation*'."
3043 For instance, change an `equation' environment to `equation*'."
29123044 (replace-regexp-in-string
29133045 "\\`[ \t]*\\\\begin{\\([^*]+?\\)}"
29143046 "\\1*"
29533085 info caption label)))))
29543086 (t (org-html--wrap-latex-environment latex-frag info caption label)))))
29553087
2956 ;;;; Latex Fragment
3088 ;;;; LaTeX Fragment
29573089
29583090 (defun org-html-latex-fragment (latex-fragment _contents info)
29593091 "Transcode a LATEX-FRAGMENT object from Org to HTML.
30593191 (lambda (raw-path info)
30603192 ;; Treat links to `file.org' as links to `file.html', if
30613193 ;; needed. See `org-html-link-org-files-as-html'.
3062 (cond
3063 ((and (plist-get info :html-link-org-files-as-html)
3064 (string= ".org"
3065 (downcase (file-name-extension raw-path "."))))
3066 (concat (file-name-sans-extension raw-path) dot html-ext))
3067 (t raw-path))))
3194 (save-match-data
3195 (cond
3196 ((and (plist-get info :html-link-org-files-as-html)
3197 (let ((case-fold-search t))
3198 (string-match "\\(.+\\)\\.org\\(?:\\.gpg\\)?$" raw-path)))
3199 (concat (match-string 1 raw-path) dot html-ext))
3200 (t raw-path)))))
30683201 (type (org-element-property :type link))
30693202 (raw-path (org-element-property :path link))
30703203 ;; Ensure DESC really exists, or set it to nil.
32033336 ((org-html-standalone-image-p destination info)
32043337 (org-export-get-ordinal
32053338 (org-element-map destination 'link #'identity info t)
3206 info 'link 'org-html-standalone-image-p))
3339 info '(link) 'org-html-standalone-image-p))
32073340 (t (org-export-get-ordinal
32083341 destination info nil counter-predicate))))
32093342 (desc
00 ;;; ox-icalendar.el --- iCalendar Back-End for Org Export Engine -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2004-2023 Free Software Foundation, Inc.
33
44 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
5 ;; Nicolas Goaziou <n dot goaziou at gmail dot com>
6 ;; Maintainer: Nicolas Goaziou <n.goaziou at gmail dot com>
5 ;; Nicolas Goaziou <mail@nicolasgoaziou.fr>
6 ;; Maintainer: Nicolas Goaziou <mail@nicolasgoaziou.fr>
77 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: https://orgmode.org
8 ;; URL: https://orgmode.org
99
1010 ;; This file is part of GNU Emacs.
1111
3131
3232 ;;; Code:
3333
34 (require 'org-macs)
35 (org-assert-version)
36
3437 (require 'cl-lib)
3538 (require 'org-agenda)
3639 (require 'ox-ascii)
3740 (declare-function org-bbdb-anniv-export-ical "ol-bbdb" nil)
41 (declare-function org-at-heading-p "org" (&optional _))
42 (declare-function org-back-to-heading "org" (&optional invisible-ok))
43 (declare-function org-next-visible-heading "org" (arg))
3844
3945
4046
6470 :group 'org-export-icalendar
6571 :version "24.1"
6672 :type 'integer)
73
74 (defcustom org-icalendar-force-alarm nil
75 "Non-nil means alarm will be created even if is set to zero.
76
77 This overrides default behavior where zero means no alarm. With
78 this set to non-nil and alarm set to zero, alarm will be created
79 and will fire at the event start."
80 :group 'org-export-icalendar
81 :type 'boolean
82 :package-version '(Org . "9.6")
83 :safe #'booleanp)
6784
6885 (defcustom org-icalendar-combined-name "OrgMode"
6986 "Calendar name for the combined iCalendar representing all agenda files."
8299 keyword."
83100 :group 'org-export-icalendar
84101 :type '(repeat (string :tag "Tag")))
102
103 (defcustom org-icalendar-scheduled-summary-prefix "S: "
104 "String prepended to exported scheduled headlines."
105 :group 'org-export-icalendar
106 :type 'string
107 :package-version '(Org . "9.6")
108 :safe #'stringp)
109
110
111 (defcustom org-icalendar-deadline-summary-prefix "DL: "
112 "String prepended to exported headlines with a deadline."
113 :group 'org-export-icalendar
114 :type 'string
115 :package-version '(Org . "9.6")
116 :safe #'stringp)
85117
86118 (defcustom org-icalendar-use-deadline '(event-if-not-todo todo-due)
87119 "Contexts where iCalendar export should use a deadline time stamp.
275307 ;;; Define Back-End
276308
277309 (org-export-define-derived-backend 'icalendar 'ascii
278 :translate-alist '((clock . ignore)
279 (footnote-definition . ignore)
280 (footnote-reference . ignore)
310 :translate-alist '((clock . nil)
311 (footnote-definition . nil)
312 (footnote-reference . nil)
281313 (headline . org-icalendar-entry)
282314 (inner-template . org-icalendar-inner-template)
283 (inlinetask . ignore)
284 (planning . ignore)
285 (section . ignore)
315 (inlinetask . nil)
316 (planning . nil)
317 (section . nil)
286318 (template . org-icalendar-template))
287319 :options-alist
288320 '((:exclude-tags
299331 (:icalendar-store-UID nil nil org-icalendar-store-UID)
300332 (:icalendar-timezone nil nil org-icalendar-timezone)
301333 (:icalendar-use-deadline nil nil org-icalendar-use-deadline)
302 (:icalendar-use-scheduled nil nil org-icalendar-use-scheduled))
334 (:icalendar-use-scheduled nil nil org-icalendar-use-scheduled)
335 (:icalendar-scheduled-summary-prefix nil nil org-icalendar-scheduled-summary-prefix)
336 (:icalendar-deadline-summary-prefix nil nil org-icalendar-deadline-summary-prefix))
303337 :filters-alist
304338 '((:filter-headline . org-icalendar-clear-blank-lines))
305339 :menu-entry
429463 t)))
430464 ;; Convert timestamp into internal time in order to use
431465 ;; `format-time-string' and fix any mistake (i.e. MI >= 60).
432 (encode-time 0 mi h d m y)
466 (org-encode-time 0 mi h d m y)
433467 (and (or (string-equal tz "UTC")
434468 (and (null tz)
435469 with-time-p
597631 ;; "VEVENT" component from scheduled, deadline, or any
598632 ;; timestamp in the entry.
599633 (let ((deadline (org-element-property :deadline entry))
600 (use-deadline (plist-get info :icalendar-use-deadline)))
634 (use-deadline (plist-get info :icalendar-use-deadline))
635 (deadline-summary-prefix (org-icalendar-cleanup-string
636 (plist-get info :icalendar-deadline-summary-prefix))))
601637 (and deadline
602638 (pcase todo-type
603639 (`todo (or (memq 'event-if-todo-not-done use-deadline)
606642 (_ (memq 'event-if-not-todo use-deadline)))
607643 (org-icalendar--vevent
608644 entry deadline (concat "DL-" uid)
609 (concat "DL: " summary) loc desc cat tz class)))
645 (concat deadline-summary-prefix summary)
646 loc desc cat tz class)))
610647 (let ((scheduled (org-element-property :scheduled entry))
611 (use-scheduled (plist-get info :icalendar-use-scheduled)))
648 (use-scheduled (plist-get info :icalendar-use-scheduled))
649 (scheduled-summary-prefix (org-icalendar-cleanup-string
650 (plist-get info :icalendar-scheduled-summary-prefix))))
612651 (and scheduled
613652 (pcase todo-type
614653 (`todo (or (memq 'event-if-todo-not-done use-scheduled)
617656 (_ (memq 'event-if-not-todo use-scheduled)))
618657 (org-icalendar--vevent
619658 entry scheduled (concat "SC-" uid)
620 (concat "S: " summary) loc desc cat tz class)))
659 (concat scheduled-summary-prefix summary)
660 loc desc cat tz class)))
621661 ;; When collecting plain timestamps from a headline and its
622662 ;; title, skip inlinetasks since collection will happen once
623663 ;; ENTRY is one of them.
791831 (let ((alarm-time
792832 (let ((warntime
793833 (org-element-property :APPT_WARNTIME entry)))
794 (if warntime (string-to-number warntime) 0))))
795 (and (or (> alarm-time 0) (> org-icalendar-alarm-time 0))
834 (if warntime (string-to-number warntime) nil))))
835 (and (or (and alarm-time
836 (> alarm-time 0))
837 (> org-icalendar-alarm-time 0)
838 org-icalendar-force-alarm)
796839 (org-element-property :hour-start timestamp)
797840 (format "BEGIN:VALARM
798841 ACTION:DISPLAY
800843 TRIGGER:-P0DT0H%dM0S
801844 END:VALARM\n"
802845 summary
803 (if (zerop alarm-time) org-icalendar-alarm-time alarm-time)))))
804
846 (cond
847 ((and alarm-time org-icalendar-force-alarm) alarm-time)
848 ((and alarm-time (not (zerop alarm-time))) alarm-time)
849 (t org-icalendar-alarm-time))))))
805850
806851 ;;;; Template
807852
823868 (if (not (plist-get info :with-author)) ""
824869 (org-export-data (plist-get info :author) info))
825870 ;; Timezone.
826 (if (org-string-nw-p org-icalendar-timezone) org-icalendar-timezone
827 (cadr (current-time-zone)))
871 (or (org-string-nw-p org-icalendar-timezone) (format-time-string "%Z"))
828872 ;; Description.
829873 (org-export-data (plist-get info :title) info)
830874 contents))
9711015 (org-icalendar--vcalendar
9721016 org-icalendar-combined-name
9731017 user-full-name
974 (or (org-string-nw-p org-icalendar-timezone) (cadr (current-time-zone)))
1018 (or (org-string-nw-p org-icalendar-timezone) (format-time-string "%Z"))
9751019 org-icalendar-combined-description
9761020 contents)))
9771021 (run-hook-with-args 'org-icalendar-after-save-hook file)))
9941038 user-full-name
9951039 ;; Timezone.
9961040 (or (org-string-nw-p org-icalendar-timezone)
997 (cadr (current-time-zone)))
1041 (format-time-string "%Z"))
9981042 ;; Description.
9991043 org-icalendar-combined-description
10001044 ;; Contents.
00 ;;; ox-koma-letter.el --- KOMA Scrlttr2 Back-End for Org Export Engine -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2007-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2007-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <n.goaziou AT gmail DOT com>
55 ;; Alan Schmitt <alan.schmitt AT polytechnique DOT org>
3434 ;; `org-koma-letter-export-to-pdf' ("pdf" file).
3535 ;;
3636 ;; On top of buffer keywords supported by `latex' back-end (see
37 ;; `org-latex-options-alist'), this back-end introduces the following
37 ;; `org-latex-packages-alist'), this back-end introduces the following
3838 ;; keywords:
3939 ;; - CLOSING: see `org-koma-letter-closing',
4040 ;; - FROM_ADDRESS: see `org-koma-letter-from-address',
6565 ;; - from-logo (see `org-koma-letter-use-from-logo')
6666 ;; - email (see `org-koma-letter-use-email')
6767 ;; - place (see `org-koma-letter-use-place')
68 ;; - location (see `org-koma-letter-use-location')
68 ;; - location (see `org-koma-letter-location')
6969 ;; - subject, a list of format options
7070 ;; (see `org-koma-letter-subject-format')
7171 ;; - after-closing-order, a list of the ordering of headings with
163163 ;; (add-to-list 'org-latex-packages-alist '("AUTO" "babel" nil))
164164
165165 ;;; Code:
166
167 (require 'org-macs)
168 (org-assert-version)
166169
167170 (require 'cl-lib)
168171 (require 'ox-latex)
00 ;;; ox-latex.el --- LaTeX Back-End for Org Export Engine -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2011-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2011-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
5 ;; Maintainer: Daniel Fleischer <danflscr@gmail.com>
56 ;; Keywords: outlines, hypermedia, calendar, wp
67
78 ;; This file is part of GNU Emacs.
2526
2627 ;;; Code:
2728
29 (require 'org-macs)
30 (org-assert-version)
31
2832 (require 'cl-lib)
2933 (require 'ox)
3034 (require 'ox-publish)
3539 (defvar org-latex-packages-alist)
3640 (defvar orgtbl-exp-regexp)
3741
42 (declare-function engrave-faces-latex-gen-preamble "ext:engrave-faces-latex")
43 (declare-function engrave-faces-latex-buffer "ext:engrave-faces-latex")
44 (declare-function engrave-faces-latex-gen-preamble-line "ext:engrave-faces-latex")
45 (declare-function engrave-faces-get-theme "ext:engrave-faces")
46
47 (defvar engrave-faces-latex-output-style)
48 (defvar engrave-faces-current-preset-style)
49 (defvar engrave-faces-latex-mathescape)
3850
3951
4052 ;;; Define Back-End
123135 (:latex-default-quote-environment nil nil org-latex-default-quote-environment)
124136 (:latex-default-table-mode nil nil org-latex-default-table-mode)
125137 (:latex-diary-timestamp-format nil nil org-latex-diary-timestamp-format)
138 (:latex-engraved-options nil nil org-latex-engraved-options)
139 (:latex-engraved-preamble nil nil org-latex-engraved-preamble)
140 (:latex-engraved-theme "LATEX_ENGRAVED_THEME" nil org-latex-engraved-theme)
126141 (:latex-footnote-defined-format nil nil org-latex-footnote-defined-format)
127142 (:latex-footnote-separator nil nil org-latex-footnote-separator)
128143 (:latex-format-drawer-function nil nil org-latex-format-drawer-function)
137152 (:latex-inactive-timestamp-format nil nil org-latex-inactive-timestamp-format)
138153 (:latex-inline-image-rules nil nil org-latex-inline-image-rules)
139154 (:latex-link-with-unknown-path-format nil nil org-latex-link-with-unknown-path-format)
140 (:latex-listings nil nil org-latex-listings)
155 (:latex-src-block-backend nil nil org-latex-src-block-backend)
141156 (:latex-listings-langs nil nil org-latex-listings-langs)
142157 (:latex-listings-options nil nil org-latex-listings-options)
143158 (:latex-minted-langs nil nil org-latex-minted-langs)
159174
160175 ;;; Internal Variables
161176
162 (defconst org-latex-babel-language-alist
163 '(("af" . "afrikaans")
164 ("bg" . "bulgarian")
165 ("ca" . "catalan")
166 ("cs" . "czech")
167 ("cy" . "welsh")
168 ("da" . "danish")
169 ("de" . "germanb")
170 ("de-at" . "naustrian")
171 ("de-de" . "ngerman")
172 ("el" . "greek")
173 ("en" . "english")
174 ("en-au" . "australian")
175 ("en-ca" . "canadian")
176 ("en-gb" . "british")
177 ("en-ie" . "irish")
178 ("en-nz" . "newzealand")
179 ("en-us" . "american")
180 ("es" . "spanish")
181 ("et" . "estonian")
182 ("eu" . "basque")
183 ("fi" . "finnish")
184 ("fr" . "french")
185 ("fr-ca" . "canadien")
186 ("gl" . "galician")
187 ("hr" . "croatian")
188 ("hu" . "hungarian")
189 ("id" . "indonesian")
190 ("is" . "icelandic")
191 ("it" . "italian")
192 ("la" . "latin")
193 ("ms" . "malay")
194 ("nl" . "dutch")
195 ("nb" . "norsk")
196 ("nn" . "nynorsk")
197 ("no" . "norsk")
198 ("pl" . "polish")
199 ("pt" . "portuguese")
200 ("pt-br" . "brazilian")
201 ("ro" . "romanian")
202 ("ru" . "russian")
203 ("sa" . "sanskrit")
204 ("sb" . "uppersorbian")
205 ("sk" . "slovak")
206 ("sl" . "slovene")
207 ("sq" . "albanian")
208 ("sr" . "serbian")
209 ("sv" . "swedish")
210 ("ta" . "tamil")
211 ("tr" . "turkish")
212 ("uk" . "ukrainian"))
213 "Alist between language code and corresponding Babel option.")
214
215 (defconst org-latex-polyglossia-language-alist
216 '(("am" "amharic")
217 ("ar" "arabic")
218 ("ast" "asturian")
219 ("bg" "bulgarian")
220 ("bn" "bengali")
221 ("bo" "tibetan")
222 ("br" "breton")
223 ("ca" "catalan")
224 ("cop" "coptic")
225 ("cs" "czech")
226 ("cy" "welsh")
227 ("da" "danish")
228 ("de" "german" "german")
229 ("de-at" "german" "austrian")
230 ("de-de" "german" "german")
231 ("dsb" "lsorbian")
232 ("dv" "divehi")
233 ("el" "greek")
234 ("en" "english" "usmax")
235 ("en-au" "english" "australian")
236 ("en-gb" "english" "uk")
237 ("en-nz" "english" "newzealand")
238 ("en-us" "english" "usmax")
239 ("eo" "esperanto")
240 ("es" "spanish")
241 ("et" "estonian")
242 ("eu" "basque")
243 ("fa" "farsi")
244 ("fi" "finnish")
245 ("fr" "french")
246 ("fu" "friulan")
247 ("ga" "irish")
248 ("gd" "scottish")
249 ("gl" "galician")
250 ("he" "hebrew")
251 ("hi" "hindi")
252 ("hr" "croatian")
253 ("hsb" "usorbian")
254 ("hu" "magyar")
255 ("hy" "armenian")
256 ("ia" "interlingua")
257 ("id" "bahasai")
258 ("is" "icelandic")
259 ("it" "italian")
260 ("kn" "kannada")
261 ("la" "latin" "modern")
262 ("la-classic" "latin" "classic")
263 ("la-medieval" "latin" "medieval")
264 ("la-modern" "latin" "modern")
265 ("lo" "lao")
266 ("lt" "lithuanian")
267 ("lv" "latvian")
268 ("ml" "malayalam")
269 ("mr" "maranthi")
270 ("nb" "norsk")
271 ("nko" "nko")
272 ("nl" "dutch")
273 ("nn" "nynorsk")
274 ("no" "norsk")
275 ("oc" "occitan")
276 ("pl" "polish")
277 ("pms" "piedmontese")
278 ("pt" "portuges")
279 ("pt-br" "brazilian")
280 ("rm" "romansh")
281 ("ro" "romanian")
282 ("ru" "russian")
283 ("sa" "sanskrit")
284 ("se" "samin")
285 ("sk" "slovak")
286 ("sl" "slovenian")
287 ("sq" "albanian")
288 ("sr" "serbian")
289 ("sv" "swedish")
290 ("syr" "syriac")
291 ("ta" "tamil")
292 ("te" "telugu")
293 ("th" "thai")
294 ("tk" "turkmen")
295 ("tr" "turkish")
296 ("uk" "ukrainian")
297 ("ur" "urdu")
298 ("vi" "vietnamese"))
299 "Alist between language code and corresponding Polyglossia option.")
300
301 (defconst org-latex-table-matrix-macros '(("bordermatrix" . "\\cr")
177 (defconst org-latex-language-alist
178 '(("am" :babel-ini-only "amharic" :polyglossia "amharic" :lang-name "Amharic")
179 ("ar" :babel "arabic" :polyglossia "arabic" :lang-name "Arabic")
180 ("ast" :babel-ini-only "asturian" :polyglossia "asturian" :lang-name "Asturian")
181 ("bg" :babel "bulgarian" :polyglossia "bulgarian" :lang-name "Bulgarian")
182 ("bn" :babel-ini-only "bengali" :polyglossia "bengali" :lang-name "Bengali")
183 ("bo" :babel-ini-only "tibetan" :polyglossia "tibetan" :lang-name "Tibetan")
184 ("br" :babel "breton" :polyglossia "breton" :lang-name "Breton")
185 ("ca" :babel "catalan" :polyglossia "catalan" :lang-name "Catalan")
186 ("cop" :babel-ini-only "coptic" :polyglossia "coptic" :lang-name "Coptic")
187 ("cs" :babel "czech" :polyglossia "czech" :lang-name "Czech")
188 ("cy" :babel "welsh" :polyglossia "welsh" :lang-name "Welsh")
189 ("da" :babel "danish" :polyglossia "danish" :lang-name "Danish")
190 ("de" :babel "ngerman" :polyglossia "german" :polyglossia-variant "german" :lang-name "German")
191 ("de-at" :babel "naustrian" :polyglossia "german" :polyglossia-variant "austrian" :lang-name "German")
192 ("dsb" :babel "lsorbian" :polyglossia "sorbian" :polyglossia-variant "lower" :lang-name "Lower Sorbian")
193 ("dv" :babel-ini-only "divehi" :polyglossia "divehi" :lang-name "Divehi")
194 ("el" :babel "greek" :polyglossia "greek" :lang-name "Greek")
195 ("el-polyton" :babel "polutonikogreek" :polyglossia "greek" :polyglossia-variant "polytonic" :lang-name "Polytonic Greek")
196 ("en" :babel "american" :polyglossia "english" :polyglossia-variant "usmax" :lang-name "English")
197 ("en-au" :babel "australian" :polyglossia "english" :polyglossia-variant "australian" :lang-name "English")
198 ("en-gb" :babel "british" :polyglossia "english" :polyglossia-variant "uk" :lang-name "English")
199 ("en-nz" :babel "newzealand" :polyglossia "english" :polyglossia-variant "newzealand" :lang-name "English")
200 ("en-us" :babel "american" :polyglossia "english" :polyglossia-variant "usmax" :lang-name "English")
201 ("eo" :babel "esperanto" :polyglossia "esperanto" :lang-name "Esperanto")
202 ("es" :babel "spanish" :polyglossia "spanish" :lang-name "Spanish")
203 ("es-mx" :babel "spanishmx" :polyglossia "spanish" :polyglossia-variant "mexican" :lang-name "Spanish")
204 ("et" :babel "estonian" :polyglossia "estonian" :lang-name "Estonian")
205 ("eu" :babel "basque" :polyglossia "basque" :lang-name "Basque")
206 ("fa" :babel "farsi" :polyglossia "farsi" :lang-name "Farsi")
207 ("fi" :babel "finnish" :polyglossia "finnish" :lang-name "Finnish")
208 ("fr" :babel "french" :polyglossia "french" :lang-name "French")
209 ("fr-ca" :babel "canadien" :polyglossia "french" :polyglossia-variant "canadian" :lang-name "French")
210 ("fur" :babel "friulan" :polyglossia "friulan" :lang-name "Friulian")
211 ("ga" :babel "irish" :polyglossia "irish" :lang-name "Irish")
212 ("gd" :babel "scottish" :polyglossia "scottish" :lang-name "Scottish Gaelic")
213 ("gl" :babel "galician" :polyglossia "galician" :lang-name "Galician")
214 ("he" :babel "hebrew" :polyglossia "hebrew" :lang-name "Hebrew")
215 ("hi" :babel "hindi" :polyglossia "hindi" :lang-name "Hindi")
216 ("hr" :babel "croatian" :polyglossia "croatian" :lang-name "Croatian")
217 ("hsb" :babel "uppersorbian" :polyglossia "sorbian" :polyglossia-variant "upper" :lang-name "Upper Sorbian")
218 ("hu" :babel "magyar" :polyglossia "magyar" :lang-name "Magyar")
219 ("hy" :babel-ini-only "armenian" :polyglossia "armenian" :lang-name "Armenian")
220 ("ia" :babel "interlingua" :polyglossia "interlingua" :lang-name "Interlingua")
221 ("id" :babel-ini-only "bahasai" :polyglossia "bahasai" :lang-name "Bahasai")
222 ("is" :babel "icelandic" :polyglossia "icelandic" :lang-name "Icelandic")
223 ("it" :babel "italian" :polyglossia "italian" :lang-name "Italian")
224 ("kn" :babel-ini-only "kannada" :polyglossia "kannada" :lang-name "Kannada")
225 ("la" :babel "latin" :polyglossia "latin" :lang-name "Latin")
226 ("la-classic" :babel "classiclatin" :polyglossia "latin" :polyglossia-variant "classic" :lang-name "Classic Latin")
227 ("la-medieval" :babel "medievallatin" :polyglossia "latin" :polyglossia-variant "medieval" :lang-name "Medieval Latin")
228 ("la-ecclesiastic" :babel "ecclesiasticlatin" :polyglossia "latin" :polyglossia-variant "ecclesiastic" :lang-name "Ecclesiastic Latin")
229 ("lo" :babel-ini-only "lao" :polyglossia "lao" :lang-name "Lao")
230 ("lt" :babel "lithuanian" :polyglossia "lithuanian" :lang-name "Lithuanian")
231 ("lv" :babel "latvian" :polyglossia "latvian" :lang-name "Latvian")
232 ("ml" :babel-ini-only "malayalam" :polyglossia "malayalam" :lang-name "Malayalam")
233 ("mr" :babel-ini-only "maranthi" :polyglossia "maranthi" :lang-name "Maranthi")
234 ("nb" :babel "norsk" :polyglossia "norwegian" :polyglossia-variant "bokmal" :lang-name "Norwegian Bokmål")
235 ("nl" :babel "dutch" :polyglossia "dutch" :lang-name "Dutch")
236 ("nn" :babel "nynorsk" :polyglossia "norwegian" :polyglossia-variant "nynorsk" :lang-name "Norwegian Nynorsk")
237 ("no" :babel "norsk" :polyglossia "norsk" :lang-name "Norwegian")
238 ("oc" :babel "occitan" :polyglossia "occitan" :lang-name "Occitan")
239 ("pl" :babel "polish" :polyglossia "polish" :lang-name "Polish")
240 ("pms" :babel "piedmontese" :polyglossia "piedmontese" :lang-name "Piedmontese")
241 ("pt" :babel "portuges" :polyglossia "portuges" :lang-name "Portuges")
242 ("pt-br" :babel "brazilian" :polyglossia "brazilian" :lang-name "Portuges")
243 ("rm" :babel-ini-only "romansh" :polyglossia "romansh" :lang-name "Romansh")
244 ("ro" :babel "romanian" :polyglossia "romanian" :lang-name "Romanian")
245 ("ru" :babel "russian" :polyglossia "russian" :lang-name "Russian")
246 ("sa" :babel-ini-only "sanskrit" :polyglossia "sanskrit" :lang-name "Sanskrit")
247 ("sk" :babel "slovak" :polyglossia "slovak" :lang-name "Slovak")
248 ("sl" :babel "slovene" :polyglossia "slovene" :lang-name "Slovene")
249 ("sq" :babel "albanian" :polyglossia "albanian" :lang-name "Albanian")
250 ("sr" :babel "serbian" :polyglossia "serbian" :lang-name "Serbian")
251 ("sv" :babel "swedish" :polyglossia "swedish" :lang-name "Swedish")
252 ("syr" :babel-ini-only "syriac" :polyglossia "syriac" :lang-name "Syriac")
253 ("ta" :babel-ini-only "tamil" :polyglossia "tamil" :lang-name "Tamil")
254 ("te" :babel-ini-only "telugu" :polyglossia "telugu" :lang-name "Telugu")
255 ("th" :babel "thai" :polyglossia "thai" :lang-name "Thai")
256 ("tk" :babel "turkmen" :polyglossia "turkmen" :lang-name "Turkmen")
257 ("tr" :babel "turkish" :polyglossia "turkish" :lang-name "Turkish")
258 ("uk" :babel "ukrainian" :polyglossia "ukrainian" :lang-name "Ukrainian")
259 ("ur" :babel-ini-only "urdu" :polyglossia "urdu" :lang-name "Urdu")
260 ("vi" :babel "vietnamese" :polyglossia "vietnamese" :lang-name "Vietnamese"))
261 "Alist between language code and its properties for LaTeX export.
262
263 In each element of the list car is always the code of the
264 language and cdr is a property list. Valid keywords for this
265 list can be:
266
267 - `:babel' the name of the language loaded by the Babel LaTeX package
268
269 - `:polyglossia' the name of the language loaded by the Polyglossia
270 LaTeX package
271
272 - `:babel-ini-only' the name of the language loaded by Babel
273 exclusively through the new ini files method. See
274 `http://mirrors.ctan.org/macros/latex/required/babel/base/babel.pdf'
275
276 - `:polyglossia-variant' the language variant loaded by Polyglossia
277
278 - `:lang-name' the actual name of the language.")
279
280 (defconst org-latex-line-break-safe "\\\\[0pt]"
281 "Linebreak protecting the following [...].
282
283 Without \"[0pt]\" it would be interpreted as an optional argument to
284 the \\\\.
285
286 This constant, for example, makes the below code not err:
287
288 \\begin{tabular}{c|c}
289 [t] & s\\\\[0pt]
290 [I] & A\\\\[0pt]
291 [m] & kg
292 \\end{tabular}")
293
294 (defconst org-latex-table-matrix-macros `(("bordermatrix" . "\\cr")
302295 ("qbordermatrix" . "\\cr")
303 ("kbordermatrix" . "\\\\"))
296 ("kbordermatrix" . ,org-latex-line-break-safe))
304297 "Alist between matrix macros and their row ending.")
305298
306299 (defconst org-latex-math-environments-re
754747
755748 (defcustom org-latex-inline-image-rules
756749 `(("file" . ,(rx "."
757 (or "pdf" "jpeg" "jpg" "png" "ps" "eps" "tikz" "pgf" "svg")
758 eos)))
750 (or "pdf" "jpeg" "jpg" "png" "ps" "eps" "tikz" "pgf" "svg")
751 eos))
752 ("https" . ,(rx "."
753 (or "jpeg" "jpg" "png" "ps" "eps" "tikz" "pgf" "svg")
754 eos)))
759755 "Rules characterizing image files that can be inlined into LaTeX.
760756
761757 A rule consists in an association whose key is the type of link
768764 through dvi to Postscript, only ps and eps are allowed. The
769765 default we use here encompasses both."
770766 :group 'org-export-latex
771 :package-version '(Org . "9.4")
767 :package-version '(Org . "9.6")
772768 :type '(alist :key-type (string :tag "Type")
773769 :value-type (regexp :tag "Path")))
774770
928924
929925 ;; Src blocks
930926
931 (defcustom org-latex-listings nil
932 "Non-nil means export source code using the listings package.
933
934 This package will fontify source code, possibly even with color.
935 If you want to use this, you also need to make LaTeX use the
936 listings package, and if you want to have color, the color
937 package. Just add these to `org-latex-packages-alist', for
938 example using customize, or with something like:
927 (defcustom org-latex-src-block-backend 'verbatim
928 "Backend used to generate source code listings.
929
930 This sets the behavior for fontifying source code, possibly even with
931 color. There are four implementations of this functionality you may
932 choose from (ordered from least to most capable):
933 1. Verbatim
934 2. Listings
935 3. Minted
936 4. Engraved
937
938 The first two options provide basic syntax
939 highlighting (listings), or none at all (verbatim).
940
941 When using listings, you also need to make use of LaTeX package
942 \"listings\". The \"color\" LaTeX package is also needed if you
943 would like color too. These can simply be added to
944 `org-latex-packages-alist', using customize or something like:
939945
940946 (require \\='ox-latex)
941947 (add-to-list \\='org-latex-packages-alist \\='(\"\" \"listings\"))
942948 (add-to-list \\='org-latex-packages-alist \\='(\"\" \"color\"))
943949
944 Alternatively,
945
946 (setq org-latex-listings \\='minted)
947
948 causes source code to be exported using the minted package as
949 opposed to listings. If you want to use minted, you need to add
950 the minted package to `org-latex-packages-alist', for example
951 using customize, or with
950 There are two further options for more comprehensive
951 fontification. The first can be set with,
952
953 (setq org-latex-src-block-backend \\='minted)
954
955 which causes source code to be exported using the LaTeX package
956 minted as opposed to listings. If you want to use minted, you
957 need to add the minted package to `org-latex-packages-alist', for
958 example using customize, or with
952959
953960 (require \\='ox-latex)
954961 (add-to-list \\='org-latex-packages-alist \\='(\"newfloat\" \"minted\"))
961968 The minted choice has possible repercussions on the preview of
962969 latex fragments (see `org-preview-latex-fragment'). If you run
963970 into previewing problems, please consult
964 URL `https://orgmode.org/worg/org-tutorials/org-latex-preview.html'."
965 :group 'org-export-latex
971 URL `https://orgmode.org/worg/org-tutorials/org-latex-preview.html'.
972
973 The most comprehensive option can be set with,
974
975 (setq org-latex-src-block-backend \\='engraved)
976
977 which causes source code to be run through
978 `engrave-faces-latex-buffer', which generates colorings using
979 Emacs' font-lock information. This requires the Emacs package
980 engrave-faces (available from ELPA), and the LaTeX package
981 fvextra be installed.
982
983 The styling of the engraved result can be customized with
984 `org-latex-engraved-preamble' and `org-latex-engraved-options'.
985 The default preamble also uses the LaTeX package tcolorbox in
986 addition to fvextra."
987 :group 'org-export-latex
988 :package-version '(Org . "9.6")
966989 :type '(choice
967 (const :tag "Use listings" t)
990 (const :tag "Use listings" listings)
968991 (const :tag "Use minted" minted)
969 (const :tag "Export verbatim" nil))
970 :safe (lambda (s) (memq s '(t nil minted))))
992 (const :tag "Use engrave-faces-latex" engraved)
993 (const :tag "Export verbatim" verbatim))
994 :safe (lambda (s) (memq s '(listings minted engraved verbatim))))
971995
972996 (defcustom org-latex-listings-langs
973997 '((emacs-lisp "Lisp") (lisp "Lisp") (clojure "Lisp")
10011025
10021026 These options are supplied as a comma-separated list to the
10031027 \\lstset command. Each element of the association list should be
1004 a list containing two strings: the name of the option, and the
1005 value. For example,
1028 a list or cons cell containing two strings: the name of the
1029 option, and the value. For example,
10061030
10071031 (setq org-latex-listings-options
10081032 \\='((\"basicstyle\" \"\\\\small\")
10091033 (\"keywordstyle\" \"\\\\color{black}\\\\bfseries\\\\underbar\")))
1034 ; or
1035 (setq org-latex-listings-options
1036 \\='((\"basicstyle\" . \"\\\\small\")
1037 (\"keywordstyle\" . \"\\\\color{black}\\\\bfseries\\\\underbar\")))
10101038
10111039 will typeset the code in a small size font with underlined, bold
10121040 black keywords.
10541082
10551083 These options are supplied within square brackets in
10561084 \\begin{minted} environments. Each element of the alist should
1057 be a list containing two strings: the name of the option, and the
1058 value. For example,
1085 be a list or cons cell containing two strings: the name of the
1086 option, and the value. For example,
10591087
10601088 (setq org-latex-minted-options
10611089 \\='((\"bgcolor\" \"bg\") (\"frame\" \"lines\")))
1090 ; or
1091 (setq org-latex-minted-options
1092 \\='((\"bgcolor\" . \"bg\") (\"frame\" . \"lines\")))
10621093
10631094 will result in source blocks being exported with
10641095
11301161 :version "26.1"
11311162 :package-version '(Org . "9.0"))
11321163
1164 (defcustom org-latex-engraved-preamble
1165 "\\usepackage{fvextra}
1166
1167 [FVEXTRA-SETUP]
1168
1169 % Make line numbers smaller and grey.
1170 \\renewcommand\\theFancyVerbLine{\\footnotesize\\color{black!40!white}\\arabic{FancyVerbLine}}
1171
1172 \\usepackage{xcolor}
1173
1174 % In case engrave-faces-latex-gen-preamble has not been run.
1175 \\providecolor{EfD}{HTML}{f7f7f7}
1176 \\providecolor{EFD}{HTML}{28292e}
1177
1178 % Define a Code environment to prettily wrap the fontified code.
1179 \\usepackage[breakable,xparse]{tcolorbox}
1180 \\DeclareTColorBox[]{Code}{o}%
1181 {colback=EfD!98!EFD, colframe=EfD!95!EFD,
1182 fontupper=\\footnotesize\\setlength{\\fboxsep}{0pt},
1183 colupper=EFD,
1184 IfNoValueTF={#1}%
1185 {boxsep=2pt, arc=2.5pt, outer arc=2.5pt,
1186 boxrule=0.5pt, left=2pt}%
1187 {boxsep=2.5pt, arc=0pt, outer arc=0pt,
1188 boxrule=0pt, leftrule=1.5pt, left=0.5pt},
1189 right=2pt, top=1pt, bottom=0.5pt,
1190 breakable}
1191
1192 [LISTINGS-SETUP]"
1193 "Preamble content injected when using engrave-faces-latex for source blocks.
1194 This is relevant when `org-latex-src-block-backend' is set to `engraved'.
1195
1196 There is quite a lot of flexibility in what this preamble can be,
1197 as long as it:
1198 - Loads the fvextra package.
1199 - Loads the package xcolor (if it is not already loaded elsewhere).
1200 - Defines a \"Code\" environment (note the capital C), which all
1201 \"Verbatim\" environments (provided by fvextra) will be wrapped with.
1202
1203 In the default value the colors \"EFD\" and \"EfD\" are provided
1204 as they are respectively the foreground and background colors,
1205 just in case they aren't provided by the generated preamble, so
1206 we can assume they are always set.
1207
1208 Within this preamble there are two recognized macro-like placeholders:
1209
1210 [FVEXTRA-SETUP]
1211
1212 [LISTINGS-SETUP]
1213
1214 Unless you have a very good reason, both of these placeholders
1215 should be included in the preamble.
1216
1217 FVEXTRA-SETUP sets fvextra's defaults according to
1218 `org-latex-engraved-options', and LISTINGS-SETUP creates the
1219 listings environment used for captioned or floating code blocks,
1220 as well as defining \\listoflistings."
1221 :group 'org-export-latex
1222 :type 'string
1223 :package-version '(Org . "9.6"))
1224
1225 (defcustom org-latex-engraved-options
1226 '(("commandchars" . "\\\\\\{\\}")
1227 ("highlightcolor" . "white!95!black!80!blue")
1228 ("breaklines" . "true")
1229 ("breaksymbol" . "\\color{white!60!black}\\tiny\\ensuremath{\\hookrightarrow}"))
1230 "Association list of options for the latex fvextra package when engraving code.
1231
1232 These options are set using \\fvset{...} in the preamble of the
1233 LaTeX export. Each element of the alist should be a list or cons
1234 cell containing two strings: the name of the option, and the
1235 value. For example,
1236
1237 (setq org-latex-engraved-options
1238 \\='((\"highlightcolor\" \"green\") (\"frame\" \"lines\")))
1239 ; or
1240 (setq org-latex-engraved-options
1241 \\='((\"highlightcolor\" . \"green\") (\"frame\" . \"lines\")))
1242
1243 will result in the following LaTeX in the preamble
1244
1245 \\fvset{%
1246 bgcolor=bg,
1247 frame=lines}
1248
1249 This will affect all fvextra environments. Note that the same
1250 options will be applied to all blocks. If you need
1251 block-specific options, you may use the following syntax:
1252
1253 #+ATTR_LATEX: :options key1=value1,key2=value2
1254 #+BEGIN_SRC <LANG>
1255 ...
1256 #+END_SRC"
1257 :group 'org-export-latex
1258 :package-version '(Org . "9.6")
1259 :type '(alist :key-type (string :tag "option")
1260 :value-type (string :tag "value")))
1261
1262 (defcustom org-latex-engraved-theme nil
1263 "The theme that should be used for engraved code, when non-nil.
1264 This can be set to any theme defined in `engrave-faces-themes' or
1265 loadable by Emacs. When set to t, the current Emacs theme is
1266 used. When nil, no theme is applied."
1267 :group 'org-export-latex
1268 :package-version '(Org . "9.6")
1269 :type 'symbol)
1270
1271 (defun org-latex-generate-engraved-preamble (info)
1272 "Generate the preamble to setup engraved code.
1273 The result is constructed from the :latex-engraved-preamble and
1274 :latex-engraved-options export options, the default values of
1275 which are given by `org-latex-engraved-preamble' and
1276 `org-latex-engraved-options' respectively."
1277 (let* ((engraved-options
1278 (plist-get info :latex-engraved-options))
1279 (engraved-preamble (plist-get info :latex-engraved-preamble))
1280 (engraved-theme (plist-get info :latex-engraved-theme))
1281 (engraved-themes
1282 (mapcar
1283 #'intern
1284 (cl-delete-duplicates
1285 (org-element-map
1286 (plist-get info :parse-tree)
1287 '(src-block inline-src-block)
1288 (lambda (src)
1289 (plist-get
1290 (org-export-read-attribute :attr_latex src)
1291 :engraved-theme))
1292 info))))
1293 (gen-theme-spec
1294 (lambda (theme)
1295 (if (eq engrave-faces-latex-output-style 'preset)
1296 (engrave-faces-latex-gen-preamble theme)
1297 (engrave-faces-latex-gen-preamble-line
1298 'default
1299 (alist-get 'default
1300 (if theme
1301 (engrave-faces-get-theme (intern theme))
1302 engrave-faces-current-preset-style)))))))
1303 (when (stringp engraved-theme)
1304 (setq engraved-theme (intern engraved-theme)))
1305 (when (string-match "^[ \t]*\\[FVEXTRA-SETUP\\][ \t]*\n?" engraved-preamble)
1306 (setq engraved-preamble
1307 (replace-match
1308 (concat
1309 "\\fvset{%\n "
1310 (org-latex--make-option-string engraved-options ",\n ")
1311 "}\n")
1312 t t
1313 engraved-preamble)))
1314 (when (string-match "^[ \t]*\\[LISTINGS-SETUP\\][ \t]*\n?" engraved-preamble)
1315 (setq engraved-preamble
1316 (replace-match
1317 (format
1318 "%% Support listings with captions
1319 \\usepackage{float}
1320 \\floatstyle{%s}
1321 \\newfloat{listing}{htbp}{lst}
1322 \\newcommand{\\listingsname}{Listing}
1323 \\floatname{listing}{\\listingsname}
1324 \\newcommand{\\listoflistingsname}{List of Listings}
1325 \\providecommand{\\listoflistings}{\\listof{listing}{\\listoflistingsname}}\n"
1326 (if (memq 'src-block org-latex-caption-above)
1327 "plaintop" "plain"))
1328 t t
1329 engraved-preamble)))
1330 (concat
1331 "\n% Setup for code blocks [1/2]\n\n"
1332 engraved-preamble
1333 "\n\n% Setup for code blocks [2/2]: syntax highlighting colors\n\n"
1334 (if (require 'engrave-faces-latex nil t)
1335 (if engraved-themes
1336 (concat
1337 (mapconcat
1338 (lambda (theme)
1339 (format
1340 "\n\\newcommand{\\engravedtheme%s}{%%\n%s\n}"
1341 (replace-regexp-in-string "[^A-Za-z]" "" (symbol-name theme))
1342 (replace-regexp-in-string
1343 "newcommand" "renewcommand"
1344 (replace-regexp-in-string
1345 "#" "##"
1346 (funcall gen-theme-spec theme)))))
1347 engraved-themes
1348 "\n")
1349 "\n\n"
1350 (cond
1351 ((memq engraved-theme engraved-themes)
1352 (concat "\\engravedtheme"
1353 (replace-regexp-in-string
1354 "[^A-Za-z]" "" engraved-theme)
1355 "\n"))
1356 (t (funcall gen-theme-spec engraved-theme))))
1357 (funcall gen-theme-spec engraved-theme))
1358 (message "Cannot engrave source blocks. Consider installing `engrave-faces'.")
1359 "% WARNING syntax highlighting unavailable as engrave-faces-latex was missing.\n")
1360 "\n")))
11331361
11341362 ;;;; Compilation
11351363
11851413 "%latex -interaction nonstopmode -output-directory %o %f"
11861414 "%latex -interaction nonstopmode -output-directory %o %f"))
11871415 "Commands to process a LaTeX file to a PDF file.
1416
1417 The command output will be parsed to extract compilation errors and
1418 warnings according to `org-latex-known-warnings'.
11881419
11891420 This is a list of strings, each of them will be given to the
11901421 shell as a command. %f in the command will be replaced by the
12081439 processing, so you could use this to apply the machinery of
12091440 AUCTeX or the Emacs LaTeX mode. This function should accept the
12101441 file name as its single argument."
1211 :group 'org-export-pdf
1442 :group 'org-export-latex
12121443 :type '(choice
12131444 (repeat :tag "Shell command sequence"
12141445 (string :tag "Shell command"))
13141545 (`paragraph
13151546 (and (org-element-property :caption datum)
13161547 "fig:"))
1548 (`src-block "lst:")
13171549 (_ nil))
13181550 (org-export-get-reference datum info))))))
13191551 (cond ((not full) label)
13381570 main)
13391571 (and (eq type 'src-block)
13401572 (not (plist-get attr :float))
1341 (null (plist-get info :latex-listings)))))
1573 (memq (plist-get info :latex-src-block-backend)
1574 '(verbatim nil)))))
13421575 (short (org-export-get-caption element t))
13431576 (caption-from-attr-latex (plist-get attr :caption)))
13441577 (cond
13581591 (paragraph "figure")
13591592 (image "figure")
13601593 (special-block "figure")
1361 (src-block (if (plist-get info :latex-listings)
1594 (src-block (if (not (memq (plist-get info :latex-src-block-backend)
1595 '(verbatim nil)))
13621596 "listing"
13631597 "figure"))
13641598 (t (symbol-name type*)))
13951629 explicitly been loaded. Then it is added to the rest of
13961630 package's options.
13971631
1398 The argument to Babel may be \"AUTO\" which is then replaced with
1399 the language of the document or `org-export-default-language'
1400 unless language in question is already loaded.
1632 The optional argument to Babel or the mandatory argument to
1633 `\babelprovide' command may be \"AUTO\" which is then replaced
1634 with the language of the document or
1635 `org-export-default-language' unless language in question is
1636 already loaded.
14011637
14021638 Return the new header."
1403 (let ((language-code (plist-get info :language)))
1404 ;; If no language is set or Babel package is not loaded, return
1405 ;; HEADER as-is.
1406 (if (or (not (stringp language-code))
1407 (not (string-match "\\\\usepackage\\[\\(.*\\)\\]{babel}" header)))
1639 (let* ((language-code (plist-get info :language))
1640 (plist (cdr
1641 (assoc language-code org-latex-language-alist)))
1642 (language (plist-get plist :babel))
1643 (language-ini-only (plist-get plist :babel-ini-only))
1644 ;; If no language is set, or Babel package is not loaded, or
1645 ;; LANGUAGE keyword value is a language served by Babel
1646 ;; exclusively through ini files, return HEADER as-is.
1647 (header (if (or language-ini-only
1648 (not (stringp language-code))
1649 (not (string-match "\\\\usepackage\\[\\(.*\\)\\]{babel}" header)))
1650 header
1651 (let ((options (save-match-data
1652 (org-split-string (match-string 1 header) ",[ \t]*"))))
1653 ;; If LANGUAGE is already loaded, return header
1654 ;; without AUTO. Otherwise, replace AUTO with language or
1655 ;; append language if AUTO is not present. Languages that are
1656 ;; served in Babel exclusively through ini files are not added
1657 ;; to the babel argument, and must be loaded using
1658 ;; `\babelprovide'.
1659 (replace-match
1660 (mapconcat (lambda (option) (if (equal "AUTO" option) language option))
1661 (cond ((member language options) (delete "AUTO" options))
1662 ((member "AUTO" options) options)
1663 (t (append options (list language))))
1664 ", ")
1665 t nil header 1)))))
1666 ;; If `\babelprovide[args]{AUTO}' is present, AUTO is
1667 ;; replaced by LANGUAGE.
1668 (if (not (string-match "\\\\babelprovide\\[.*\\]{\\(.+\\)}" header))
14081669 header
1409 (let ((options (save-match-data
1410 (org-split-string (match-string 1 header) ",[ \t]*")))
1411 (language (cdr (assoc-string language-code
1412 org-latex-babel-language-alist t))))
1413 ;; If LANGUAGE is already loaded, return header without AUTO.
1414 ;; Otherwise, replace AUTO with language or append language if
1415 ;; AUTO is not present.
1416 (replace-match
1417 (mapconcat (lambda (option) (if (equal "AUTO" option) language option))
1418 (cond ((member language options) (delete "AUTO" options))
1419 ((member "AUTO" options) options)
1420 (t (append options (list language))))
1421 ", ")
1422 t nil header 1)))))
1670 (let ((prov (match-string 1 header)))
1671 (if (equal "AUTO" prov)
1672 (replace-regexp-in-string (format
1673 "\\(\\\\babelprovide\\[.*\\]\\)\\({\\)%s}" prov)
1674 (format "\\1\\2%s}"
1675 (or language language-ini-only))
1676 header t)
1677 header)))))
14231678
14241679 (defun org-latex-guess-polyglossia-language (header info)
14251680 "Set the Polyglossia language according to the LANGUAGE keyword.
14361691 using \setdefaultlanguage and not as an option to the package.
14371692
14381693 Return the new header."
1439 (let ((language (plist-get info :language)))
1694 (let* ((language (plist-get info :language)))
14401695 ;; If no language is set or Polyglossia is not loaded, return
14411696 ;; HEADER as-is.
14421697 (if (or (not (stringp language))
14611716 (concat "\\usepackage{polyglossia}\n"
14621717 (mapconcat
14631718 (lambda (l)
1464 (let ((l (or (assoc l org-latex-polyglossia-language-alist)
1465 l)))
1466 (format (if main-language-set "\\setotherlanguage%s{%s}\n"
1719 (let* ((plist (cdr
1720 (assoc language org-latex-language-alist)))
1721 (polyglossia-variant (plist-get plist :polyglossia-variant))
1722 (polyglossia-lang (plist-get plist :polyglossia))
1723 (l (if (equal l language)
1724 polyglossia-lang
1725 l)))
1726 (format (if main-language-set (format "\\setotherlanguage{%s}\n" l)
14671727 (setq main-language-set t)
14681728 "\\setmainlanguage%s{%s}\n")
1469 (if (and (consp l) (= (length l) 3))
1470 (format "[variant=%s]" (nth 2 l))
1729 (if polyglossia-variant
1730 (format "[variant=%s]" polyglossia-variant)
14711731 "")
1472 (nth 1 l))))
1732 l)))
14731733 languages
14741734 ""))
14751735 t t header 0)))))
15011761 when (not (string-match (regexp-quote (char-to-string c)) s))
15021762 return (char-to-string c))))
15031763
1504 (defun org-latex--make-option-string (options)
1764 (defun org-latex--make-option-string (options &optional separator)
15051765 "Return a comma separated string of keywords and values.
15061766 OPTIONS is an alist where the key is the options keyword as
15071767 a string, and the value a list containing the keyword value, or
15081768 nil."
15091769 (mapconcat (lambda (pair)
1510 (pcase-let ((`(,keyword ,value) pair))
1511 (concat keyword
1512 (and (> (length value) 0)
1513 (concat "="
1514 (if (string-match-p (rx (any "[]")) value)
1515 (format "{%s}" value)
1516 value))))))
1517 options
1518 ","))
1770 (let ((keyword (car pair))
1771 (value (pcase (cdr pair)
1772 ((pred stringp) (cdr pair))
1773 ((pred consp) (cadr pair)))))
1774 (concat keyword
1775 (when value
1776 (concat "="
1777 (if (string-match-p (rx (any "[]")) value)
1778 (format "{%s}" value)
1779 value))))))
1780 options
1781 (or separator ",")))
15191782
15201783 (defun org-latex--wrap-label (element output info)
15211784 "Wrap label associated to ELEMENT around OUTPUT, if appropriate.
15561819 "Protect special chars, then wrap TEXT in \"\\texttt{}\"."
15571820 (format "\\texttt{%s}"
15581821 (replace-regexp-in-string
1559 "--\\|[\\{}$%&_#~^]"
1822 "--\\|<<\\|>>\\|[\\{}$%&_#~^]"
15601823 (lambda (m)
1561 (cond ((equal m "--") "-{}-")
1824 (cond ((equal m "--") "-{}-{}")
1825 ((equal m "<<") "<{}<{}")
1826 ((equal m ">>") ">{}>{}")
15621827 ((equal m "\\") "\\textbackslash{}")
15631828 ((equal m "~") "\\textasciitilde{}")
15641829 ((equal m "^") "\\textasciicircum{}")
16101875 (defun org-latex--format-spec (info)
16111876 "Create a format-spec for document meta-data.
16121877 INFO is a plist used as a communication channel."
1613 (let ((language (let ((lang (plist-get info :language)))
1614 (or (cdr (assoc-string lang org-latex-babel-language-alist t))
1615 (nth 1 (assoc-string lang org-latex-polyglossia-language-alist t))
1616 lang))))
1878 (let ((language (let* ((lang (plist-get info :language))
1879 (plist (cdr
1880 (assoc lang org-latex-language-alist))))
1881 ;; Here the actual name of the LANGUAGE or LANG is used.
1882 (or (plist-get plist :lang-name)
1883 lang))))
16171884 `((?a . ,(org-export-data (plist-get info :author) info))
16181885 (?t . ,(org-export-data (plist-get info :title) info))
16191886 (?s . ,(org-export-data (plist-get info :subtitle) info))
16261893 (?c . ,(plist-get info :creator))
16271894 (?l . ,language)
16281895 (?L . ,(capitalize language))
1629 (?D . ,(org-export-get-date info)))))
1896 (?D . ,(org-export-data (org-export-get-date info) info)))))
16301897
16311898 (defun org-latex--insert-compiler (info)
16321899 "Insert LaTeX_compiler info into the document.
17231990 (format "\\author{%s\\thanks{%s}}\n" author email))
17241991 ((or author email) (format "\\author{%s}\n" (or author email)))))
17251992 ;; Date.
1993 ;; LaTeX displays today's date by default. One can override this by
1994 ;; inserting \date{} for no date, or \date{string} with any other
1995 ;; string to be displayed as the date.
17261996 (let ((date (and (plist-get info :with-date) (org-export-get-date info))))
17271997 (format "\\date{%s}\n" (org-export-data date info)))
17281998 ;; Title and subtitle.
17412011 (let ((template (plist-get info :latex-hyperref-template)))
17422012 (and (stringp template)
17432013 (format-spec template spec)))
2014 ;; engrave-faces-latex preamble
2015 (when (and (eq org-latex-src-block-backend 'engraved)
2016 (org-element-map (plist-get info :parse-tree)
2017 '(src-block inline-src-block) #'identity
2018 info t))
2019 (org-latex-generate-engraved-preamble info))
17442020 ;; Document start.
17452021 "\\begin{document}\n\n"
17462022 ;; Title command.
18042080 (concat (org-timestamp-translate (org-element-property :value clock))
18052081 (let ((time (org-element-property :duration clock)))
18062082 (and time (format " (%s)" time)))))
1807 "\\\\"))
2083 org-latex-line-break-safe))
18082084
18092085
18102086 ;;;; Code
21222398 "Transcode an INLINE-SRC-BLOCK element from Org to LaTeX.
21232399 CONTENTS holds the contents of the item. INFO is a plist holding
21242400 contextual information."
2125 (let* ((code (org-element-property :value inline-src-block))
2126 (separator (org-latex--find-verb-separator code)))
2127 (cl-case (plist-get info :latex-listings)
2128 ;; Do not use a special package: transcode it verbatim, as code.
2129 ((nil) (org-latex--text-markup code 'code info))
2130 ;; Use minted package.
2131 (minted
2132 (let* ((org-lang (org-element-property :language inline-src-block))
2133 (mint-lang (or (cadr (assq (intern org-lang)
2134 (plist-get info :latex-minted-langs)))
2135 (downcase org-lang)))
2136 (options (org-latex--make-option-string
2137 (plist-get info :latex-minted-options))))
2138 (format "\\mintinline%s{%s}{%s}"
2139 (if (string= options "") "" (format "[%s]" options))
2140 mint-lang
2141 code)))
2142 ;; Use listings package.
2143 (otherwise
2144 ;; Maybe translate language's name.
2145 (let* ((org-lang (org-element-property :language inline-src-block))
2146 (lst-lang (or (cadr (assq (intern org-lang)
2147 (plist-get info :latex-listings-langs)))
2148 org-lang))
2149 (options (org-latex--make-option-string
2150 (append (plist-get info :latex-listings-options)
2151 `(("language" ,lst-lang))))))
2152 (concat (format "\\lstinline[%s]" options)
2153 separator code separator))))))
2154
2401 (let ((code (org-element-property :value inline-src-block))
2402 (lang (org-element-property :language inline-src-block)))
2403 (pcase (plist-get info :latex-src-block-backend)
2404 (`verbatim (org-latex--text-markup code 'code info))
2405 (`minted (org-latex-inline-src-block--minted info code lang))
2406 (`engraved (org-latex-inline-src-block--engraved info code lang))
2407 (`listings (org-latex-inline-src-block--listings info code lang))
2408 (oldval
2409 (message "Please update the LaTeX src-block-backend to %s"
2410 (if oldval "listings" "verbatim"))
2411 (if oldval
2412 (org-latex-inline-src-block--listings info code lang)
2413 (org-latex--text-markup code 'code info))))))
2414
2415 (defun org-latex-inline-src-block--minted (info code lang)
2416 "Transcode an inline src block's content from Org to LaTeX, using minted.
2417 INFO, CODE, and LANG are provided by `org-latex-inline-src-block'."
2418 (let ((mint-lang (or (cadr (assq (intern lang)
2419 (plist-get info :latex-minted-langs)))
2420 (downcase lang)))
2421 (options (org-latex--make-option-string
2422 (plist-get info :latex-minted-options))))
2423 (format "\\mintinline%s{%s}{%s}"
2424 (if (string= options "") "" (format "[%s]" options))
2425 mint-lang
2426 code)))
2427
2428 (defun org-latex-inline-src-block--engraved (info code lang)
2429 "Transcode an inline src block's content from Org to LaTeX, using engrave-faces.
2430 INFO, CODE, and LANG are provided by `org-latex-inline-src-block'."
2431 (org-latex-src--engrave-code
2432 code lang nil (plist-get info :latex-engraved-options) t))
2433
2434 (defun org-latex-inline-src-block--listings (info code lang)
2435 "Transcode an inline src block's content from Org to LaTeX, using lstlistings.
2436 INFO, CODE, and LANG are provided by `org-latex-inline-src-block'."
2437 (let* ((lst-lang (or (cadr (assq (intern lang)
2438 (plist-get info :latex-listings-langs)))
2439 lang))
2440 (separator (org-latex--find-verb-separator code))
2441 (options (org-latex--make-option-string
2442 (append (plist-get info :latex-listings-options)
2443 `(("language" ,lst-lang))))))
2444 (concat (format "\\lstinline[%s]" options)
2445 separator code separator)))
21552446
21562447 ;;;; Inlinetask
21572448
21862477 (mapcar #'org-latex--protect-text tags)))))))
21872478 (concat "\\begin{center}\n"
21882479 "\\fbox{\n"
2189 "\\begin{minipage}[c]{.6\\textwidth}\n"
2480 "\\begin{minipage}[c]{.6\\linewidth}\n"
21902481 full-title "\n\n"
21912482 (and (org-string-nw-p contents)
2192 (concat "\\rule[.8em]{\\textwidth}{2pt}\n\n" contents))
2483 (concat "\\rule[.8em]{\\linewidth}{2pt}\n\n" contents))
21932484 "\\end{minipage}\n"
21942485 "}\n"
21952486 "\\end{center}")))
23032594 (concat depth (and depth "\n") "\\tableofcontents"))))
23042595 ((string-match-p "\\<tables\\>" value) "\\listoftables")
23052596 ((string-match-p "\\<listings\\>" value)
2306 (cl-case (plist-get info :latex-listings)
2597 (cl-case (plist-get info :latex-src-block-backend)
23072598 ((nil) "\\listoffigures")
23082599 (minted "\\listoflistings")
2600 (engraved "\\listoflistings")
23092601 (otherwise "\\lstlistoflistings")))))))))
23102602
23112603
2312 ;;;; Latex Environment
2604 ;;;; LaTeX Environment
23132605
23142606 (defun org-latex--environment-type (latex-environment)
23152607 "Return the TYPE of LATEX-ENVIRONMENT.
23672659 (insert caption)
23682660 (buffer-string))))))
23692661
2370 ;;;; Latex Fragment
2662 ;;;; LaTeX Fragment
23712663
23722664 (defun org-latex-latex-fragment (latex-fragment _contents _info)
23732665 "Transcode a LATEX-FRAGMENT object from Org to LaTeX.
23852677 (defun org-latex-line-break (_line-break _contents _info)
23862678 "Transcode a LINE-BREAK object from Org to LaTeX.
23872679 CONTENTS is nil. INFO is a plist holding contextual information."
2388 "\\\\\n")
2680 (concat org-latex-line-break-safe "\n"))
23892681
23902682
23912683 ;;;; Link
24102702 (cond ((string= float "wrap") 'wrap)
24112703 ((string= float "sideways") 'sideways)
24122704 ((string= float "multicolumn") 'multicolumn)
2705 ((string= float "t") 'figure)
24132706 ((and (plist-member attr :float) (not float)) 'nonfloat)
24142707 (float float)
24152708 ((or (org-element-property :caption parent)
24922785 ((string-prefix-p "," options)
24932786 (format "[%s]" (substring options 1)))
24942787 (t (format "[%s]" options)))
2495 path))
2788 ;; While \includegraphics is fine with unicode in the path,
2789 ;; \includesvg is prone to producing errors.
2790 (if (and (string-match-p "[^[:ascii:]]" path)
2791 (equal filetype "svg"))
2792 (concat "\\detokenize{" path "}")
2793 path)))
24962794 (when (equal filetype "svg")
24972795 (setq image-code (replace-regexp-in-string "^\\\\includegraphics"
24982796 "\\includesvg"
25872885 ;; Link type is handled by a special function.
25882886 ((org-export-custom-protocol-maybe link desc 'latex info))
25892887 ;; Image file.
2590 (imagep (org-latex--inline-image link info))
2888 (imagep (org-latex--inline-image (org-export-link-localise link) info))
25912889 ;; Radio link: Transcode target's contents and use them as link's
25922890 ;; description.
25932891 ((string= type "radio")
27253023 ;; Handle break preservation if required.
27263024 (when (plist-get info :preserve-breaks)
27273025 (setq output (replace-regexp-in-string
2728 "\\(?:[ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n" output nil t)))
3026 "\\(?:[ \t]*\\\\\\\\\\)?[ \t]*\n"
3027 (concat org-latex-line-break-safe "\n")
3028 output nil t)))
27293029 ;; Return value.
27303030 output))
27313031
27613061 (format (plist-get info :latex-active-timestamp-format)
27623062 (org-timestamp-translate scheduled)))))))
27633063 " ")
2764 "\\\\"))
3064 org-latex-line-break-safe))
27653065
27663066
27673067 ;;;; Property Drawer
29793279 contextual information."
29803280 (when (org-string-nw-p (org-element-property :value src-block))
29813281 (let* ((lang (org-element-property :language src-block))
2982 (caption (org-element-property :caption src-block))
2983 (caption-above-p (org-latex--caption-above-p src-block info))
2984 (label (org-element-property :name src-block))
2985 (custom-env (and lang
2986 (cadr (assq (intern lang)
2987 org-latex-custom-lang-environments))))
2988 (num-start (org-export-get-loc src-block info))
2989 (retain-labels (org-element-property :retain-labels src-block))
2990 (attributes (org-export-read-attribute :attr_latex src-block))
2991 (float (plist-get attributes :float))
2992 (listings (plist-get info :latex-listings)))
2993 (cond
2994 ;; Case 1. No source fontification.
2995 ((or (not lang) (not listings))
2996 (let ((caption-str (org-latex--caption/label-string src-block info))
2997 (verbatim (format "\\begin{verbatim}\n%s\\end{verbatim}"
2998 (org-export-format-code-default src-block info))))
2999 (cond ((string= "multicolumn" float)
3000 (format "\\begin{figure*}[%s]\n%s%s\n%s\\end{figure*}"
3001 (plist-get info :latex-default-figure-position)
3002 (if caption-above-p caption-str "")
3003 verbatim
3004 (if caption-above-p "" caption-str)))
3005 (caption (concat
3006 (if caption-above-p caption-str "")
3007 verbatim
3008 (if caption-above-p "" (concat "\n" caption-str))))
3009 (t verbatim))))
3010 ;; Case 2. Custom environment.
3011 (custom-env
3012 (let ((caption-str (org-latex--caption/label-string src-block info))
3013 (formatted-src (org-export-format-code-default src-block info)))
3014 (if (string-match-p "\\`[a-zA-Z0-9]+\\'" custom-env)
3015 (format "\\begin{%s}\n%s\\end{%s}\n"
3016 custom-env
3017 (concat (and caption-above-p caption-str)
3018 formatted-src
3019 (and (not caption-above-p) caption-str))
3020 custom-env)
3021 (format-spec custom-env
3022 `((?s . ,formatted-src)
3023 (?c . ,caption)
3024 (?f . ,float)
3025 (?l . ,(org-latex--label src-block info))
3026 (?o . ,(or (plist-get attributes :options) "")))))))
3027 ;; Case 3. Use minted package.
3028 ((eq listings 'minted)
3029 (let* ((caption-str (org-latex--caption/label-string src-block info))
3030 (placement (or (org-unbracket-string "[" "]" (plist-get attributes :placement))
3031 (plist-get info :latex-default-figure-position)))
3032 (float-env
3033 (cond
3034 ((string= "multicolumn" float)
3035 (format "\\begin{listing*}[%s]\n%s%%s\n%s\\end{listing*}"
3036 placement
3037 (if caption-above-p caption-str "")
3038 (if caption-above-p "" caption-str)))
3039 (caption
3040 (format "\\begin{listing}[%s]\n%s%%s\n%s\\end{listing}"
3041 placement
3042 (if caption-above-p caption-str "")
3043 (if caption-above-p "" caption-str)))
3044 ((string= "t" float)
3045 (concat (format "\\begin{listing}[%s]\n"
3046 placement)
3047 "%s\n\\end{listing}"))
3048 (t "%s")))
3049 (options (plist-get info :latex-minted-options))
3050 (body
3051 (format
3052 "\\begin{minted}[%s]{%s}\n%s\\end{minted}"
3053 ;; Options.
3054 (concat
3055 (org-latex--make-option-string
3056 (if (or (not num-start) (assoc "linenos" options))
3057 options
3058 (append
3059 `(("linenos")
3060 ("firstnumber" ,(number-to-string (1+ num-start))))
3061 options)))
3062 (let ((local-options (plist-get attributes :options)))
3063 (and local-options (concat "," local-options))))
3064 ;; Language.
3065 (or (cadr (assq (intern lang)
3066 (plist-get info :latex-minted-langs)))
3067 (downcase lang))
3068 ;; Source code.
3069 (let* ((code-info (org-export-unravel-code src-block))
3070 (max-width
3071 (apply 'max
3072 (mapcar 'length
3073 (org-split-string (car code-info)
3074 "\n")))))
3075 (org-export-format-code
3076 (car code-info)
3077 (lambda (loc _num ref)
3078 (concat
3079 loc
3080 (when ref
3081 ;; Ensure references are flushed to the right,
3082 ;; separated with 6 spaces from the widest line
3083 ;; of code.
3084 (concat (make-string (+ (- max-width (length loc)) 6)
3085 ?\s)
3086 (format "(%s)" ref)))))
3087 nil (and retain-labels (cdr code-info)))))))
3088 ;; Return value.
3089 (format float-env body)))
3090 ;; Case 4. Use listings package.
3091 (t
3092 (let ((lst-lang
3093 (or (cadr (assq (intern lang)
3094 (plist-get info :latex-listings-langs)))
3095 lang))
3096 (caption-str
3097 (when caption
3098 (let ((main (org-export-get-caption src-block))
3099 (secondary (org-export-get-caption src-block t)))
3100 (if (not secondary)
3101 (format "{%s}" (org-export-data main info))
3102 (format "{[%s]%s}"
3103 (org-export-data secondary info)
3104 (org-export-data main info))))))
3105 (lst-opt (plist-get info :latex-listings-options)))
3106 (concat
3107 ;; Options.
3108 (format
3109 "\\lstset{%s}\n"
3110 (concat
3111 (org-latex--make-option-string
3112 (append
3113 lst-opt
3114 (cond
3115 ((and (not float) (plist-member attributes :float)) nil)
3116 ((string= "multicolumn" float) '(("float" "*")))
3117 ((and float (not (assoc "float" lst-opt)))
3118 `(("float" ,(plist-get info :latex-default-figure-position)))))
3119 `(("language" ,lst-lang))
3120 (if label
3121 `(("label" ,(org-latex--label src-block info)))
3122 '(("label" " ")))
3123 (if caption-str `(("caption" ,caption-str)) '(("caption" " ")))
3124 `(("captionpos" ,(if caption-above-p "t" "b")))
3125 (cond ((assoc "numbers" lst-opt) nil)
3126 ((not num-start) '(("numbers" "none")))
3127 (t `(("firstnumber" ,(number-to-string (1+ num-start)))
3128 ("numbers" "left"))))))
3129 (let ((local-options (plist-get attributes :options)))
3130 (and local-options (concat "," local-options)))))
3131 ;; Source code.
3132 (format
3133 "\\begin{lstlisting}\n%s\\end{lstlisting}"
3134 (let* ((code-info (org-export-unravel-code src-block))
3135 (max-width
3136 (apply 'max
3137 (mapcar 'length
3138 (org-split-string (car code-info) "\n")))))
3139 (org-export-format-code
3140 (car code-info)
3141 (lambda (loc _num ref)
3142 (concat
3143 loc
3144 (when ref
3145 ;; Ensure references are flushed to the right,
3146 ;; separated with 6 spaces from the widest line of
3147 ;; code
3148 (concat (make-string (+ (- max-width (length loc)) 6) ?\s)
3149 (format "(%s)" ref)))))
3150 nil (and retain-labels (cdr code-info))))))))))))
3151
3282 (caption (org-element-property :caption src-block))
3283 (caption-above-p (org-latex--caption-above-p src-block info))
3284 (label (org-element-property :name src-block))
3285 (custom-env (and lang
3286 (cadr (assq (intern lang)
3287 org-latex-custom-lang-environments))))
3288 (num-start (org-export-get-loc src-block info))
3289 (retain-labels (org-element-property :retain-labels src-block))
3290 (attributes (org-export-read-attribute :attr_latex src-block))
3291 (float (plist-get attributes :float)))
3292 (funcall
3293 (pcase (plist-get info :latex-src-block-backend)
3294 ((or `verbatim (guard (not lang))) #'org-latex-src-block--verbatim)
3295 (`minted #'org-latex-src-block--minted)
3296 (`engraved #'org-latex-src-block--engraved)
3297 (`listings #'org-latex-src-block--listings)
3298 ((guard custom-env) #'org-latex-src-block--custom)
3299 (oldval
3300 (message "Please update the LaTeX src-block-backend to %s"
3301 (if oldval "listings" "verbatim"))
3302 (if oldval
3303 #'org-latex-src-block--listings
3304 #'org-latex-src-block--verbatim)))
3305 :src-block src-block
3306 :info info
3307 :lang lang
3308 :caption caption
3309 :caption-above-p caption-above-p
3310 :label label
3311 :num-start num-start
3312 :retain-labels retain-labels
3313 :attributes attributes
3314 :float float
3315 :custom-env custom-env))))
3316
3317 (cl-defun org-latex-src-block--verbatim
3318 (&key src-block info caption caption-above-p float &allow-other-keys)
3319 "Transcode a SRC-BLOCK element from Org to LaTeX, using verbatim.
3320 LANG, CAPTION, CAPTION-ABOVE-P, LABEL, NUM-START, RETAIN-LABELS, ATTRIBUTES
3321 and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
3322 (let ((caption-str (org-latex--caption/label-string src-block info))
3323 (verbatim (format "\\begin{verbatim}\n%s\\end{verbatim}"
3324 (org-export-format-code-default src-block info))))
3325 (cond ((string= "multicolumn" float)
3326 (format "\\begin{figure*}[%s]\n%s%s\n%s\\end{figure*}"
3327 (plist-get info :latex-default-figure-position)
3328 (if caption-above-p caption-str "")
3329 verbatim
3330 (if caption-above-p "" caption-str)))
3331 (caption (concat
3332 (if caption-above-p caption-str "")
3333 verbatim
3334 (if caption-above-p "" (concat "\n" caption-str))))
3335 (t verbatim))))
3336
3337 (cl-defun org-latex-src-block--custom
3338 (&key src-block info caption caption-above-p attributes float custom-env &allow-other-keys)
3339 "Transcode a SRC-BLOCK element from Org to LaTeX, using a custom environment.
3340 LANG, CAPTION, CAPTION-ABOVE-P, LABEL, NUM-START, RETAIN-LABELS, ATTRIBUTES
3341 and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
3342 (let ((caption-str (org-latex--caption/label-string src-block info))
3343 (formatted-src (org-export-format-code-default src-block info)))
3344 (if (string-match-p "\\`[a-zA-Z0-9]+\\'" custom-env)
3345 (format "\\begin{%s}\n%s\\end{%s}\n"
3346 custom-env
3347 (concat (and caption-above-p caption-str)
3348 formatted-src
3349 (and (not caption-above-p) caption-str))
3350 custom-env)
3351 (format-spec custom-env
3352 `((?s . ,formatted-src)
3353 (?c . ,caption)
3354 (?f . ,float)
3355 (?l . ,(org-latex--label src-block info))
3356 (?o . ,(or (plist-get attributes :options) "")))))))
3357
3358 (cl-defun org-latex-src-block--minted
3359 (&key src-block info lang caption caption-above-p num-start retain-labels attributes float &allow-other-keys)
3360 "Transcode a SRC-BLOCK element from Org to LaTeX, using minted.
3361 LANG, CAPTION, CAPTION-ABOVE-P, LABEL, NUM-START, RETAIN-LABELS, ATTRIBUTES
3362 and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
3363 (let* ((caption-str (org-latex--caption/label-string src-block info))
3364 (placement (or (org-unbracket-string "[" "]" (plist-get attributes :placement))
3365 (plist-get info :latex-default-figure-position)))
3366 (multicolumn-p (string= "multicolumn" float))
3367 (float-env
3368 (cond
3369 ((or caption multicolumn-p)
3370 (cons
3371 (concat "\\begin{listing" (when multicolumn-p "*")
3372 "}[" placement "]\n"
3373 (if caption-above-p caption-str ""))
3374 (concat "\n" (if caption-above-p "" caption-str)
3375 "\\end{listing" (when multicolumn-p "*") "}")))
3376 ((string= "t" float)
3377 (cons
3378 (concat "\\begin{listing}[" placement "]\n")
3379 "\n\\end{listing}"))))
3380 (options (plist-get info :latex-minted-options))
3381 (body
3382 (format
3383 "\\begin{minted}[%s]{%s}\n%s\\end{minted}"
3384 ;; Options.
3385 (concat
3386 (org-latex--make-option-string
3387 (if (or (not num-start) (assoc "linenos" options))
3388 options
3389 (append
3390 `(("linenos")
3391 ("firstnumber" ,(number-to-string (1+ num-start))))
3392 options)))
3393 (let ((local-options (plist-get attributes :options)))
3394 (and local-options (concat "," local-options))))
3395 ;; Language.
3396 (or (cadr (assq (intern lang)
3397 (plist-get info :latex-minted-langs)))
3398 (downcase lang))
3399 ;; Source code.
3400 (let* ((code-info (org-export-unravel-code src-block))
3401 (max-width
3402 (apply 'max
3403 (mapcar 'string-width
3404 (org-split-string (car code-info)
3405 "\n")))))
3406 (org-export-format-code
3407 (car code-info)
3408 (lambda (loc _num ref)
3409 (concat
3410 loc
3411 (when ref
3412 ;; Ensure references are flushed to the right,
3413 ;; separated with 6 spaces from the widest line
3414 ;; of code.
3415 (concat (make-string (+ (- max-width (length loc)) 6)
3416 ?\s)
3417 (format "(%s)" ref)))))
3418 nil (and retain-labels (cdr code-info)))))))
3419 (concat (car float-env) body (cdr float-env))))
3420
3421 (defun org-latex-src--engrave-mathescape-p (info options)
3422 "From the export INFO plist, and the per-block OPTIONS, determine mathescape."
3423 (let ((default-options (plist-get info :latex-engraved-options))
3424 (mathescape-status
3425 (lambda (opts)
3426 (cl-some
3427 (lambda (opt)
3428 (or (and
3429 (null (cdr opt))
3430 (cond
3431 ((string-match-p
3432 "\\(?:^\\|,\\)mathescape=false\\(?:,\\|$\\)"
3433 (car opt))
3434 'no)
3435 ((or (string-match-p
3436 "\\(?:^\\|,\\)mathescape\\(?:=true\\)?\\(?:,\\|$\\)"
3437 (car opt))
3438 (string= "mathescape" (car opt)))
3439 'yes)))
3440 (and
3441 (string= (car opt) "mathescape")
3442 (cond
3443 ((or (and (stringp (cdr opt)) (string= (cdr opt) "true"))
3444 (equal '("true") (cdr opt)))
3445 'yes)
3446 ((or (and (stringp (cdr opt)) (string= "false" (cdr opt)))
3447 (equal '("false") (cdr opt)))
3448 'no)))))
3449 opts))))
3450 (let ((mathescape (or (funcall mathescape-status default-options)
3451 (funcall mathescape-status options))))
3452 (when (eq mathescape 'yes)
3453 (or engrave-faces-latex-mathescape t)))))
3454
3455 (defun org-latex-src--engrave-code (content lang &optional theme options inline)
3456 "Engrave CONTENT to LaTeX in a LANG-mode buffer, and give the result.
3457 When the THEME symbol is non-nil, that theme will be used.
3458
3459 When INLINE is nil, a Verbatim environment wrapped in a Code
3460 environment will be used. When t, a Verb command will be used.
3461
3462 When OPTIONS is provided, as either a string or list of key-value
3463 pairs accepted by `org-latex--make-option-string', it is passed
3464 to the Verbatim environment or Verb command."
3465 (if (require 'engrave-faces-latex nil t)
3466 (let* ((lang-mode (and lang (org-src-get-lang-mode lang)))
3467 (engrave-faces-current-preset-style
3468 (if theme
3469 (engrave-faces-get-theme theme)
3470 engrave-faces-current-preset-style))
3471 (engraved-buffer
3472 (with-temp-buffer
3473 (insert (replace-regexp-in-string "\n\\'" "" content))
3474 (when lang-mode
3475 (if (functionp lang-mode)
3476 (funcall lang-mode)
3477 (message "Cannot engrave code as %s. %s is undefined."
3478 lang lang-mode)))
3479 (engrave-faces-latex-buffer)))
3480 (engraved-code
3481 (with-current-buffer engraved-buffer
3482 (buffer-string)))
3483 (engraved-options
3484 (when options
3485 (concat "["
3486 (if (listp options)
3487 (org-latex--make-option-string options)
3488 options)
3489 "]")))
3490 (engraved-wrapped
3491 (if inline
3492 (concat "\\Verb" engraved-options "{" engraved-code "}")
3493 (concat "\\begin{Code}\n\\begin{Verbatim}" engraved-options "\n"
3494 engraved-code "\n\\end{Verbatim}\n\\end{Code}"))))
3495 (kill-buffer engraved-buffer)
3496 (if theme
3497 (concat "{\\engravedtheme"
3498 (replace-regexp-in-string "[^A-Za-z]" ""
3499 (symbol-name theme))
3500 engraved-wrapped
3501 "}")
3502 engraved-wrapped))
3503 (user-error "Cannot engrave code as `engrave-faces-latex' is unavailable.")))
3504
3505 (cl-defun org-latex-src-block--engraved
3506 (&key src-block info lang caption caption-above-p num-start retain-labels attributes float &allow-other-keys)
3507 "Transcode a SRC-BLOCK element from Org to LaTeX, using engrave-faces-latex.
3508 LANG, CAPTION, CAPTION-ABOVE-P, LABEL, NUM-START, RETAIN-LABELS, ATTRIBUTES
3509 and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
3510 (let* ((caption-str (org-latex--caption/label-string src-block info))
3511 (placement (or (org-unbracket-string "[" "]" (plist-get attributes :placement))
3512 (plist-get info :latex-default-figure-position)))
3513 (multicolumn-p (string= "multicolumn" float))
3514 (float-env
3515 (cond
3516 ((or caption multicolumn-p)
3517 (cons
3518 (concat "\\begin{listing" (when multicolumn-p "*")
3519 "}[" placement "]\n"
3520 (if caption-above-p caption-str ""))
3521 (concat "\n" (if caption-above-p "" caption-str)
3522 "\\end{listing" (when multicolumn-p "*") "}")))
3523 ((string= "t" float)
3524 (cons
3525 (concat "\\begin{listing}[" placement "]\n")
3526 "\n\\end{listing}"))))
3527 (options
3528 (let ((engraved-options (plist-get info :latex-engraved-options))
3529 (local-options (plist-get attributes :options)))
3530 (append
3531 (when (and num-start (not (assoc "linenos" engraved-options)))
3532 `(("linenos")
3533 ("firstnumber" ,(number-to-string (1+ num-start)))))
3534 (and local-options `((,local-options))))))
3535 (engraved-theme (plist-get attributes :engraved-theme))
3536 (content
3537 (let* ((code-info (org-export-unravel-code src-block))
3538 (max-width
3539 (apply 'max
3540 (mapcar 'string-width
3541 (org-split-string (car code-info)
3542 "\n")))))
3543 (org-export-format-code
3544 (car code-info)
3545 (lambda (loc _num ref)
3546 (concat
3547 loc
3548 (when ref
3549 ;; Ensure references are flushed to the right,
3550 ;; separated with 6 spaces from the widest line
3551 ;; of code.
3552 (concat (make-string (+ (- max-width (length loc)) 6)
3553 ?\s)
3554 (format "(%s)" ref)))))
3555 nil (and retain-labels (cdr code-info)))))
3556 (body
3557 (let ((engrave-faces-latex-mathescape
3558 (org-latex-src--engrave-mathescape-p info options)))
3559 (org-latex-src--engrave-code
3560 content lang
3561 (when engraved-theme (intern engraved-theme))
3562 options))))
3563 (concat (car float-env) body (cdr float-env))))
3564
3565 (cl-defun org-latex-src-block--listings
3566 (&key src-block info lang caption caption-above-p label num-start retain-labels attributes float &allow-other-keys)
3567 "Transcode a SRC-BLOCK element from Org to LaTeX, using listings.
3568 LANG, CAPTION, CAPTION-ABOVE-P, LABEL, NUM-START, RETAIN-LABELS, ATTRIBUTES
3569 and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
3570 (let ((lst-lang
3571 (or (cadr (assq (intern lang)
3572 (plist-get info :latex-listings-langs)))
3573 lang))
3574 (caption-str
3575 (when caption
3576 (let ((main (org-export-get-caption src-block))
3577 (secondary (org-export-get-caption src-block t)))
3578 (if (not secondary)
3579 (format "{%s}" (org-export-data main info))
3580 (format "{[%s]%s}"
3581 (org-export-data secondary info)
3582 (org-export-data main info))))))
3583 (lst-opt (plist-get info :latex-listings-options)))
3584 (concat
3585 (format
3586 "\\begin{lstlisting}[%s]\n%s\\end{lstlisting}"
3587 ;; Options.
3588 (concat
3589 (org-latex--make-option-string
3590 (append
3591 lst-opt
3592 (cond
3593 ((and (not float) (plist-member attributes :float)) nil)
3594 ((string= "multicolumn" float) '(("float" "*")))
3595 ((and float (not (assoc "float" lst-opt)))
3596 `(("float" ,(plist-get info :latex-default-figure-position)))))
3597 `(("language" ,lst-lang))
3598 (if label
3599 `(("label" ,(org-latex--label src-block info)))
3600 '(("label" " ")))
3601 (if caption-str `(("caption" ,caption-str)) '(("caption" " ")))
3602 `(("captionpos" ,(if caption-above-p "t" "b")))
3603 (cond ((assoc "numbers" lst-opt) nil)
3604 ((not num-start) '(("numbers" "none")))
3605 (t `(("firstnumber" ,(number-to-string (1+ num-start)))
3606 ("numbers" "left"))))))
3607 (let ((local-options (plist-get attributes :options)))
3608 (and local-options (concat "," local-options))))
3609 ;; Source code.
3610 (let* ((code-info (org-export-unravel-code src-block))
3611 (max-width
3612 (apply 'max
3613 (mapcar 'string-width
3614 (org-split-string (car code-info) "\n")))))
3615 (org-export-format-code
3616 (car code-info)
3617 (lambda (loc _num ref)
3618 (concat
3619 loc
3620 (when ref
3621 ;; Ensure references are flushed to the right,
3622 ;; separated with 6 spaces from the widest line of
3623 ;; code
3624 (concat (make-string (+ (- max-width (length loc)) 6) ?\s)
3625 (format "(%s)" ref)))))
3626 nil (and retain-labels (cdr code-info))))))))
31523627
31533628 ;;;; Statistics Cookie
31543629
31893664 ;; `org-latex-table' is the entry point for table transcoding. It
31903665 ;; takes care of tables with a "verbatim" mode. Otherwise, it
31913666 ;; delegates the job to either `org-latex--table.el-table',
3192 ;; `org-latex--org-table' or `org-latex--math-table' functions,
3667 ;; `org-latex--org-table', `org-latex--math-table' or
3668 ;; `org-latex--org-tabbing' functions,
31933669 ;; depending of the type of the table and the mode requested.
31943670 ;;
31953671 ;; `org-latex--align-string' is a subroutine used to build alignment
32133689 `(table nil ,@(org-element-contents table))))))
32143690 ;; Case 2: Matrix.
32153691 ((or (string= type "math") (string= type "inline-math"))
3216 (org-latex--math-table table info))
3217 ;; Case 3: Standard table.
3692 (org-latex--math-table table info))
3693 ;; Case 3: Tabbing
3694 ((string= type "tabbing")
3695 (org-table--org-tabbing table contents info))
3696 ;; Case 4: Standard table.
32183697 (t (concat (org-latex--org-table table contents info)
32193698 ;; When there are footnote references within the
32203699 ;; table, insert their definition just after it.
32513730 info)
32523731 (apply 'concat (nreverse align)))))
32533732
3733 (defun org-latex--align-string-tabbing (table info)
3734 "Return LaTeX alignment string using tabbing environment.
3735 TABLE is the considered table. INFO is a plist used as
3736 a communication channel."
3737 (or (org-export-read-attribute :attr_latex table :align)
3738 (let* ((count
3739 ;; Count the number of cells in the first row.
3740 (length
3741 (org-element-map
3742 (org-element-map table 'table-row
3743 (lambda (row)
3744 (and (eq (org-element-property :type row)
3745 'standard)
3746 row))
3747 info 'first-match)
3748 'table-cell #'identity)))
3749 ;; Calculate the column width, using a proportion of
3750 ;; the document's textwidth.
3751 (separator
3752 (format "\\hspace{%s\\textwidth} \\= "
3753 (- (/ 1.0 count) 0.01))))
3754 (concat (apply 'concat (make-list count separator))
3755 "\\kill"))))
3756
32543757 (defun org-latex--decorate-table (table attributes caption above? info)
32553758 "Decorate TABLE string with caption and float environment.
32563759
32653768 (cond ((and (not float) (plist-member attributes :float)) nil)
32663769 ((member float '("sidewaystable" "sideways")) "sidewaystable")
32673770 ((equal float "multicolumn") "table*")
3771 ((string= float "t") "table")
32683772 (float float)
32693773 ((org-string-nw-p caption) "table")
32703774 (t nil))))
33133817 `table' as its `:mode' attribute."
33143818 (let* ((attr (org-export-read-attribute :attr_latex table))
33153819 (alignment (org-latex--align-string table info))
3820 (opt (org-export-read-attribute :attr_latex table :options))
33163821 (table-env (or (plist-get attr :environment)
33173822 (plist-get info :latex-default-table-environment)))
33183823 (width
33343839 (format "\\begin{%s}%s{%s}\n" table-env width alignment)
33353840 (and above?
33363841 (org-string-nw-p caption)
3337 (concat caption "\\\\\n"))
3842 (concat caption org-latex-line-break-safe "\n"))
33383843 contents
33393844 (and (not above?)
33403845 (org-string-nw-p caption)
3341 (concat caption "\\\\\n"))
3846 (concat caption org-latex-line-break-safe "\n"))
33423847 (format "\\end{%s}" table-env)
33433848 (and fontsize "}"))))
33443849 (t
3345 (let ((output (format "\\begin{%s}%s{%s}\n%s\\end{%s}"
3850 (let ((output (format "\\begin{%s}%s%s{%s}\n%s\\end{%s}"
33463851 table-env
3852 (if opt (format "[%s]" opt) "")
33473853 width
33483854 alignment
33493855 contents
33503856 table-env)))
33513857 (org-latex--decorate-table output attr caption above? info))))))
3858
3859
3860 (defun org-table--org-tabbing (table contents info)
3861 "Return tabbing environment LaTeX code for Org table.
3862 TABLE is the table type element to transcode. CONTENTS is its
3863 contents, as a string. INFO is a plist used as a communication
3864 channel.
3865
3866 This function assumes TABLE has `org' as its `:type' property and
3867 `tabbing' as its `:mode' attribute."
3868 (format "\\begin{%s}\n%s\n%s\\end{%s}"
3869 "tabbing"
3870 (org-latex--align-string-tabbing table info)
3871 contents
3872 "tabbing"))
33523873
33533874 (defun org-latex--table.el-table (table info)
33543875 "Return appropriate LaTeX code for a table.el table.
34073928 (lambda (cell)
34083929 (substring (org-element-interpret-data cell) 0 -1))
34093930 (org-element-map row 'table-cell #'identity info) "&")
3410 (or (cdr (assoc env org-latex-table-matrix-macros)) "\\\\")
3931 (or (cdr (assoc env org-latex-table-matrix-macros)) org-latex-line-break-safe)
34113932 "\n")))
34123933 (org-element-map table 'table-row #'identity info) "")))
34133934 (concat
34333954 "Transcode a TABLE-CELL element from Org to LaTeX.
34343955 CONTENTS is the cell contents. INFO is a plist used as
34353956 a communication channel."
3436 (concat
3437 (let ((scientific-format (plist-get info :latex-table-scientific-notation)))
3957 (let ((type (org-export-read-attribute
3958 :attr_latex (org-export-get-parent-table table-cell) :mode))
3959 (scientific-format (plist-get info :latex-table-scientific-notation)))
3960 (concat
34383961 (if (and contents
34393962 scientific-format
34403963 (string-match orgtbl-exp-regexp contents))
34433966 (format scientific-format
34443967 (match-string 1 contents)
34453968 (match-string 2 contents))
3446 contents))
3447 (when (org-export-get-next-element table-cell info) " & ")))
3969 contents)
3970 (when (org-export-get-next-element table-cell info)
3971 (if (string= type "tabbing") " \\> " " & ")))))
34483972
34493973
34503974 ;;;; Table Row
34764000 ;; hline was specifically marked.
34774001 (and booktabsp (not (org-export-get-previous-element table-row info))
34784002 "\\toprule\n")
3479 contents "\\\\\n"
4003 contents org-latex-line-break-safe "\n"
34804004 (cond
34814005 ;; Special case for long tables. Define header and footers.
34824006 ((and longtablep (org-export-table-row-ends-header-p table-row info))
34844008 (org-export-get-parent-table table-row) info))))
34854009 (format "%s
34864010 \\endfirsthead
3487 \\multicolumn{%d}{l}{%s} \\\\
4011 \\multicolumn{%d}{l}{%s} \\\\[0pt]
34884012 %s
3489 %s \\\\\n
4013 %s \\\\[0pt]\n
34904014 %s
34914015 \\endhead
34924016 %s\\multicolumn{%d}{r}{%s} \\\\
35844108 (replace-regexp-in-string
35854109 "^[ \t]+" (lambda (m) (format "\\hspace*{%dem}" (length m)))
35864110 (replace-regexp-in-string
3587 "^[ \t]*\\\\\\\\$" "\\vspace*{1em}"
4111 (concat "^[ \t]*" (regexp-quote org-latex-line-break-safe) "$")
4112 "\\vspace*{1em}"
35884113 (replace-regexp-in-string
3589 "\\([ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n"
3590 contents nil t) nil t) nil t) linreset)
4114 "\\([ \t]*\\\\\\\\\\)?[ \t]*\n"
4115 (concat org-latex-line-break-safe "\n")
4116 contents nil t)
4117 nil t)
4118 nil t)
4119 linreset)
35914120 info)
35924121 ;; Insert footnote definitions, if any, after the environment, so
35934122 ;; the special formatting above is not applied to them.
37304259 t)
37314260 (progn (beginning-of-line) (looking-at-p "%"))
37324261 (match-string 0)))
4262 ;; Cannot find the compiler inserted by
4263 ;; `org-latex-template' -> `org-latex--insert-compiler'.
4264 ;; Use a fallback.
37334265 "pdflatex"))
37344266 (process (if (functionp org-latex-pdf-process) org-latex-pdf-process
37354267 ;; Replace "%latex" with "%L" and "%bib" and
00 ;;; ox-man.el --- Man Back-End for Org Export Engine -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2011-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2011-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
55 ;; Luis R Anaya <papoanaya aroba hot mail punto com>
3535 ;; "MAN_CLASS_OPTIONS".
3636
3737 ;;; Code:
38
39 (require 'org-macs)
40 (org-assert-version)
3841
3942 (require 'cl-lib)
4043 (require 'ox)
222225 Alternatively, this may be a Lisp function that does the
223226 processing. This function should accept the file name as
224227 its single argument."
225 :group 'org-export-pdf
226228 :group 'org-export-man
227229 :version "24.4"
228230 :package-version '(Org . "8.0")
00 ;;; ox-md.el --- Markdown Back-End for Org Export Engine -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2012-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2012-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
5 ;; Maintainer: Nicolas Goaziou <n.goaziou at gmail dot com>
5 ;; Maintainer: Nicolas Goaziou <mail@nicolasgoaziou.fr>
66 ;; Keywords: org, wp, markdown
77
88 ;; This file is part of GNU Emacs.
2727 ;; information.
2828
2929 ;;; Code:
30
31 (require 'org-macs)
32 (org-assert-version)
3033
3134 (require 'cl-lib)
3235 (require 'ox-html)
6972 :type 'string
7073 :version "26.1"
7174 :package-version '(Org . "9.0"))
75
76 (defcustom org-md-toplevel-hlevel 1
77 "Heading level to use for level 1 Org headings in markdown export.
78
79 If this is 1, headline levels will be preserved on export. If this is
80 2, top level Org headings will be exported to level 2 markdown
81 headings, level 2 Org headings will be exported to level 3 markdown
82 headings, and so on.
83
84 Incrementing this value may be helpful when creating markdown to be
85 included into another document or application that reserves top-level
86 headings for its own use."
87 :group 'org-export-md
88 :package-version '(Org . "9.6")
89 ;; Avoid `natnum' because that's not available until Emacs 28.1.
90 :type 'integer)
91
7292
7393
7494 ;;; Define Back-End
119139 :options-alist
120140 '((:md-footnote-format nil nil org-md-footnote-format)
121141 (:md-footnotes-section nil nil org-md-footnotes-section)
122 (:md-headline-style nil nil org-md-headline-style)))
142 (:md-headline-style nil nil org-md-headline-style)
143 (:md-toplevel-hlevel nil nil org-md-toplevel-hlevel)))
123144
124145
125146 ;;; Filters
192213 ;; A link refers internally to HEADLINE.
193214 (org-element-map (plist-get info :parse-tree) 'link
194215 (lambda (link)
195 (eq headline
196 (pcase (org-element-property :type link)
197 ((or "custom-id" "id") (org-export-resolve-id-link link info))
198 ("fuzzy" (org-export-resolve-fuzzy-link link info))
199 (_ nil))))
216 (equal headline
217 ;; Ignore broken links.
218 (condition-case nil
219 (org-export-resolve-id-link link info)
220 (org-link-broken nil))))
200221 info t))))
201222
202223 (defun org-md--headline-title (style level title &optional anchor tags)
228249 contents according to the specified element."
229250 (concat
230251 (unless scope
231 (let ((style (plist-get info :md-headline-style))
252 (let ((level (plist-get info :md-toplevel-hlevel))
253 (style (plist-get info :md-headline-style))
232254 (title (org-html--translate "Table of Contents" info)))
233 (org-md--headline-title style 1 title nil)))
255 (org-md--headline-title style level title nil)))
234256 (mapconcat
235257 (lambda (headline)
236258 (let* ((indentation
349371 CONTENTS is the headline contents. INFO is a plist used as
350372 a communication channel."
351373 (unless (org-element-property :footnote-section-p headline)
352 (let* ((level (org-export-get-relative-level headline info))
374 (let* ((level (+ (org-export-get-relative-level headline info)
375 (1- (plist-get info :md-toplevel-hlevel))))
353376 (title (org-export-data (org-element-property :title headline) info))
354377 (todo (and (plist-get info :with-todo-keywords)
355378 (let ((todo (org-element-property :todo-keyword
462485 (_ (org-export-with-backend 'html keyword contents info))))
463486
464487
465 ;;;; Latex Environment
488 ;;;; LaTeX Environment
466489
467490 (defun org-md-latex-environment (latex-environment _contents info)
468491 "Transcode a LATEX-ENVIRONMENT object from Org to Markdown.
477500 latex-frag)
478501 latex-frag))))
479502
480 ;;;; Latex Fragment
503 ;;;; LaTeX Fragment
481504
482505 (defun org-md-latex-fragment (latex-fragment _contents info)
483506 "Transcode a LATEX-FRAGMENT object from Org to Markdown.
00 ;;; ox-odt.el --- OpenDocument Text Exporter for Org Mode -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2010-2023 Free Software Foundation, Inc.
33
44 ;; Author: Jambunathan K <kjambunathan at gmail dot com>
55 ;; Keywords: outlines, hypermedia, calendar, wp
6 ;; Homepage: https://orgmode.org
6 ;; URL: https://orgmode.org
77
88 ;; This file is part of GNU Emacs.
99
2323 ;;; Commentary:
2424
2525 ;;; Code:
26
27 (require 'org-macs)
28 (org-assert-version)
2629
2730 (require 'cl-lib)
2831 (require 'format-spec)
3033 (require 'org-macs)
3134 (require 'ox)
3235 (require 'table nil 'noerror)
36
37 (declare-function org-at-heading-p "org" (&optional _))
38 (declare-function org-back-to-heading "org" (&optional invisible-ok))
39 (declare-function org-next-visible-heading "org" (arg))
3340
3441 ;;; Define Back-End
3542
361368 component xml buffers before they are saved. Turn this off for
362369 regular use. Turn this on if you need to examine the xml
363370 visually."
364 :group 'org-export-odt
365371 :version "24.1"
366372 :type 'boolean)
367373
398404 :type '(choice
399405 (const :tag "Not set" nil)
400406 (directory :tag "Schema directory"))
401 :group 'org-export-odt
402407 :version "24.1"
403408 :set
404409 (lambda (var value)
405410 "Set `org-odt-schema-dir'.
406411 Also add it to `rng-schema-locating-files'."
407412 (let ((schema-dir value))
408 (set var
413 (set-default-toplevel-value var
409414 (if (and
410415 (file-expand-wildcards
411416 (expand-file-name "od-manifest-schema*.rnc" schema-dir))
436441 under `org-odt-styles-dir' is used."
437442 :type '(choice (const nil)
438443 (file))
439 :group 'org-export-odt
440444 :version "24.3")
441445
442446 (defcustom org-odt-styles-file nil
470474
471475 #+ODT_STYLES_FILE: \"/path/to/styles.xml\" or
472476 #+ODT_STYLES_FILE: (\"/path/to/file.ott\" (\"styles.xml\" \"image/hdr.png\"))."
473 :group 'org-export-odt
474477 :version "24.1"
475478 :type
476479 '(choice
485488
486489 (defcustom org-odt-display-outline-level 2
487490 "Outline levels considered for enumerating captioned entities."
488 :group 'org-export-odt
489491 :version "24.4"
490492 :package-version '(Org . "8.0")
491493 :type 'integer)
515517 %d output dir in full
516518 %D output dir as a URL.
517519 %x extra options as set in `org-odt-convert-capabilities'."
518 :group 'org-export-odt
519520 :version "24.1"
520521 :type
521522 '(choice
528529 "Use this converter to convert from \"odt\" format to other formats.
529530 During customization, the list of converter names are populated
530531 from `org-odt-convert-processes'."
531 :group 'org-export-odt
532532 :version "24.1"
533533 :type '(choice :convert-widget
534534 (lambda (w)
590590 with that class.
591591
592592 See default setting of this variable for a typical configuration."
593 :group 'org-export-odt
594593 :version "24.1"
595594 :type
596595 '(choice
617616
618617 You can set this option on per-file basis using file local
619618 values. See Info node `(emacs) File Variables'."
620 :group 'org-export-odt
621619 :version "24.1"
622620 :type '(choice :convert-widget
623621 (lambda (w)
643641 The function should return the string to be exported.
644642
645643 The default value simply returns the value of CONTENTS."
646 :group 'org-export-odt
647644 :version "26.1"
648645 :package-version '(Org . "8.3")
649646 :type 'function)
663660 TAGS the tags string, separated with colons (string or nil).
664661
665662 The function result will be used as headline text."
666 :group 'org-export-odt
667663 :version "26.1"
668664 :package-version '(Org . "8.3")
669665 :type 'function)
684680 CONTENTS the contents of the inlinetask, as a string.
685681
686682 The function should return the string to be exported."
687 :group 'org-export-odt
688683 :version "26.1"
689684 :package-version '(Org . "8.3")
690685 :type 'function)
711706 be loaded.
712707
713708 Any other symbol is a synonym for `mathjax'."
714 :group 'org-export-odt
715709 :version "24.4"
716710 :package-version '(Org . "8.0")
717711 :type '(choice
731725 A rule consists in an association whose key is the type of link
732726 to consider, and value is a regexp that will be matched against
733727 link's path."
734 :group 'org-export-odt
735728 :version "24.4"
736729 :package-version '(Org . "8.0")
737730 :type '(alist :key-type (string :tag "Type")
744737 A rule consists in an association whose key is the type of link
745738 to consider, and value is a regexp that will be matched against
746739 link's path."
747 :group 'org-export-odt
748740 :version "26.1"
749741 :package-version '(Org . "8.3")
750742 :type '(alist :key-type (string :tag "Type")
755747 Use this for sizing of embedded images. See Info node `(org)
756748 Images in ODT export' for more information."
757749 :type 'float
758 :group 'org-export-odt
759750 :version "24.4"
760751 :package-version '(Org . "8.1"))
761752
777768
778769 This variable is effective only if `org-odt-fontify-srcblocks' is
779770 turned on."
780 :group 'org-export-odt
781771 :version "24.1"
782772 :type 'boolean)
783773
787777 blocks in the exported file. For colorization to work, you need
788778 to make available an enhanced version of `htmlfontify' library."
789779 :type 'boolean
790 :group 'org-export-odt
791780 :version "24.1")
792781
793782
872861 The TABLE-STYLE-NAME \"OrgEquation\" is used internally for
873862 formatting of numbered display equations. Do not delete this
874863 style from the list."
875 :group 'org-export-odt
876864 :version "24.1"
877865 :type '(choice
878866 (const :tag "None" nil)
917905 the application UI or through a custom styles file.
918906
919907 See `org-odt--build-date-styles' for implementation details."
920 :group 'org-export-odt
921908 :version "24.4"
922909 :package-version '(Org . "8.0")
923910 :type 'boolean)
932919 (let* ((format-timestamp
933920 (lambda (timestamp format &optional end utc)
934921 (if timestamp
935 (org-timestamp-format timestamp format end utc)
922 (org-format-timestamp timestamp format end utc)
936923 (format-time-string format nil utc))))
937924 (has-time-p (or (not timestamp)
938925 (org-timestamp-has-time-p timestamp)))
948935 ;; don't bother about formatting the date contents to be
949936 ;; compatible with "OrgDate1" and "OrgDateTime" styles. A
950937 ;; simple Org-style date should suffice.
951 (date (let* ((formats
952 (if org-display-custom-times
953 (cons (substring
954 (car org-time-stamp-custom-formats) 1 -1)
955 (substring
956 (cdr org-time-stamp-custom-formats) 1 -1))
957 '("%Y-%m-%d %a" . "%Y-%m-%d %a %H:%M")))
958 (format (if has-time-p (cdr formats) (car formats))))
938 (date (let ((format (org-time-stamp-format
939 has-time-p 'no-brackets 'custom)))
959940 (funcall format-timestamp timestamp format end)))
960941 (repeater (let ((repeater-type (org-element-property
961942 :repeater-type timestamp))
14341415 ;; value before moving on to temp-buffer context down below.
14351416 (custom-time-fmts
14361417 (if org-display-custom-times
1437 (cons (substring (car org-time-stamp-custom-formats) 1 -1)
1438 (substring (cdr org-time-stamp-custom-formats) 1 -1))
1418 (cons (org-time-stamp-format
1419 nil 'no-brackets 'custom)
1420 (org-time-stamp-format
1421 'with-time 'no-brackets 'custom))
14391422 '("%Y-%M-%d %a" . "%Y-%M-%d %a %H:%M"))))
14401423 (with-temp-buffer
14411424 (insert-file-contents
20021985 (ignore))))))))
20031986
20041987
2005 ;;;; Latex Environment
2006
1988 ;;;; LaTeX Environment
20071989
20081990 ;; (eval-after-load 'ox-odt '(ad-deactivate 'org-format-latex-as-mathml))
2009 ;; (defadvice org-format-latex-as-mathml ; FIXME
2010 ;; (after org-odt-protect-latex-fragment activate)
1991 ;; (advice-add 'org-format-latex-as-mathml ; FIXME
1992 ;; :around #'org--odt-protect-latex-fragment)
1993 ;; (defun org--odt-protect-latex-fragment (orig-fun latex-frag &rest args)
20111994 ;; "Encode LaTeX fragment as XML.
20121995 ;; Do this when translation to MathML fails."
2013 ;; (unless (> (length ad-return-value) 0)
2014 ;; (setq ad-return-value (org-odt--encode-plain-text (ad-get-arg 0)))))
1996 ;; (let ((retval (apply orig-fun latex-frag args)))
1997 ;; (if (> (length retval) 0)
1998 ;; retval
1999 ;; (org-odt--encode-plain-text latex-frag))))
20152000
20162001 (defun org-odt-latex-environment (latex-environment _contents info)
20172002 "Transcode a LATEX-ENVIRONMENT element from Org to ODT.
20212006 (org-odt-do-format-code latex-frag info)))
20222007
20232008
2024 ;;;; Latex Fragment
2009 ;;;; LaTeX Fragment
20252010
20262011 ;; (when latex-frag ; FIXME
20272012 ;; (setq href (propertize href :title "LaTeX Fragment"
26982683 ((member type '("http" "https" "ftp" "mailto"))
26992684 (concat type ":" raw-path))
27002685 ((string= type "file")
2701 (org-export-file-uri raw-path))
2686 (let ((path-uri (org-export-file-uri raw-path)))
2687 (if (string-prefix-p "file://" path-uri)
2688 path-uri
2689 ;; Otherwise, it is a relative path.
2690 ;; OpenOffice treats base directory inside the odt
2691 ;; archive. The directory containing the odt file
2692 ;; is "../".
2693 (concat "../" path-uri))))
27022694 (t raw-path)))
27032695 ;; Convert & to &amp; for correct XML representation
27042696 (path (replace-regexp-in-string "&" "&amp;" path)))
27472739 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
27482740 (org-export-get-reference destination info)
27492741 (or desc (org-export-get-ordinal destination info))))
2742 ;; Link to a file, corresponding to string return value of
2743 ;; `org-export-resolve-id-link'. Export it is file link.
2744 (plain-text
2745 (let ((file-link (org-element-copy link)))
2746 (org-element-put-property file-link :type "file")
2747 (org-element-put-property file-link :path destination)
2748 (org-element-put-property
2749 file-link
2750 :raw-link (format "file:%s" destination))
2751 (org-odt-link file-link desc info)))
27502752 ;; Fuzzy link points to some element (e.g., an inline image,
27512753 ;; a math formula or a table).
27522754 (otherwise
29132915 (setq output
29142916 (replace-regexp-in-string (car pair) (cdr pair) output t nil))))
29152917 ;; Handle break preservation if required.
2916 (when (plist-get info :preserve-breaks)
2917 (setq output (replace-regexp-in-string
2918 "\\(\\\\\\\\\\)?[ \t]*\n" "<text:line-break/>" output t)))
2918 (if (plist-get info :preserve-breaks)
2919 (setq output (replace-regexp-in-string
2920 "\\(\\\\\\\\\\)?[ \t]*\n" "<text:line-break/>" output t))
2921 ;; OpenDocument schema recognizes newlines as spaces, which may
2922 ;; not be desired in scripts that do not separate words with
2923 ;; spaces (for example, Han script). `fill-region' is able to
2924 ;; handle such situations.
2925 ;; FIXME: The unnecessary spacing may still remain when a newline
2926 ;; is at a boundary between Org objects (e.g. italics markup
2927 ;; followed by newline).
2928 (when (org-string-nw-p output) ; blank string needs not to be re-filled
2929 (setq output
2930 (with-temp-buffer
2931 (save-match-data
2932 (let ((leading (and (string-match (rx bos (1+ blank)) output)
2933 (match-string 0 output)))
2934 (trailing (and (string-match (rx (1+ blank) eos) output)
2935 (match-string 0 output))))
2936 (insert
2937 (substring
2938 output
2939 (length leading)
2940 (pcase (length trailing)
2941 (0 nil)
2942 (n (- n)))))
2943 ;; Unfill, retaining leading/trailing space.
2944 (let ((fill-column most-positive-fixnum))
2945 (fill-region (point-min) (point-max)))
2946 (concat leading (buffer-string) trailing)))))))
29192947 ;; Return value.
29202948 output))
29212949
31003128 (with-temp-buffer
31013129 (insert code)
31023130 (funcall lang-mode)
3103 (org-font-lock-ensure)
3131 (font-lock-ensure)
31043132 (buffer-string))))
31053133 (fontifier (if use-htmlfontify-p 'org-odt-htmlfontify-string
31063134 'org-odt--encode-plain-text))
32263254 When STYLE-SPEC is nil, style the table cell the conventional way
32273255 - choose cell borders based on row and column groupings and
32283256 choose paragraph alignment based on `org-col-cookies' text
3229 property. See also
3230 `org-odt-get-paragraph-style-cookie-for-table-cell'.
3257 property. See also `org-odt-table-style-spec'.
32313258
32323259 When STYLE-SPEC is non-nil, ignore the above cookie and return
32333260 styles congruent with the ODF-1.2 specification."
35723599 ;; item, but also within description lists and low-level
35733600 ;; headlines.
35743601
3575 ;; See `org-odt-translate-description-lists' and
3576 ;; `org-odt-translate-low-level-headlines' for how this is
3602 ;; See `org-odt--translate-description-lists' for how this is
35773603 ;; tackled.
35783604
35793605 (concat "\n"
00 ;;; ox-org.el --- Org Back-End for Org Export Engine -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2013-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2013-2023 Free Software Foundation, Inc.
33
44 ;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
5 ;; Maintainer: Nicolas Goaziou <n.goaziou at gmail dot com>
5 ;; Maintainer: Nicolas Goaziou <mail@nicolasgoaziou.fr>
66 ;; Keywords: org, wp
77
88 ;; This file is part of GNU Emacs.
2323 ;;; Commentary:
2424
2525 ;;; Code:
26
27 (require 'org-macs)
28 (org-assert-version)
2629
2730 (require 'ox)
2831 (declare-function htmlize-buffer "ext:htmlize" (&optional buffer))
327330 (work-buffer (or visitingp (find-file-noselect filename)))
328331 newbuf)
329332 (with-current-buffer work-buffer
330 (org-font-lock-ensure)
331 (org-show-all)
333 (font-lock-ensure)
334 (org-fold-show-all)
332335 (setq newbuf (htmlize-buffer)))
333336 (with-current-buffer newbuf
334337 (when org-org-htmlized-css-url
00 ;;; ox-publish.el --- Publish Related Org Mode Files as a Website -*- lexical-binding: t; -*-
1 ;; Copyright (C) 2006-2021 Free Software Foundation, Inc.
1 ;; Copyright (C) 2006-2023 Free Software Foundation, Inc.
22
33 ;; Author: David O'Toole <dto@gnu.org>
4 ;; Maintainer: Nicolas Goaziou <n.goaziou at gmail dot com>
4 ;; Maintainer: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55 ;; Keywords: hypermedia, outlines, wp
66
77 ;; This file is part of GNU Emacs.
3737
3838 ;;; Code:
3939
40 (require 'org-macs)
41 (org-assert-version)
42
4043 (require 'cl-lib)
4144 (require 'format-spec)
4245 (require 'ox)
4346
47 (declare-function org-at-heading-p "org" (&optional _))
48 (declare-function org-back-to-heading "org" (&optional invisible-ok))
49 (declare-function org-next-visible-heading "org" (arg))
4450
4551
4652 ;;; Variables
378384 "Update publishing timestamp for file FILENAME.
379385 If there is no timestamp, create one."
380386 (let ((key (org-publish-timestamp-filename filename pub-dir pub-func))
381 (stamp (org-publish-cache-ctime-of-src filename)))
387 (stamp (org-publish-cache-mtime-of-src filename)))
382388 (org-publish-cache-set key stamp)))
383389
384390 (defun org-publish-remove-all-timestamps ()
838844 latter case, optional argument BACKEND has to be set to the
839845 back-end where the option is defined, e.g.,
840846
841 (org-publish-find-property file :subtitle 'latex)
847 (org-publish-find-property file :subtitle \\='latex)
842848
843849 Return value may be a string or a list, depending on the type of
844850 PROPERTY, i.e. \"behavior\" parameter from `org-export-options-alist'."
11761182 (org-link-search search nil t)
11771183 (error
11781184 (signal 'org-link-broken (cdr err)))))
1179 (and (org-at-heading-p)
1185 (and (derived-mode-p 'org-mode)
1186 (org-at-heading-p)
11801187 (org-string-nw-p (org-entry-get (point) "CUSTOM_ID"))))))))
11811188 ((not org-publish-cache)
11821189 (progn
12881295 (let* ((key (org-publish-timestamp-filename filename pub-dir pub-func))
12891296 (pstamp (org-publish-cache-get key))
12901297 (org-inhibit-startup t)
1291 included-files-ctime)
1298 included-files-mtime)
12921299 (when (equal (file-name-extension filename) "org")
12931300 (let ((case-fold-search t))
12941301 (with-temp-buffer
13091316 (substring m 0 (match-beginning 0))
13101317 m)))))
13111318 (when include-filename
1312 (push (org-publish-cache-ctime-of-src
1319 (push (org-publish-cache-mtime-of-src
13131320 (expand-file-name include-filename (file-name-directory filename)))
1314 included-files-ctime))))))))))
1321 included-files-mtime))))))))))
13151322 (or (null pstamp)
1316 (let ((ctime (org-publish-cache-ctime-of-src filename)))
1317 (or (time-less-p pstamp ctime)
1318 (cl-some (lambda (ct) (time-less-p ctime ct))
1319 included-files-ctime))))))
1323 (let ((mtime (org-publish-cache-mtime-of-src filename)))
1324 (or (time-less-p pstamp mtime)
1325 (cl-some (lambda (ct) (time-less-p mtime ct))
1326 included-files-mtime))))))
13201327
13211328 (defun org-publish-cache-set-file-property
13221329 (filename property value &optional project-name)
13611368 (error "`org-publish-cache-set' called, but no cache present"))
13621369 (puthash key value org-publish-cache))
13631370
1364 (defun org-publish-cache-ctime-of-src (file)
1365 "Get the ctime of FILE as an integer."
1371 (defun org-publish-cache-mtime-of-src (file)
1372 "Get the mtime of FILE as an integer."
13661373 (let ((attr (file-attributes
13671374 (expand-file-name (or (file-symlink-p file) file)
13681375 (file-name-directory file)))))
00 ;;; ox-texinfo.el --- Texinfo Back-End for Org Export Engine -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2012-2021 Free Software Foundation, Inc.
2 ;; Copyright (C) 2012-2023 Free Software Foundation, Inc.
33 ;; Author: Jonathan Leech-Pepin <jonathan.leechpepin at gmail dot com>
4 ;; Maintainer: Nicolas Goaziou <n.goaziou at gmail dot com>
4 ;; Maintainer: Nicolas Goaziou <mail@nicolasgoaziou.fr>
55 ;; Keywords: outlines, hypermedia, calendar, wp
66
77 ;; This file is part of GNU Emacs.
2525
2626 ;;; Code:
2727
28 (require 'org-macs)
29 (org-assert-version)
30
2831 (require 'cl-lib)
2932 (require 'ox)
3033
34 (eval-when-compile (require 'subr-x))
35
3136 (defvar orgtbl-exp-regexp)
32
37 (defvar org-texinfo-supports-math--cache)
3338
3439
3540 ;;; Define Back-End
5459 (italic . org-texinfo-italic)
5560 (item . org-texinfo-item)
5661 (keyword . org-texinfo-keyword)
62 (latex-environment . org-texinfo-latex-environment)
63 (latex-fragment . org-texinfo-latex-fragment)
5764 (line-break . org-texinfo-line-break)
5865 (link . org-texinfo-link)
5966 (node-property . org-texinfo-node-property)
8289 (verse-block . org-texinfo-verse-block))
8390 :filters-alist
8491 '((:filter-headline . org-texinfo--filter-section-blank-lines)
85 (:filter-parse-tree . org-texinfo--normalize-headlines)
92 (:filter-parse-tree . (org-texinfo--normalize-headlines
93 org-texinfo--separate-definitions))
8694 (:filter-section . org-texinfo--filter-section-blank-lines)
8795 (:filter-final-output . org-texinfo--untabify))
8896 :menu-entry
117125 (:texinfo-table-default-markup nil nil org-texinfo-table-default-markup)
118126 (:texinfo-text-markup-alist nil nil org-texinfo-text-markup-alist)
119127 (:texinfo-format-drawer-function nil nil org-texinfo-format-drawer-function)
120 (:texinfo-format-inlinetask-function nil nil org-texinfo-format-inlinetask-function)))
121
128 (:texinfo-format-inlinetask-function nil nil org-texinfo-format-inlinetask-function)
129 (:texinfo-compact-itemx nil "compact-itemx" org-texinfo-compact-itemx)
130 ;; Redefine regular options.
131 (:with-latex nil "tex" org-texinfo-with-latex)))
122132
123133
124134 ;;; User Configurable Variables
353363 :group 'org-export-texinfo
354364 :type 'function)
355365
366 ;;;; LaTeX
367
368 (defcustom org-texinfo-with-latex (and org-export-with-latex 'detect)
369 "When non-nil, the Texinfo exporter attempts to process LaTeX math.
370
371 When set to t, the exporter will process LaTeX environments and
372 fragments as Texinfo \"@displaymath\" and \"@math\" commands
373 respectively. Alternatively, when set to `detect', the exporter
374 does so only if the installed version of Texinfo supports the
375 necessary commands."
376 :group 'org-export-texinfo
377 :package-version '(Org . "9.6")
378 :type '(choice
379 (const :tag "Detect" detect)
380 (const :tag "Yes" t)
381 (const :tag "No" nil)))
382
383 ;;;; Itemx
384
385 (defcustom org-texinfo-compact-itemx nil
386 "Non-nil means certain items in description list become `@itemx'.
387
388 If this is non-nil and an item in a description list has no
389 body but is followed by another item, then the second item is
390 transcoded to `@itemx'. See info node `(org)Plain lists in
391 Texinfo export' for how to enable this for individual lists."
392 :package-version '(Org . "9.6")
393 :group 'org-export-texinfo
394 :type 'boolean
395 :safe t)
396
356397 ;;;; Compilation
357398
358399 (defcustom org-texinfo-info-process '("makeinfo --no-split %f")
405446 (list (cons "file"
406447 (regexp-opt '("eps" "pdf" "png" "jpg" "jpeg" "gif" "svg"))))
407448 "Rules characterizing image files that can be inlined.")
449
450 (defvar org-texinfo--quoted-keys-regexp
451 (regexp-opt '("BS" "TAB" "RET" "ESC" "SPC" "DEL"
452 "LFD" "DELETE" "SHIFT" "Ctrl" "Meta" "Alt"
453 "Cmd" "Super" "UP" "LEFT" "RIGHT" "DOWN")
454 'words)
455 "Regexp matching keys that have to be quoted using @key{KEY}.")
456
457 (defconst org-texinfo--definition-command-alist
458 '(("deffn Command" . "Command")
459 ("defun" . "Function")
460 ("defmac" . "Macro")
461 ("defspec" . "Special Form")
462 ("defvar" . "Variable")
463 ("defopt" . "User Option")
464 (nil . "Key"))
465 "Alist mapping Texinfo definition commands to output in Info files.")
466
467 (defconst org-texinfo--definition-command-regexp
468 (format "\\`%s: \\(.+\\)"
469 (regexp-opt
470 (delq nil (mapcar #'cdr org-texinfo--definition-command-alist))
471 t))
472 "Regexp used to match definition commands in descriptive lists.")
408473
409474
410475 ;;; Internal Functions
568633 (pcase (assoc class (plist-get info :texinfo-classes))
569634 (`(,_ ,_ . ,sections) sections)
570635 (_ (user-error "Unknown Texinfo class: %S" class)))))
636
637 (defun org-texinfo--separate-definitions (tree _backend info)
638 "Split up descriptive lists in TREE that contain Texinfo definition commands.
639 INFO is a plist used as a communication channel.
640 Return new tree."
641 (org-element-map tree 'plain-list
642 (lambda (plain-list)
643 (when (eq (org-element-property :type plain-list) 'descriptive)
644 (let ((contents (org-element-contents plain-list))
645 (items nil))
646 (dolist (item contents)
647 (pcase-let ((`(,cmd . ,args) (org-texinfo--match-definition item)))
648 (cond
649 (cmd
650 (when items
651 (org-texinfo--split-plain-list plain-list (nreverse items))
652 (setq items nil))
653 (org-texinfo--split-definition plain-list item cmd args))
654 (t
655 (when args
656 (org-texinfo--massage-key-item plain-list item args info))
657 (push item items)))))
658 (unless (org-element-contents plain-list)
659 (org-element-extract-element plain-list)))))
660 info)
661 tree)
662
663 (defun org-texinfo--match-definition (item)
664 "Return a cons-cell if ITEM specifies a Texinfo definition command.
665 The car is the command and the cdr is its arguments."
666 (let ((tag (car-safe (org-element-property :tag item))))
667 (and tag
668 (stringp tag)
669 (string-match org-texinfo--definition-command-regexp tag)
670 (pcase-let*
671 ((cmd (car (rassoc (match-string-no-properties 1 tag)
672 org-texinfo--definition-command-alist)))
673 (`(,cmd ,category)
674 (and cmd (save-match-data (split-string cmd " "))))
675 (args (match-string-no-properties 2 tag)))
676 (cons cmd (if category (concat category " " args) args))))))
677
678 (defun org-texinfo--split-definition (plain-list item cmd args)
679 "Insert a definition command before list PLAIN-LIST.
680 Replace list item ITEM with a special-block that inherits the
681 contents of ITEM and whose type and Texinfo attributes are
682 specified by CMD and ARGS."
683 (let ((contents (org-element-contents item)))
684 (org-element-insert-before
685 (apply #'org-element-create 'special-block
686 (list :type cmd
687 :attr_texinfo (list (format ":options %s" args))
688 :post-blank (if contents 1 0))
689 (mapc #'org-element-extract-element contents))
690 plain-list))
691 (org-element-extract-element item))
692
693 (defun org-texinfo--split-plain-list (plain-list items)
694 "Insert a new plain list before the plain list PLAIN-LIST.
695 Remove ITEMS from PLAIN-LIST and use them as the contents of the
696 new plain list."
697 (org-element-insert-before
698 (apply #'org-element-create 'plain-list
699 (list :type 'descriptive
700 :attr_texinfo (org-element-property :attr_texinfo plain-list)
701 :post-blank 1)
702 (mapc #'org-element-extract-element items))
703 plain-list))
704
705 (defun org-texinfo--massage-key-item (plain-list item args info)
706 "In PLAIN-LIST modify ITEM based on ARGS.
707
708 Reformat ITEM's tag property and determine the arguments for the
709 `@findex' and `@kindex' commands for ITEM and store them in ITEM
710 using the `:findex' and `:kindex' properties.
711
712 If PLAIN-LIST is a description list whose `:compact' attribute is
713 non-nil and ITEM has no content but is followed by another item,
714 then store the `@findex' and `@kindex' values in the next item.
715 If the previous item stored its respective values in this item,
716 then move them to the next item.
717
718 INFO is a plist used as a communication channel."
719 (let ((key nil)
720 (cmd nil))
721 (if (string-match (rx (+ " ")
722 "(" (group (+ (not (any "()")))) ")"
723 (* " ")
724 eos)
725 args)
726 (setq key (substring args 0 (match-beginning 0))
727 cmd (match-string 1 args))
728 (setq key args))
729 (org-element-put-property
730 item :tag
731 (cons (org-export-raw-string (org-texinfo-kbd-macro key t))
732 (and cmd `(" (" (code (:value ,cmd :post-blank 0)) ")"))))
733 (let ((findex (org-element-property :findex item))
734 (kindex (org-element-property :kindex item))
735 (next-item (org-export-get-next-element item nil))
736 (mx (string-prefix-p "M-x " key)))
737 (when (and (not cmd) mx)
738 (setq cmd (substring key 4)))
739 (when (and cmd (not (member cmd findex)))
740 (setq findex (nconc findex (list cmd))))
741 (unless mx
742 (setq kindex (nconc kindex (list key))))
743 (cond
744 ((and next-item
745 (or (plist-get info :texinfo-compact-itemx)
746 (org-not-nil
747 (org-export-read-attribute :attr_texinfo plain-list :compact)))
748 (not (org-element-contents item))
749 (eq 1 (org-element-property :post-blank item)))
750 (org-element-put-property next-item :findex findex)
751 (org-element-put-property next-item :kindex kindex)
752 (org-element-put-property item :findex nil)
753 (org-element-put-property item :kindex nil))
754 (t
755 (org-element-set-contents
756 item
757 (nconc (mapcar (lambda (key) `(keyword (:key "KINDEX" :value ,key))) kindex)
758 (mapcar (lambda (cmd) `(keyword (:key "FINDEX" :value ,cmd))) findex)
759 (org-element-contents item))))))))
571760
572761 ;;; Template
573762
9891178 CONTENTS holds the contents of the item. INFO is a plist holding
9901179 contextual information."
9911180 (let* ((tag (org-element-property :tag item))
992 (split (org-string-nw-p
993 (org-export-read-attribute :attr_texinfo
994 (org-element-property :parent item)
995 :sep)))
996 (items (and tag
997 (let ((tag (org-export-data tag info)))
998 (if split
999 (split-string tag (regexp-quote split) t "[ \t\n]+")
1000 (list tag))))))
1001 (format "%s\n%s"
1002 (pcase items
1003 (`nil "@item")
1004 (`(,item) (concat "@item " item))
1005 (`(,item . ,items)
1006 (concat "@item " item "\n"
1007 (mapconcat (lambda (i) (concat "@itemx " i))
1008 items
1009 "\n"))))
1010 (or contents ""))))
1181 (plain-list (org-element-property :parent item))
1182 (compact (and (eq (org-element-property :type plain-list) 'descriptive)
1183 (or (plist-get info :texinfo-compact-itemx)
1184 (org-not-nil (org-export-read-attribute
1185 :attr_texinfo plain-list :compact)))))
1186 (previous-item nil))
1187 (when (and compact
1188 (org-export-get-next-element item info)
1189 (not (org-element-contents item))
1190 (eq 1 (org-element-property :post-blank item)))
1191 (org-element-put-property item :post-blank 0))
1192 (if (and compact
1193 (setq previous-item (org-export-get-previous-element item info))
1194 (not (org-element-contents previous-item))
1195 (eq 0 (org-element-property :post-blank previous-item)))
1196 (format "@itemx%s\n%s"
1197 (if tag (concat " " (org-export-data tag info)) "")
1198 (or contents ""))
1199 (let* ((split (org-string-nw-p (org-export-read-attribute
1200 :attr_texinfo plain-list :sep)))
1201 (items (and tag
1202 (let ((tag (org-export-data tag info)))
1203 (if split
1204 (split-string tag (regexp-quote split)
1205 t "[ \t\n]+")
1206 (list tag))))))
1207 (format "%s\n%s"
1208 (pcase items
1209 (`nil "@item")
1210 (`(,item) (concat "@item " item))
1211 (`(,item . ,items)
1212 (concat "@item " item "\n"
1213 (mapconcat (lambda (i) (concat "@itemx " i))
1214 items
1215 "\n"))))
1216 (or contents ""))))))
10111217
10121218 ;;;; Keyword
10131219
10301236 ((string-match-p "\\<listings\\>" value)
10311237 (concat "@listoffloats "
10321238 (org-export-translate "Listing" :utf-8 info))))))))
1239
1240 ;;;; LaTeX Environment
1241
1242 (defun org-texinfo-latex-environment (environment _contents info)
1243 "Transcode a LaTeX ENVIRONMENT from Org to Texinfo.
1244 CONTENTS is ignored. INFO is a plist holding contextual information."
1245 (let ((with-latex (plist-get info :with-latex)))
1246 (when (or (eq with-latex t)
1247 (and (eq with-latex 'detect)
1248 (org-texinfo-supports-math-p)))
1249 (let ((value (org-element-property :value environment)))
1250 (string-join (list "@displaymath"
1251 (string-trim (org-remove-indentation value))
1252 "@end displaymath")
1253 "\n")))))
1254
1255 ;;;; LaTeX Fragment
1256
1257 (defun org-texinfo-latex-fragment (fragment _contents info)
1258 "Transcode a LaTeX FRAGMENT from Org to Texinfo.
1259 INFO is a plist holding contextual information."
1260 (let ((with-latex (plist-get info :with-latex)))
1261 (when (or (eq with-latex t)
1262 (and (eq with-latex 'detect)
1263 (org-texinfo-supports-math-p)))
1264 (let ((value (org-remove-indentation
1265 (org-element-property :value fragment))))
1266 (cond
1267 ((or (string-match-p "^\\\\\\[" value)
1268 (string-match-p "^\\$\\$" value))
1269 (concat "\n"
1270 "@displaymath"
1271 "\n"
1272 (string-trim (substring value 2 -2))
1273 "\n"
1274 "@end displaymath"
1275 "\n"))
1276 ((string-match-p "^\\$" value)
1277 (concat "@math{"
1278 (string-trim (substring value 1 -1))
1279 "}"))
1280 ((string-match-p "^\\\\(" value)
1281 (concat "@math{"
1282 (string-trim (substring value 2 -2))
1283 "}"))
1284 (t value))))))
10331285
10341286 ;;;; Line Break
10351287
16101862 (format "@display\n%s@end display" contents))
16111863
16121864
1613 ;;; Interactive functions
1865 ;;; Public Functions
1866
1867 (defun org-texinfo-kbd-macro (key &optional noquote)
1868 "Quote KEY using @kbd{...} and if necessary @key{...}.
1869
1870 This is intended to be used as an Org macro like so:
1871
1872 #+macro: kbd (eval (org-texinfo-kbd-macro $1))
1873 Type {{{kbd(C-c SPC)}}}.
1874
1875 Also see info node `(org)Key bindings in Texinfo export'.
1876
1877 If optional NOQOUTE is non-nil, then do not add the quoting
1878 that is necessary when using this in an Org macro."
1879 (format (if noquote "@kbd{%s}" "@@texinfo:@kbd{@@%s@@texinfo:}@@")
1880 (let ((case-fold-search nil))
1881 (replace-regexp-in-string
1882 org-texinfo--quoted-keys-regexp
1883 (if noquote "@key{\\&}" "@@texinfo:@key{@@\\&@@texinfo:}@@")
1884 key t))))
1885
1886 ;;; Interactive Functions
16141887
16151888 ;;;###autoload
16161889 (defun org-texinfo-export-to-texinfo
16911964 parameters overriding Org default settings, but still inferior to
16921965 file-local settings.
16931966
1694 When optional argument PUB-DIR is set, use it as the publishing
1695 directory.
1696
16971967 Return INFO file's name."
16981968 (interactive)
16991969 (let ((outfile (org-export-output-file-name ".texi" subtreep))
17462016 (message "Process completed.")
17472017 output))
17482018
2019 (defun org-texinfo-supports-math-p ()
2020 "Return t if the installed version of Texinfo supports \"@math\".
2021
2022 Once computed, the results remain cached."
2023 (unless (boundp 'org-texinfo-supports-math--cache)
2024 (setq org-texinfo-supports-math--cache
2025 (let ((math-example "1 + 1 = 2"))
2026 (let* ((input-file (make-temp-file "test" nil ".info"))
2027 (input-content (string-join
2028 (list (format "@setfilename %s" input-file)
2029 "@node Top"
2030 "@displaymath"
2031 math-example
2032 "@end displaymath")
2033 "\n")))
2034 (with-temp-file input-file
2035 (insert input-content))
2036 (when-let* ((output-file
2037 ;; If compilation fails, consider math to
2038 ;; be not supported.
2039 (ignore-errors (org-texinfo-compile input-file)))
2040 (output-content (with-temp-buffer
2041 (insert-file-contents output-file)
2042 (buffer-string))))
2043 (let ((result (string-match-p (regexp-quote math-example)
2044 output-content)))
2045 (delete-file input-file)
2046 (delete-file output-file)
2047 (if result t nil)))))))
2048 org-texinfo-supports-math--cache)
17492049
17502050 (provide 'ox-texinfo)
17512051
00 ;;; ox.el --- Export Framework for Org Mode -*- lexical-binding: t; -*-
11
2 ;; Copyright (C) 2012-2021 Free Software Foundation, Inc.
3
4 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
5 ;; Maintainer: Nicolas Goaziou <n.goaziou at gmail dot com>
2 ;; Copyright (C) 2012-2023 Free Software Foundation, Inc.
3
4 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
5 ;; Maintainer: Nicolas Goaziou <mail@nicolasgoaziou.fr>
66 ;; Keywords: outlines, hypermedia, calendar, wp
77
88 ;; This file is part of GNU Emacs.
7171
7272 ;;; Code:
7373
74 (require 'org-macs)
75 (org-assert-version)
76
7477 (require 'cl-lib)
7578 (require 'ob-exp)
7679 (require 'oc)
77 (require 'oc-basic) ;default value for `org-cite-export-processors'
7880 (require 'ol)
7981 (require 'org-element)
8082 (require 'org-macro)
8688 (declare-function org-publish-all "ox-publish" (&optional force async))
8789 (declare-function org-publish-current-file "ox-publish" (&optional force async))
8890 (declare-function org-publish-current-project "ox-publish" (&optional force async))
91 (declare-function org-at-heading-p "org" (&optional _))
92 (declare-function org-back-to-heading "org" (&optional invisible-ok))
93 (declare-function org-next-visible-heading "org" (arg))
8994
9095 (defvar org-publish-project-alist)
9196 (defvar org-table-number-fraction)
258263 rules.")
259264
260265 (defconst org-export-ignored-local-variables
261 '(org-font-lock-keywords
262 org-element--cache org-element--cache-objects org-element--cache-sync-keys
263 org-element--cache-sync-requests org-element--cache-sync-timer)
266 '( org-font-lock-keywords org-element--cache-change-tic
267 org-element--cache-change-tic org-element--cache-size
268 org-element--headline-cache-size
269 org-element--cache-sync-keys-value
270 org-element--cache-change-warning org-element--headline-cache
271 org-element--cache org-element--cache-sync-keys
272 org-element--cache-sync-requests org-element--cache-sync-timer)
264273 "List of variables not copied through upon buffer duplication.
265274 Export process takes place on a copy of the original buffer.
266275 When this copy is created, all Org related local variables not in
631640 (defcustom org-export-with-smart-quotes nil
632641 "Non-nil means activate smart quotes during export.
633642 This option can also be set with the OPTIONS keyword,
634 e.g., \"':t\".
643 e.g., \"\\=':t\".
635644
636645 When setting this to non-nil, you need to take care of
637646 using the correct Babel package when exporting to LaTeX.
867876
868877 This variable allows providing shortcuts for export snippets.
869878
870 For example, with a value of \\='((\"h\" . \"html\")), the
871 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
879 For example, with:
880
881 (setq org-export-snippet-translation-alist
882 \\='((\"h\" . \"html\")))
883
884 the HTML back-end will recognize the contents of \"@@h:<b>@@\" as
872885 HTML code while every other back-end will ignore it."
873886 :group 'org-export-general
874887 :version "24.4"
11771190 Menu entry for the export dispatcher. It should be a list
11781191 like:
11791192
1180 \\='(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
1193 (KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
11811194
11821195 where :
11831196
12011214 If it is an alist, associations should follow the
12021215 pattern:
12031216
1204 \\='(KEY DESCRIPTION ACTION)
1217 (KEY DESCRIPTION ACTION)
12051218
12061219 where KEY, DESCRIPTION and ACTION are described above.
12071220
12081221 Valid values include:
12091222
1210 \\='(?m \"My Special Back-end\" my-special-export-function)
1223 (?m \"My Special Back-end\" my-special-export-function)
12111224
12121225 or
12131226
1214 \\='(?l \"Export to LaTeX\"
1227 (?l \"Export to LaTeX\"
12151228 ((?p \"As PDF file\" org-latex-export-to-pdf)
12161229 (?o \"As PDF file and open\"
12171230 (lambda (a s v b)
12221235 or the following, which will be added to the previous
12231236 sub-menu,
12241237
1225 \\='(?l 1
1238 (?l 1
12261239 ((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
12271240 (?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
12281241
13901403 e.g., `org-export-create-backend'. It specifies which back-end
13911404 specific items to read, if any."
13921405 (let ((line
1393 (let ((s 0) alist)
1394 (while (string-match "\\(.+?\\):\\((.*?)\\|\\S-+\\)?[ \t]*" options s)
1395 (setq s (match-end 0))
1396 (let ((value (match-string 2 options)))
1397 (when value
1398 (push (cons (match-string 1 options)
1399 (read value))
1400 alist))))
1406 (let (alist)
1407 (with-temp-buffer
1408 (insert options)
1409 (goto-char (point-min))
1410 (while (re-search-forward "\\s-*\\(.+?\\):" nil t)
1411 (when (looking-at-p "\\S-")
1412 (push (cons (match-string 1)
1413 (read (current-buffer))) ; moves point
1414 alist))))
14011415 alist))
14021416 ;; Priority is given to back-end specific options.
14031417 (all (append (org-export-get-all-options backend)
14201434 ;; property is the keyword with "EXPORT_" appended to it.
14211435 (org-with-wide-buffer
14221436 ;; Make sure point is at a heading.
1423 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1437 (org-back-to-heading t)
14241438 (let ((plist
14251439 ;; EXPORT_OPTIONS are parsed in a non-standard way. Take
14261440 ;; care of them right from the start.
19071921 (org-element-property :archivedp data)))
19081922 (let ((transcoder (org-export-transcoder data info)))
19091923 (or (and (functionp transcoder)
1910 (broken-link-handler
1911 (funcall transcoder data nil info)))
1924 (if (eq type 'link)
1925 (broken-link-handler
1926 (funcall transcoder data nil info))
1927 (funcall transcoder data nil info)))
19121928 ;; Export snippets never return a nil value so
19131929 ;; that white spaces following them are never
19141930 ;; ignored.
20742090
20752091 ;;;; Hooks
20762092
2077 (defvar org-export-before-processing-hook nil
2078 "Hook run at the beginning of the export process.
2093 (defvar org-export-before-processing-functions nil
2094 "Abnormal hook run at the beginning of the export process.
20792095
20802096 This is run before include keywords and macros are expanded and
20812097 Babel code blocks executed, on a copy of the original buffer
20852101 Every function in this hook will be called with one argument: the
20862102 back-end currently used, as a symbol.")
20872103
2088 (defvar org-export-before-parsing-hook nil
2089 "Hook run before parsing an export buffer.
2104 (defvar org-export-before-parsing-functions nil
2105 "Abnormal hook run before parsing an export buffer.
20902106
20912107 This is run after include keywords and macros have been expanded
20922108 and Babel code blocks executed, on a copy of the original buffer
25282544 ;; a default template (or a back-end specific template) at point or in
25292545 ;; current subtree.
25302546
2531 (defun org-export-copy-buffer ()
2547 (cl-defun org-export-copy-buffer (&key to-buffer drop-visibility
2548 drop-narrowing drop-contents
2549 drop-locals)
25322550 "Return a copy of the current buffer.
25332551 The copy preserves Org buffer-local variables, visibility and
2534 narrowing."
2535 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2536 (new-buf (generate-new-buffer (buffer-name))))
2552 narrowing.
2553
2554 IMPORTANT: The buffer copy may also have `buffer-file-name' copied.
2555 To prevent Emacs overwriting the original buffer file,
2556 `write-contents-functions' is set to (always). Do not alter this
2557 variable and do not do anything that might alter it (like calling a
2558 major mode) to prevent data corruption. Also, do note that Emacs may
2559 jump into the created buffer if the original file buffer is closed and
2560 then re-opened. Making edits in the buffer copy may also trigger
2561 Emacs save dialog. Prefer using `org-export-with-buffer-copy' macro
2562 when possible.
2563
2564 When optional key `:to-buffer' is non-nil, copy into BUFFER.
2565
2566 Optional keys `:drop-visibility', `:drop-narrowing', `:drop-contents',
2567 and `:drop-locals' are passed to `org-export--generate-copy-script'."
2568 (let ((copy-buffer-fun (org-export--generate-copy-script
2569 (current-buffer)
2570 :copy-unreadable 'do-not-check
2571 :drop-visibility drop-visibility
2572 :drop-narrowing drop-narrowing
2573 :drop-contents drop-contents
2574 :drop-locals drop-locals))
2575 (new-buf (or to-buffer (generate-new-buffer (buffer-name)))))
25372576 (with-current-buffer new-buf
25382577 (funcall copy-buffer-fun)
25392578 (set-buffer-modified-p nil))
25402579 new-buf))
25412580
2542 (defmacro org-export-with-buffer-copy (&rest body)
2581 (cl-defmacro org-export-with-buffer-copy ( &rest body
2582 &key to-buffer drop-visibility
2583 drop-narrowing drop-contents
2584 drop-locals
2585 &allow-other-keys)
25432586 "Apply BODY in a copy of the current buffer.
25442587 The copy preserves local variables, visibility and contents of
25452588 the original buffer. Point is at the beginning of the buffer
2546 when BODY is applied."
2589 when BODY is applied.
2590
2591 Optional keys can modify what is being copied and the generated buffer
2592 copy. `:to-buffer', `:drop-visibility', `:drop-narrowing',
2593 `:drop-contents', and `:drop-locals' are passed as arguments to
2594 `org-export-copy-buffer'."
25472595 (declare (debug t))
25482596 (org-with-gensyms (buf-copy)
2549 `(let ((,buf-copy (org-export-copy-buffer)))
2597 `(let ((,buf-copy (org-export-copy-buffer
2598 :to-buffer ,to-buffer
2599 :drop-visibility ,drop-visibility
2600 :drop-narrowing ,drop-narrowing
2601 :drop-contents ,drop-contents
2602 :drop-locals ,drop-locals)))
25502603 (unwind-protect
25512604 (with-current-buffer ,buf-copy
25522605 (goto-char (point-min))
2553 (progn ,@body))
2606 (prog1
2607 (progn ,@body)
2608 ;; `org-export-copy-buffer' carried the value of
2609 ;; `buffer-file-name' from the original buffer. When not
2610 ;; killed, the new buffer copy may become a target of
2611 ;; `find-file'. Prevent this.
2612 (setq buffer-file-name nil)))
25542613 (and (buffer-live-p ,buf-copy)
25552614 ;; Kill copy without confirmation.
25562615 (progn (with-current-buffer ,buf-copy
25572616 (restore-buffer-modified-p nil))
2558 (kill-buffer ,buf-copy)))))))
2559
2560 (defun org-export--generate-copy-script (buffer)
2617 (unless ,to-buffer
2618 (kill-buffer ,buf-copy))))))))
2619
2620 (cl-defun org-export--generate-copy-script (buffer
2621 &key
2622 copy-unreadable
2623 drop-visibility
2624 drop-narrowing
2625 drop-contents
2626 drop-locals)
25612627 "Generate a function duplicating BUFFER.
25622628
25632629 The copy will preserve local variables, visibility, contents and
25642630 narrowing of the original buffer. If a region was active in
25652631 BUFFER, contents will be narrowed to that region instead.
25662632
2633 When optional key `:copy-unreadable' is non-nil, do not ensure that all
2634 the copied local variables will be readable in another Emacs session.
2635
2636 When optional keys `:drop-visibility', `:drop-narrowing',
2637 `:drop-contents', or `:drop-locals' are non-nil, do not preserve
2638 visibility, narrowing, contents, or local variables correspondingly.
2639
25672640 The resulting function can be evaluated at a later time, from
25682641 another buffer, effectively cloning the original buffer there.
25692642
25702643 The function assumes BUFFER's major mode is `org-mode'."
25712644 (with-current-buffer buffer
2572 (let ((str (org-with-wide-buffer (buffer-string)))
2645 (let ((str (unless drop-contents (org-with-wide-buffer (buffer-string))))
25732646 (narrowing
2574 (if (org-region-active-p)
2575 (list (region-beginning) (region-end))
2576 (list (point-min) (point-max))))
2647 (unless drop-narrowing
2648 (if (org-region-active-p)
2649 (list (region-beginning) (region-end))
2650 (list (point-min) (point-max)))))
25772651 (pos (point))
25782652 (varvals
2579 (let ((bound-variables (org-export--list-bound-variables))
2580 (varvals nil))
2581 (dolist (entry (buffer-local-variables (buffer-base-buffer)))
2582 (when (consp entry)
2583 (let ((var (car entry))
2584 (val (cdr entry)))
2585 (and (not (memq var org-export-ignored-local-variables))
2586 (or (memq var
2587 '(default-directory
2588 buffer-file-name
2589 buffer-file-coding-system))
2590 (assq var bound-variables)
2591 (string-match "^\\(org-\\|orgtbl-\\)"
2592 (symbol-name var)))
2593 ;; Skip unreadable values, as they cannot be
2594 ;; sent to external process.
2595 (or (not val) (ignore-errors (read (format "%S" val))))
2596 (push (cons var val) varvals)))))
2597 varvals))
2653 (unless drop-locals
2654 (let ((bound-variables (org-export--list-bound-variables))
2655 (varvals nil))
2656 (dolist (entry (buffer-local-variables (buffer-base-buffer)))
2657 (when (consp entry)
2658 (let ((var (car entry))
2659 (val (cdr entry)))
2660 (and (not (memq var org-export-ignored-local-variables))
2661 (or (memq var
2662 '(default-directory
2663 ;; Required to convert file
2664 ;; links in the #+INCLUDEd
2665 ;; files. See
2666 ;; `org-export--prepare-file-contents'.
2667 buffer-file-name
2668 buffer-file-coding-system
2669 ;; Needed to preserve folding state
2670 char-property-alias-alist))
2671 (assq var bound-variables)
2672 (string-match "^\\(org-\\|orgtbl-\\)"
2673 (symbol-name var)))
2674 ;; Skip unreadable values, as they cannot be
2675 ;; sent to external process.
2676 (or copy-unreadable (not val)
2677 (ignore-errors (read (format "%S" val))))
2678 (push (cons var val) varvals)))))
2679 varvals)))
25982680 (ols
2599 (let (ov-set)
2600 (dolist (ov (overlays-in (point-min) (point-max)))
2601 (let ((invis-prop (overlay-get ov 'invisible)))
2602 (when invis-prop
2603 (push (list (overlay-start ov) (overlay-end ov)
2604 invis-prop)
2605 ov-set))))
2606 ov-set)))
2681 (unless drop-visibility
2682 (let (ov-set)
2683 (dolist (ov (overlays-in (point-min) (point-max)))
2684 (let ((invis-prop (overlay-get ov 'invisible)))
2685 (when invis-prop
2686 (push (list (overlay-start ov) (overlay-end ov)
2687 invis-prop)
2688 ov-set))))
2689 ov-set))))
26072690 (lambda ()
26082691 (let ((inhibit-modification-hooks t))
2609 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2610 ;; already in BUFFER.
2611 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2692 ;; Set major mode. Ignore `org-mode-hook' and other hooks as
2693 ;; they have been run already in BUFFER.
2694 (unless (eq major-mode 'org-mode)
2695 (delay-mode-hooks
2696 (let ((org-inhibit-startup t)) (org-mode))))
26122697 ;; Copy specific buffer local variables and variables set
26132698 ;; through BIND keywords.
26142699 (pcase-dolist (`(,var . ,val) varvals)
26152700 (set (make-local-variable var) val))
2616 ;; Whole buffer contents.
2617 (insert str)
2701 ;; Whole buffer contents when requested.
2702 (when str (erase-buffer) (insert str))
2703 ;; Make org-element-cache not complain about changed buffer
2704 ;; state.
2705 (org-element-cache-reset nil 'no-persistence)
26182706 ;; Narrowing.
2619 (apply #'narrow-to-region narrowing)
2707 (when narrowing
2708 (apply #'narrow-to-region narrowing))
26202709 ;; Current position of point.
26212710 (goto-char pos)
26222711 ;; Overlays with invisible property.
26232712 (pcase-dolist (`(,start ,end ,invis) ols)
2624 (overlay-put (make-overlay start end) 'invisible invis)))))))
2713 (overlay-put (make-overlay start end) 'invisible invis))
2714 ;; Never write the buffer copy to disk, despite
2715 ;; `buffer-file-name' not being nil.
2716 (setq write-contents-functions (list (lambda (&rest _) t))))))))
26252717
26262718 (defun org-export--delete-comment-trees ()
26272719 "Delete commented trees and commented inlinetasks in the buffer.
29313023 Return code as a string."
29323024 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
29333025 (org-export-barf-if-invalid-backend backend)
2934 (save-excursion
2935 (save-restriction
2936 ;; Narrow buffer to an appropriate region or subtree for
2937 ;; parsing. If parsing subtree, be sure to remove main
2938 ;; headline, planning data and property drawer.
2939 (cond ((org-region-active-p)
2940 (narrow-to-region (region-beginning) (region-end)))
2941 (subtreep
2942 (org-narrow-to-subtree)
2943 (goto-char (point-min))
2944 (org-end-of-meta-data)
2945 (narrow-to-region (point) (point-max))))
2946 ;; Initialize communication channel with original buffer
2947 ;; attributes, unavailable in its copy.
2948 (let* ((org-export-current-backend (org-export-backend-name backend))
2949 (info (org-combine-plists
2950 (org-export--get-export-attributes
2951 backend subtreep visible-only body-only)
2952 (org-export--get-buffer-attributes)))
2953 (parsed-keywords
2954 (delq nil
2955 (mapcar (lambda (o) (and (eq (nth 4 o) 'parse) (nth 1 o)))
2956 (append (org-export-get-all-options backend)
2957 org-export-options-alist))))
2958 tree)
2959 ;; Update communication channel and get parse tree. Buffer
2960 ;; isn't parsed directly. Instead, all buffer modifications
2961 ;; and consequent parsing are undertaken in a temporary copy.
2962 (org-export-with-buffer-copy
2963 ;; Run first hook with current back-end's name as argument.
2964 (run-hook-with-args 'org-export-before-processing-hook
2965 (org-export-backend-name backend))
2966 (org-export-expand-include-keyword)
2967 (org-export--delete-comment-trees)
2968 (org-macro-initialize-templates org-export-global-macros)
2969 (org-macro-replace-all org-macro-templates parsed-keywords)
2970 ;; Refresh buffer properties and radio targets after previous
2971 ;; potentially invasive changes.
2972 (org-set-regexps-and-options)
2973 (org-update-radio-target-regexp)
2974 ;; Possibly execute Babel code. Re-run a macro expansion
2975 ;; specifically for {{{results}}} since inline source blocks
2976 ;; may have generated some more. Refresh buffer properties
2977 ;; and radio targets another time.
2978 (when org-export-use-babel
2979 (org-babel-exp-process-buffer)
2980 (org-macro-replace-all '(("results" . "$1")) parsed-keywords)
3026 (org-fold-core-ignore-modifications
3027 (save-excursion
3028 (save-restriction
3029 ;; Narrow buffer to an appropriate region or subtree for
3030 ;; parsing. If parsing subtree, be sure to remove main
3031 ;; headline, planning data and property drawer.
3032 (cond ((org-region-active-p)
3033 (narrow-to-region (region-beginning) (region-end)))
3034 (subtreep
3035 (org-narrow-to-subtree)
3036 (goto-char (point-min))
3037 (org-end-of-meta-data)
3038 ;; Make the region include top heading in the subtree.
3039 ;; This way, we will be able to retrieve its export
3040 ;; options when calling
3041 ;; `org-export--get-subtree-options'.
3042 (when (bolp) (backward-char))
3043 (narrow-to-region (point) (point-max))))
3044 ;; Initialize communication channel with original buffer
3045 ;; attributes, unavailable in its copy.
3046 (let* ((org-export-current-backend (org-export-backend-name backend))
3047 (info (org-combine-plists
3048 (org-export--get-export-attributes
3049 backend subtreep visible-only body-only)
3050 (org-export--get-buffer-attributes)))
3051 (parsed-keywords
3052 (delq nil
3053 (mapcar (lambda (o) (and (eq (nth 4 o) 'parse) (nth 1 o)))
3054 (append (org-export-get-all-options backend)
3055 org-export-options-alist))))
3056 tree modified-tick)
3057 ;; Update communication channel and get parse tree. Buffer
3058 ;; isn't parsed directly. Instead, all buffer modifications
3059 ;; and consequent parsing are undertaken in a temporary copy.
3060 (org-export-with-buffer-copy
3061 (font-lock-mode -1)
3062 ;; Run first hook with current back-end's name as argument.
3063 (run-hook-with-args 'org-export-before-processing-hook
3064 (org-export-backend-name backend))
3065 (org-export-expand-include-keyword)
3066 (org-export--delete-comment-trees)
3067 (org-macro-initialize-templates org-export-global-macros)
3068 (org-macro-replace-all org-macro-templates parsed-keywords)
3069 ;; Refresh buffer properties and radio targets after previous
3070 ;; potentially invasive changes.
29813071 (org-set-regexps-and-options)
2982 (org-update-radio-target-regexp))
2983 ;; Run last hook with current back-end's name as argument.
2984 ;; Update buffer properties and radio targets one last time
2985 ;; before parsing.
2986 (goto-char (point-min))
2987 (save-excursion
2988 (run-hook-with-args 'org-export-before-parsing-hook
2989 (org-export-backend-name backend)))
2990 (org-set-regexps-and-options)
2991 (org-update-radio-target-regexp)
2992 ;; Update communication channel with environment.
2993 (setq info
2994 (org-combine-plists
2995 info (org-export-get-environment backend subtreep ext-plist)))
2996 ;; Pre-process citations environment, i.e. install
2997 ;; bibliography list, and citation processor in INFO.
2998 (org-cite-store-bibliography info)
2999 (org-cite-store-export-processor info)
3000 ;; De-activate uninterpreted data from parsed keywords.
3001 (dolist (entry (append (org-export-get-all-options backend)
3002 org-export-options-alist))
3003 (pcase entry
3004 (`(,p ,_ ,_ ,_ parse)
3005 (let ((value (plist-get info p)))
3006 (plist-put info
3007 p
3008 (org-export--remove-uninterpreted-data value info))))
3009 (_ nil)))
3010 ;; Install user's and developer's filters.
3011 (setq info (org-export-install-filters info))
3012 ;; Call options filters and update export options. We do not
3013 ;; use `org-export-filter-apply-functions' here since the
3014 ;; arity of such filters is different.
3015 (let ((backend-name (org-export-backend-name backend)))
3016 (dolist (filter (plist-get info :filter-options))
3017 (let ((result (funcall filter info backend-name)))
3018 (when result (setq info result)))))
3019 ;; Parse buffer.
3020 (setq tree (org-element-parse-buffer nil visible-only))
3021 ;; Prune tree from non-exported elements and transform
3022 ;; uninterpreted elements or objects in both parse tree and
3023 ;; communication channel.
3024 (org-export--prune-tree tree info)
3025 (org-export--remove-uninterpreted-data tree info)
3026 ;; Call parse tree filters.
3027 (setq tree
3028 (org-export-filter-apply-functions
3029 (plist-get info :filter-parse-tree) tree info))
3030 ;; Now tree is complete, compute its properties and add them
3031 ;; to communication channel.
3032 (setq info (org-export--collect-tree-properties tree info))
3033 ;; Process citations and bibliography. Replace each citation
3034 ;; and "print_bibliography" keyword in the parse tree with
3035 ;; the output of the selected citation export processor.
3036 (org-cite-process-citations info)
3037 (org-cite-process-bibliography info)
3038 ;; Eventually transcode TREE. Wrap the resulting string into
3039 ;; a template.
3040 (let* ((body (org-element-normalize-string
3041 (or (org-export-data tree info) "")))
3042 (inner-template (cdr (assq 'inner-template
3043 (plist-get info :translate-alist))))
3044 (full-body (org-export-filter-apply-functions
3045 (plist-get info :filter-body)
3046 (if (not (functionp inner-template)) body
3047 (funcall inner-template body info))
3048 info))
3049 (template (cdr (assq 'template
3050 (plist-get info :translate-alist))))
3051 (output
3052 (if (or (not (functionp template)) body-only) full-body
3053 (funcall template full-body info))))
3054 ;; Call citation export finalizer.
3055 (setq output (org-cite-finalize-export output info))
3056 ;; Remove all text properties since they cannot be
3057 ;; retrieved from an external process. Finally call
3058 ;; final-output filter and return result.
3059 (org-no-properties
3060 (org-export-filter-apply-functions
3061 (plist-get info :filter-final-output)
3062 output info))))))))
3072 (org-update-radio-target-regexp)
3073 (setq modified-tick (buffer-chars-modified-tick))
3074 ;; Possibly execute Babel code. Re-run a macro expansion
3075 ;; specifically for {{{results}}} since inline source blocks
3076 ;; may have generated some more. Refresh buffer properties
3077 ;; and radio targets another time.
3078 (when org-export-use-babel
3079 (org-babel-exp-process-buffer)
3080 (org-macro-replace-all '(("results" . "$1")) parsed-keywords)
3081 (unless (eq modified-tick (buffer-chars-modified-tick))
3082 (org-set-regexps-and-options)
3083 (org-update-radio-target-regexp))
3084 (setq modified-tick (buffer-chars-modified-tick)))
3085 ;; Run last hook with current back-end's name as argument.
3086 ;; Update buffer properties and radio targets one last time
3087 ;; before parsing.
3088 (goto-char (point-min))
3089 (save-excursion
3090 (run-hook-with-args 'org-export-before-parsing-hook
3091 (org-export-backend-name backend)))
3092 (unless (eq modified-tick (buffer-chars-modified-tick))
3093 (org-set-regexps-and-options)
3094 (org-update-radio-target-regexp))
3095 (setq modified-tick (buffer-chars-modified-tick))
3096 ;; Update communication channel with environment.
3097 (setq info
3098 (org-combine-plists
3099 info (org-export-get-environment backend subtreep ext-plist)))
3100 ;; Pre-process citations environment, i.e. install
3101 ;; bibliography list, and citation processor in INFO.
3102 (org-cite-store-bibliography info)
3103 (org-cite-store-export-processor info)
3104 ;; De-activate uninterpreted data from parsed keywords.
3105 (dolist (entry (append (org-export-get-all-options backend)
3106 org-export-options-alist))
3107 (pcase entry
3108 (`(,p ,_ ,_ ,_ parse)
3109 (let ((value (plist-get info p)))
3110 (plist-put info
3111 p
3112 (org-export--remove-uninterpreted-data value info))))
3113 (_ nil)))
3114 ;; Install user's and developer's filters.
3115 (setq info (org-export-install-filters info))
3116 ;; Call options filters and update export options. We do not
3117 ;; use `org-export-filter-apply-functions' here since the
3118 ;; arity of such filters is different.
3119 (let ((backend-name (org-export-backend-name backend)))
3120 (dolist (filter (plist-get info :filter-options))
3121 (let ((result (funcall filter info backend-name)))
3122 (when result (setq info result)))))
3123 ;; Parse buffer.
3124 (setq tree (org-element-parse-buffer nil visible-only))
3125 ;; Prune tree from non-exported elements and transform
3126 ;; uninterpreted elements or objects in both parse tree and
3127 ;; communication channel.
3128 (org-export--prune-tree tree info)
3129 (org-export--remove-uninterpreted-data tree info)
3130 ;; Call parse tree filters.
3131 (setq tree
3132 (org-export-filter-apply-functions
3133 (plist-get info :filter-parse-tree) tree info))
3134 ;; Now tree is complete, compute its properties and add them
3135 ;; to communication channel.
3136 (setq info (org-export--collect-tree-properties tree info))
3137 ;; Process citations and bibliography. Replace each citation
3138 ;; and "print_bibliography" keyword in the parse tree with
3139 ;; the output of the selected citation export processor.
3140 (org-cite-process-citations info)
3141 (org-cite-process-bibliography info)
3142 ;; Eventually transcode TREE. Wrap the resulting string into
3143 ;; a template.
3144 (let* ((body (org-element-normalize-string
3145 (or (org-export-data tree info) "")))
3146 (inner-template (cdr (assq 'inner-template
3147 (plist-get info :translate-alist))))
3148 (full-body (org-export-filter-apply-functions
3149 (plist-get info :filter-body)
3150 (if (not (functionp inner-template)) body
3151 (funcall inner-template body info))
3152 info))
3153 (template (cdr (assq 'template
3154 (plist-get info :translate-alist))))
3155 (output
3156 (if (or (not (functionp template)) body-only) full-body
3157 (funcall template full-body info))))
3158 ;; Call citation export finalizer.
3159 (setq output (org-cite-finalize-export output info))
3160 ;; Remove all text properties since they cannot be
3161 ;; retrieved from an external process. Finally call
3162 ;; final-output filter and return result.
3163 (org-no-properties
3164 (org-export-filter-apply-functions
3165 (plist-get info :filter-final-output)
3166 output info)))))))))
30633167
30643168 ;;;###autoload
30653169 (defun org-export-string-as (string backend &optional body-only ext-plist)
32103314 (beginning-of-line)
32113315 ;; Extract arguments from keyword's value.
32123316 (let* ((value (org-element-property :value element))
3213 (ind (current-indentation))
3317 (ind (org-current-text-indentation))
32143318 location
32153319 (coding-system-for-read
32163320 (or (and (string-match ":coding +\\(\\S-+\\)>" value)
32223326 value)
32233327 (prog1
32243328 (save-match-data
3225 (let ((matched (match-string 1 value)))
3329 (let ((matched (match-string 1 value))
3330 stripped)
32263331 (when (string-match "\\(::\\(.*?\\)\\)\"?\\'"
32273332 matched)
32283333 (setq location (match-string 2 matched))
32293334 (setq matched
32303335 (replace-match "" nil nil matched 1)))
3231 (expand-file-name (org-strip-quotes matched)
3232 dir)))
3233 (setq value (replace-match "" nil nil value)))))
3336 (setq stripped (org-strip-quotes matched))
3337 (if (org-url-p stripped)
3338 stripped
3339 (expand-file-name stripped dir))))
3340 (setq value (replace-match "" nil nil value)))))
32343341 (only-contents
32353342 (and (string-match ":only-contents *\\([^: \r\t\n]\\S-*\\)?"
32363343 value)
32663373 (delete-region (point) (line-beginning-position 2))
32673374 (cond
32683375 ((not file) nil)
3269 ((not (file-readable-p file))
3376 ((and (not (org-url-p file)) (not (file-readable-p file)))
32703377 (error "Cannot include file %s" file))
32713378 ;; Check if files has already been parsed. Look after
32723379 ;; inclusion lines too, as different parts of the same
33123419 includer-file)))
33133420 (org-export-expand-include-keyword
33143421 (cons (list file lines) included)
3315 (file-name-directory file)
3316 footnotes)
3422 (unless (org-url-p file)
3423 (file-name-directory file))
3424 footnotes)
33173425 (buffer-string)))))
33183426 ;; Expand footnotes after all files have been
33193427 ;; included. Footnotes are stored at end of buffer.
33363444 Return a string of lines to be included in the format expected by
33373445 `org-export--prepare-file-contents'."
33383446 (with-temp-buffer
3339 (insert-file-contents file)
3447 (insert (org-file-contents file))
33403448 (unless (eq major-mode 'org-mode)
33413449 (let ((org-inhibit-startup t)) (org-mode)))
33423450 (condition-case err
34413549 Optional argument INCLUDER is the file name where the inclusion
34423550 is to happen."
34433551 (with-temp-buffer
3444 (insert-file-contents file)
3552 (insert (org-file-contents file))
34453553 (when lines
34463554 (let* ((lines (split-string lines "-"))
34473555 (lbeg (string-to-number (car lines)))
37473855 (if (not label) (org-element-contents footnote-reference)
37483856 (let ((cache (or (plist-get info :footnote-definition-cache)
37493857 (let ((hash (make-hash-table :test #'equal)))
3858 ;; Cache all the footnotes in document for
3859 ;; later search.
3860 (org-element-map (plist-get info :parse-tree)
3861 '(footnote-definition footnote-reference)
3862 (lambda (f)
3863 ;; Skip any standard footnote reference
3864 ;; since those cannot contain a
3865 ;; definition.
3866 (unless (eq (org-element-property :type f) 'standard)
3867 (puthash
3868 (cons :element (org-element-property :label f))
3869 f
3870 hash)))
3871 info)
37503872 (plist-put info :footnote-definition-cache hash)
37513873 hash))))
37523874 (or
37533875 (gethash label cache)
37543876 (puthash label
3755 (org-element-map (plist-get info :parse-tree)
3756 '(footnote-definition footnote-reference)
3757 (lambda (f)
3758 (cond
3759 ;; Skip any footnote with a different label.
3760 ;; Also skip any standard footnote reference
3761 ;; with the same label since those cannot
3762 ;; contain a definition.
3763 ((not (equal (org-element-property :label f) label)) nil)
3764 ((eq (org-element-property :type f) 'standard) nil)
3765 ((org-element-contents f))
3766 ;; Even if the contents are empty, we can not
3767 ;; return nil since that would eventually raise
3768 ;; the error. Instead, return the equivalent
3769 ;; empty string.
3770 (t "")))
3771 info t)
3877 (let ((hashed (gethash (cons :element label) cache)))
3878 (when hashed
3879 (or (org-element-contents hashed)
3880 ;; Even if the contents are empty, we can not
3881 ;; return nil since that would eventually raise
3882 ;; the error. Instead, return the equivalent
3883 ;; empty string.
3884 "")))
37723885 cache)
37733886 (error "Definition not found for footnote %s" label))))))
37743887
40884201 ((and fmt
40894202 (not (cdr date))
40904203 (eq (org-element-type (car date)) 'timestamp))
4091 (org-timestamp-format (car date) fmt))
4204 (org-format-timestamp (car date) fmt))
40924205 (t date))))
40934206
40944207
41254238 ;; `org-export-data' for further processing, depending on
41264239 ;; `org-export-with-broken-links' value.
41274240
4128 (org-define-error 'org-link-broken "Unable to resolve link; aborting")
4241 (define-error 'org-link-broken "Unable to resolve link; aborting")
41294242
41304243 (defun org-export-custom-protocol-maybe (link desc backend &optional info)
41314244 "Try exporting LINK object with a dedicated function.
42734386 - target's or radio-target's name as a list of strings if
42744387 TYPE is `target'.
42754388
4276 - NAME affiliated keyword if TYPE is `other'.
4389 - NAME or RESULTS affiliated keyword if TYPE is `other'.
42774390
42784391 A search cell is the internal representation of a fuzzy link. It
42794392 ignores white spaces and statistics cookies, if applicable."
42914404 (and custom-id (cons 'custom-id custom-id)))))))
42924405 (`target
42934406 (list (cons 'target (split-string (org-element-property :value datum)))))
4294 ((and (let name (org-element-property :name datum))
4407 ((and (let name (or (org-element-property :name datum)
4408 (car (org-element-property :results datum))))
42954409 (guard name))
42964410 (list (cons 'other (split-string name))))
42974411 (_ nil)))
43234437
43244438 - If LINK path matches a target object (i.e. <<path>>) return it.
43254439
4326 - If LINK path exactly matches the name affiliated keyword
4327 (i.e. #+NAME: path) of an element, return that element.
4440 - If LINK path exactly matches the name or results affiliated keyword
4441 (i.e. #+NAME: path or #+RESULTS: name) of an element, return that
4442 element.
43284443
43294444 - If LINK path exactly matches any headline name, return that
43304445 element.
43404455 (let* ((search-cells (org-export-string-to-search-cell
43414456 (org-element-property :path link)))
43424457 (link-cache (or (plist-get info :resolve-fuzzy-link-cache)
4343 (let ((table (make-hash-table :test #'eq)))
4458 (let ((table (make-hash-table :test #'equal)))
4459 ;; Cache all the element search cells.
4460 (org-element-map (plist-get info :parse-tree)
4461 (append pseudo-types '(target) org-element-all-elements)
4462 (lambda (datum)
4463 (dolist (cell (org-export-search-cells datum))
4464 (if (gethash cell table)
4465 (push datum (gethash cell table))
4466 (puthash cell (list datum) table)))))
43444467 (plist-put info :resolve-fuzzy-link-cache table)
43454468 table)))
43464469 (cached (gethash search-cells link-cache 'not-found)))
43474470 (if (not (eq cached 'not-found)) cached
43484471 (let ((matches
4349 (org-element-map (plist-get info :parse-tree)
4350 (append pseudo-types '(target) org-element-all-elements)
4351 (lambda (datum)
4352 (and (org-export-match-search-cell-p datum search-cells)
4353 datum)))))
4472 (let (result)
4473 (dolist (search-cell search-cells)
4474 (setq result
4475 (nconc
4476 result
4477 (gethash search-cell link-cache))))
4478 (delq nil result))))
43544479 (unless matches
43554480 (signal 'org-link-broken (list (org-element-property :path link))))
43564481 (puthash
43774502 \"custom-id\". Throw an error if no match is found."
43784503 (let ((id (org-element-property :path link)))
43794504 ;; First check if id is within the current parse tree.
4380 (or (org-element-map (plist-get info :parse-tree) 'headline
4381 (lambda (headline)
4382 (when (or (equal (org-element-property :ID headline) id)
4383 (equal (org-element-property :CUSTOM_ID headline) id))
4384 headline))
4385 info 'first-match)
4386 ;; Otherwise, look for external files.
4387 (cdr (assoc id (plist-get info :id-alist)))
4388 (signal 'org-link-broken (list id)))))
4505 (or (let ((local-ids (or (plist-get info :id-local-cache)
4506 (let ((table (make-hash-table :test #'equal)))
4507 (org-element-map
4508 (plist-get info :parse-tree)
4509 'headline
4510 (lambda (headline)
4511 (let ((id (org-element-property :ID headline))
4512 (custom-id (org-element-property :CUSTOM_ID headline)))
4513 (when id
4514 (unless (gethash id table)
4515 (puthash id headline table)))
4516 (when custom-id
4517 (unless (gethash custom-id table)
4518 (puthash custom-id headline table)))))
4519 info)
4520 (plist-put info :id-local-cache table)
4521 table))))
4522 (gethash id local-ids))
4523 ;; Otherwise, look for external files.
4524 (cdr (assoc id (plist-get info :id-alist)))
4525 (signal 'org-link-broken (list id)))))
43894526
43904527 (defun org-export-resolve-radio-link (link info)
43914528 "Return radio-target object referenced as LINK destination.
43944531
43954532 Return value can be a radio-target object or nil. Assume LINK
43964533 has type \"radio\"."
4397 (let ((path (replace-regexp-in-string
4398 "[ \r\t\n]+" " " (org-element-property :path link))))
4534 (let ((path (org-string-clean-whitespace (org-element-property :path link))))
43994535 (org-element-map (plist-get info :parse-tree) 'radio-target
44004536 (lambda (radio)
4401 (and (eq (compare-strings
4402 (replace-regexp-in-string
4403 "[ \r\t\n]+" " " (org-element-property :value radio))
4404 nil nil path nil nil t)
4405 t)
4537 (and (org-string-equal-ignore-case
4538 (org-string-clean-whitespace (org-element-property :value radio))
4539 path)
44064540 radio))
44074541 info 'first-match)))
44084542
44404574 (let ((fullname (expand-file-name filename)))
44414575 (concat (if (string-prefix-p "/" fullname) "file://" "file:///")
44424576 fullname)))))
4577
4578 (defun org-export-link-remote-p (link)
4579 "Returns non-nil if the link refers to a remote resource."
4580 (or (member (org-element-property :type link) '("http" "https" "ftp"))
4581 (and (string= (org-element-property :type link) "file")
4582 (file-remote-p (org-element-property :path link)))))
4583
4584 (defun org-export-link--remote-local-copy (link)
4585 "Download the remote resource specified by LINK, and return its local path."
4586 ;; TODO work this into ol.el as a link parameter, say :download.
4587 (let* ((location-type
4588 (pcase (org-element-property :type link)
4589 ((or "http" "https" "ftp") 'url)
4590 ((and "file" (guard (file-remote-p
4591 (org-element-property :path link))))
4592 'file)
4593 (_ (error "Cannot copy %s:%s to a local file"
4594 (org-element-property :type link)
4595 (org-element-property :path link)))))
4596 (path
4597 (pcase location-type
4598 ('url
4599 (concat (org-element-property :type link)
4600 ":" (org-element-property :path link)))
4601 ('file
4602 (org-element-property :path link)))))
4603 (or (org-persist-read location-type path)
4604 (org-persist-register location-type path
4605 :write-immediately t))))
4606
4607 (require 'subr-x) ;; FIXME: For `thread-first' in Emacs 26.
4608 (defun org-export-link-localise (link)
4609 "Convert remote LINK to local link.
4610 If LINK refers to a remote resource, modify it to point to a local
4611 downloaded copy. Otherwise, return unchanged LINK."
4612 (when (org-export-link-remote-p link)
4613 (let* ((local-path (org-export-link--remote-local-copy link)))
4614 (if local-path
4615 (setcdr link
4616 (thread-first (cadr link)
4617 (plist-put :type "file")
4618 (plist-put :path local-path)
4619 (plist-put :raw-link (concat "file:" local-path))
4620 list))
4621 (display-warning
4622 '(org export)
4623 (format "unable to obtain local copy of %s"
4624 (org-element-property :raw-link link))))))
4625 link)
44434626
44444627 ;;;; For References
44454628 ;;
45744757 (let ((counter 0))
45754758 ;; Increment counter until ELEMENT is found again.
45764759 (org-element-map (plist-get info :parse-tree)
4577 (or types (org-element-type element))
4760 (or (and types (cons (org-element-type element) types))
4761 (org-element-type element))
45784762 (lambda (el)
4579 (cond
4580 ((eq element el) (1+ counter))
4581 ((not predicate) (cl-incf counter) nil)
4582 ((funcall predicate el info) (cl-incf counter) nil)))
4763 (let ((cached (org-element-property :org-export--counter el)))
4764 (cond
4765 ((eq element el) (1+ counter))
4766 ;; Use cached result.
4767 ((and cached
4768 (equal predicate (car cached))
4769 (equal types (cadr cached)))
4770 (setq counter (nth 2 cached))
4771 nil)
4772 ((not predicate)
4773 (cl-incf counter)
4774 (org-element-put-property
4775 el :org-export--counter (list predicate types counter))
4776 nil)
4777 ((funcall predicate el info)
4778 (cl-incf counter)
4779 (org-element-put-property
4780 el :org-export--counter (list predicate types counter))
4781 nil))))
45834782 info 'first-match)))))
45844783
45854784 ;;;; For Raw objects
46024801 ;; a given element, excluded. Note: "-n" switches reset that count.
46034802 ;;
46044803 ;; `org-export-unravel-code' extracts source code (along with a code
4605 ;; references alist) from an `element-block' or `src-block' type
4804 ;; references alist) from an `example-block' or `src-block' type
46064805 ;; element.
46074806 ;;
46084807 ;; `org-export-format-code' applies a formatting function to each line
54655664 (secondary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
54665665 (secondary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
54675666 (apostrophe :utf-8 "’" :html "&rsquo;"))
5667 ("fa"
5668 (primary-opening
5669 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5670 :texinfo "@guillemetleft{}")
5671 (primary-closing
5672 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5673 :texinfo "@guillemetright{}")
5674 (secondary-opening :utf-8 "‹" :html "&lsaquo;" :latex "\\guilsinglleft{}"
5675 :texinfo "@guilsinglleft{}")
5676 (secondary-closing :utf-8 "›" :html "&rsaquo;" :latex "\\guilsinglright{}"
5677 :texinfo "@guilsinglright{}")
5678 (apostrophe :utf-8 "’" :html "&rsquo;"))
54685679 ("fr"
54695680 (primary-opening
54705681 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
54725683 (primary-closing
54735684 :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
54745685 :texinfo "@tie{}@guillemetright{}")
5475 (secondary-opening
5476 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5477 :texinfo "@guillemetleft{}@tie{}")
5478 (secondary-closing :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5479 :texinfo "@tie{}@guillemetright{}")
5686 (secondary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5687 (secondary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
54805688 (apostrophe :utf-8 "’" :html "&rsquo;"))
54815689 ("is"
54825690 (primary-opening
57865994 ("eo" :html "A&#365;toro")
57875995 ("es" :default "Autor")
57885996 ("et" :default "Autor")
5997 ("fa" :default "نویسنده")
57895998 ("fi" :html "Tekij&auml;")
57905999 ("fr" :default "Auteur")
57916000 ("hu" :default "Szerz&otilde;")
58116020 ("cs" :default "Pokračování z předchozí strany")
58126021 ("de" :default "Fortsetzung von vorheriger Seite")
58136022 ("es" :html "Contin&uacute;a de la p&aacute;gina anterior" :ascii "Continua de la pagina anterior" :default "Continúa de la página anterior")
6023 ("fa" :default "ادامه از صفحهٔ قبل")
58146024 ("fr" :default "Suite de la page précédente")
58156025 ("it" :default "Continua da pagina precedente")
58166026 ("ja" :default "前ページからの続き")
58286038 ("cs" :default "Pokračuje na další stránce")
58296039 ("de" :default "Fortsetzung nächste Seite")
58306040 ("es" :html "Contin&uacute;a en la siguiente p&aacute;gina" :ascii "Continua en la siguiente pagina" :default "Continúa en la siguiente página")
6041 ("fa" :default "ادامه در صفحهٔ بعد")
58316042 ("fr" :default "Suite page suivante")
58326043 ("it" :default "Continua alla pagina successiva")
58336044 ("ja" :default "次ページに続く")
58426053 ("tr" :default "Devamı sonraki sayfada"))
58436054 ("Created"
58446055 ("cs" :default "Vytvořeno")
6056 ("fa" :default "ساخته شده")
58456057 ("nl" :default "Gemaakt op") ;; must be followed by a date or date+time
58466058 ("pt_BR" :default "Criado em")
58476059 ("ro" :default "Creat")
58566068 ("eo" :default "Dato")
58576069 ("es" :default "Fecha")
58586070 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
6071 ("fa" :default "تاریخ")
58596072 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
58606073 ("hu" :html "D&aacute;tum")
58616074 ("is" :default "Dagsetning")
58826095 ("de" :default "Gleichung")
58836096 ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
58846097 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
6098 ("fa" :default "معادله")
58856099 ("fr" :ascii "Equation" :default "Équation")
58866100 ("is" :default "Jafna")
58876101 ("ja" :default "方程式")
59046118 ("de" :default "Abbildung")
59056119 ("es" :default "Figura")
59066120 ("et" :default "Joonis")
6121 ("fa" :default "شکل")
59076122 ("is" :default "Mynd")
59086123 ("it" :default "Figura")
59096124 ("ja" :default "図" :html "&#22259;")
59246139 ("de" :default "Abbildung %d:")
59256140 ("es" :default "Figura %d:")
59266141 ("et" :default "Joonis %d:")
6142 ("fa" :default "شکل %d:")
59276143 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
59286144 ("is" :default "Mynd %d")
59296145 ("it" :default "Figura %d:")
59486164 ("eo" :default "Piednotoj")
59496165 ("es" :ascii "Notas al pie de pagina" :html "Notas al pie de p&aacute;gina" :default "Notas al pie de página")
59506166 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
6167 ("fa" :default "پانوشت‌ها")
59516168 ("fi" :default "Alaviitteet")
59526169 ("fr" :default "Notes de bas de page")
59536170 ("hu" :html "L&aacute;bjegyzet")
59766193 ("de" :default "Programmauflistungsverzeichnis")
59776194 ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
59786195 ("et" :default "Loendite nimekiri")
6196 ("fa" :default "فهرست برنامه‌ریزی‌ها")
59796197 ("fr" :default "Liste des programmes")
59806198 ("ja" :default "ソースコード目次")
59816199 ("nl" :default "Lijst van programma's")
59946212 ("de" :default "Tabellenverzeichnis")
59956213 ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
59966214 ("et" :default "Tabelite nimekiri")
6215 ("fa" :default "فهرست جدول‌ها")
59976216 ("fr" :default "Liste des tableaux")
59986217 ("is" :default "Töfluskrá" :html "T&ouml;fluskr&aacute;")
59996218 ("it" :default "Indice delle tabelle")
60176236 ("de" :default "Programmlisting")
60186237 ("es" :default "Listado de programa")
60196238 ("et" :default "Loend")
6239 ("fa" :default "برنامه‌ریزی")
60206240 ("fr" :default "Programme" :html "Programme")
60216241 ("it" :default "Listato")
60226242 ("ja" :default "ソースコード")
60376257 ("de" :default "Programmlisting %d")
60386258 ("es" :default "Listado de programa %d")
60396259 ("et" :default "Loend %d")
6260 ("fa" :default "برنامه‌ریزی %d:")
60406261 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
60416262 ("it" :default "Listato %d :")
60426263 ("ja" :default "ソースコード%d:")
60556276 ("cs" :default "Reference")
60566277 ("de" :default "Quellen")
60576278 ("es" :default "Referencias")
6279 ("fa" :default "منابع")
60586280 ("fr" :ascii "References" :default "Références")
60596281 ("it" :default "Riferimenti")
60606282 ("nl" :default "Bronverwijzingen")
60646286 ("tr" :default "Referanslar"))
60656287 ("See figure %s"
60666288 ("cs" :default "Viz obrázek %s")
6289 ("fa" :default "نمایش شکل %s")
60676290 ("fr" :default "cf. figure %s"
60686291 :html "cf.&nbsp;figure&nbsp;%s" :latex "cf.~figure~%s")
60696292 ("it" :default "Vedi figura %s")
60756298 ("tr" :default "bkz. şekil %s"))
60766299 ("See listing %s"
60776300 ("cs" :default "Viz program %s")
6301 ("fa" :default "نمایش برنامه‌ریزی %s")
60786302 ("fr" :default "cf. programme %s"
60796303 :html "cf.&nbsp;programme&nbsp;%s" :latex "cf.~programme~%s")
60806304 ("nl" :default "Zie programma %s"
60906314 ("de" :default "siehe Abschnitt %s")
60916315 ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
60926316 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
6317 ("fa" :default "نمایش بخش %s")
60936318 ("fr" :default "cf. section %s")
60946319 ("it" :default "Vedi sezione %s")
60956320 ("ja" :default "セクション %s を参照")
61056330 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
61066331 ("See table %s"
61076332 ("cs" :default "Viz tabulka %s")
6333 ("fa" :default "نمایش جدول %s")
61086334 ("fr" :default "cf. tableau %s"
61096335 :html "cf.&nbsp;tableau&nbsp;%s" :latex "cf.~tableau~%s")
61106336 ("it" :default "Vedi tabella %s")
61206346 ("de" :default "Tabelle")
61216347 ("es" :default "Tabla")
61226348 ("et" :default "Tabel")
6349 ("fa" :default "جدول")
61236350 ("fr" :default "Tableau")
61246351 ("is" :default "Tafla")
61256352 ("it" :default "Tabella")
61386365 ("de" :default "Tabelle %d")
61396366 ("es" :default "Tabla %d")
61406367 ("et" :default "Tabel %d")
6368 ("fa" :default "جدول %d")
61416369 ("fr" :default "Tableau %d :")
61426370 ("is" :default "Tafla %d")
61436371 ("it" :default "Tabella %d:")
61636391 ("eo" :default "Enhavo")
61646392 ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
61656393 ("et" :default "Sisukord")
6394 ("fa" :default "فهرست")
61666395 ("fi" :html "Sis&auml;llysluettelo")
61676396 ("fr" :ascii "Sommaire" :default "Table des matières")
61686397 ("hu" :html "Tartalomjegyz&eacute;k")
61746403 ("nb" :default "Innhold")
61756404 ("nn" :default "Innhald")
61766405 ("pl" :html "Spis tre&#x015b;ci")
6177 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
6406 ("pt_BR" :html "&Iacute;ndice" :utf-8 "Índice" :ascii "Indice")
61786407 ("ro" :default "Cuprins")
61796408 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
61806409 :utf-8 "Содержание")
61906419 ("de" :default "Unbekannter Verweis")
61916420 ("es" :default "Referencia desconocida")
61926421 ("et" :default "Tundmatu viide")
6422 ("fa" :default "منبع ناشناس")
61936423 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
61946424 ("it" :default "Riferimento sconosciuto")
61956425 ("ja" :default "不明な参照先")
62516481 ;;
62526482 ;; Export Stack is viewed through a dedicated major mode
62536483 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
6254 ;;`org-export-stack-delete', `org-export-stack-view' and
6484 ;;`org-export-stack-remove', `org-export-stack-view' and
62556485 ;;`org-export-stack-clear'.
62566486 ;;
62576487 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
63666596 Optional argument POST-PROCESS is a function which should accept
63676597 no argument. It is always called within the current process,
63686598 from BUFFER, with point at its beginning. Export back-ends can
6369 use it to set a major mode there, e.g,
6599 use it to set a major mode there, e.g.,
63706600
63716601 (defun org-latex-export-as-latex
63726602 (&optional async subtreep visible-only body-only ext-plist)
63736603 (interactive)
63746604 (org-export-to-buffer \\='latex \"*Org LATEX Export*\"
63756605 async subtreep visible-only body-only ext-plist
6376 #'LaTeX-mode))
6606 #\\='LaTeX-mode))
63776607
63786608 When expressed as an anonymous function, using `lambda',
63796609 POST-PROCESS needs to be quoted.
64396669 (let ((outfile (org-export-output-file-name \".tex\" subtreep)))
64406670 (org-export-to-file \\='latex outfile
64416671 async subtreep visible-only body-only ext-plist
6442 #'org-latex-compile)))
6672 #\\='org-latex-compile)))
64436673
64446674 When expressed as an anonymous function, using `lambda',
64456675 POST-PROCESS needs to be quoted.
64496679 (declare (indent 2))
64506680 (if (not (file-writable-p file)) (error "Output file not writable")
64516681 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
6452 (encoding (or org-export-coding-system buffer-file-coding-system))
6453 auto-mode-alist)
6682 (encoding (or org-export-coding-system buffer-file-coding-system)))
64546683 (if async
64556684 (org-export-async-start
64566685 (lambda (file)
64626691 (with-temp-buffer
64636692 (insert output)
64646693 (let ((coding-system-for-write ',encoding))
6465 (write-file ,file)))
6694 (write-region (point-min) (point-max) ,file)))
64666695 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
64676696 (let ((output (org-export-as
64686697 backend subtreep visible-only body-only ext-plist)))
64696698 (with-temp-buffer
64706699 (insert output)
64716700 (let ((coding-system-for-write encoding))
6472 (write-file file)))
6701 (write-region (point-min) (point-max) file)))
64736702 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
64746703 (org-kill-new output))
64756704 ;; Get proper return value.
65246753 (cond
65256754 (pub-dir (concat (file-name-as-directory pub-dir)
65266755 (file-name-nondirectory base-name)))
6527 ((file-name-absolute-p base-name) base-name)
65286756 (t base-name))))
65296757 ;; If writing to OUTPUT-FILE would overwrite original file, append
65306758 ;; EXTENSION another time to final name.
69257153 (delete-other-windows)
69267154 (org-switch-to-buffer-other-window
69277155 (get-buffer-create "*Org Export Dispatcher*"))
6928 (setq cursor-type nil
6929 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
7156 (setq cursor-type nil)
7157 (setq header-line-format
7158 (let ((propertize-help-key
7159 (lambda (key)
7160 ;; Add `face' *and* `font-lock-face' to "work
7161 ;; reliably in any buffer", per a comment in
7162 ;; `help--key-description-fontified'.
7163 (propertize key
7164 'font-lock-face 'help-key-binding
7165 'face 'help-key-binding))))
7166 (apply 'format
7167 (cons "Use %s, %s, %s, or %s to navigate."
7168 (mapcar propertize-help-key
7169 (list "SPC" "DEL" "C-n" "C-p"))))))
69307170 ;; Make sure that invisible cursor will not highlight square
69317171 ;; brackets.
69327172 (set-syntax-table (copy-syntax-table))
3131 testdir = $(TMPDIR)/tmp-orgtest
3232
3333 # Configuration for testing
34 # Verbose ERT summary by default for Emacs-28 and above.
35 # To override:
36 # - Add to local.mk
37 # EMACS_TEST_VERBOSE =
38 # - Export EMACS_TEST_VERBOSE environment variable with empty value
39 # - Run tests as
40 # EMACS_TEST_VERBOSE= make test [OTHER_ARGUMENTS...]
41 # or as
42 # make test EMACS_TEST_VERBOSE= [OTHER_ARGUMENTS...]
43 EMACS_TEST_VERBOSE ?= yes
44 ifeq (,$(EMACS_TEST_VERBOSE))
45 # Emacs-28 considers empty value as true, fixed in Emacs-29
46 unexport EMACS_TEST_VERBOSE
47 endif
3448 # add options before standard load-path
3549 BTEST_PRE =
3650 # add options after standard load path
3852 # -L <path-to>/ert # needed for Emacs23, Emacs24 has ert built in
3953 # -L <path-to>/ess # needed for running R tests
4054 # -L <path-to>/htmlize # need at least version 1.34 for source code formatting
41 BTEST_OB_LANGUAGES = awk C fortran maxima lilypond octave perl python
55 BTEST_OB_LANGUAGES = awk C fortran maxima lilypond octave perl python java
4256 # R # requires ESS to be installed and configured
4357 # ruby # requires inf-ruby to be installed and configured
4458 # extra packages to require for testing
4559 BTEST_EXTRA =
4660 # ess-site # load ESS for R tests
61 # Whether to activate extra debugging facilities for make repro.
62 REPRO_DEBUG ?= yes
63 # Extra arguments passed to Emacs for make repro.
64 # e.g. -l config.el /tmp/bug.org
65 REPRO_ARGS ?=
4766 ##->8-------------------------------------------------------------------
4867 ## YOU MAY NEED TO ADAPT THESE DEFINITIONS
4968 ##----------------------------------------------------------------------
5271 req-ob-lang = --eval '(require '"'"'ob-$(ob-lang))'
5372 lst-ob-lang = ($(ob-lang) . t)
5473 req-extra = --eval '(require '"'"'$(req))'
55 BTEST_RE ?= \\(org\\|ob\\)
74 BTEST_RE ?= \\(org\\|ob\\|ox\\)
5675 BTEST_LOAD = \
5776 --eval '(add-to-list '"'"'load-path (concat default-directory "lisp"))' \
5877 --eval '(add-to-list '"'"'load-path (concat default-directory "testing"))'
7897 # should be useful for manual testing and verification of problems.
7998 NOBATCH = $(EMACSQ) $(BTEST_INIT) -l org -f org-version
8099
100 ifeq ($(REPRO_DEBUG), yes)
101 REPRO_INIT = --eval "(setq \
102 debug-on-error t\
103 debug-on-signal nil\
104 debug-on-quit nil\
105 org-element--cache-self-verify 'backtrace\
106 org-element--cache-self-verify-frequency 1.0\
107 org-element--cache-map-statistics t)"
108 else
109 REPRO_INIT =
110 endif
111
112 # Running a plain emacs with no config, this Org mode loaded, and
113 # debugging facilities activated.
114 REPRO = $(NOBATCH) $(REPRO_INIT) $(REPRO_ARGS)
115
81116 # start Emacs with no user and site configuration
82117 # EMACSQ = -vanilla # XEmacs
83118 EMACSQ = $(EMACS) -Q
84119
85120 # Using emacs in batch mode.
86121 BATCH = $(EMACSQ) -batch \
87 --eval '(setq vc-handled-backends nil org-startup-folded nil)'
122 --eval '(setq vc-handled-backends nil org-startup-folded nil org-element-cache-persistent nil)'
88123
89124 # Emacs must be started in toplevel directory
90125 BATCHO = $(BATCH) \
11 ;;
22 ;; Author: Achim Gratz
33 ;; Keywords: orgmode
4 ;; Homepage: https://orgmode.org
4 ;; URL: https://orgmode.org
55 ;;
66 ;; This file is not part of GNU Emacs.
77 ;;
8989 (set-visited-file-name "org-loaddefs.el")
9090 (insert ";;; org-loaddefs.el --- autogenerated file, do not edit\n;;\n;;; Code:\n")
9191 (let ((files (directory-files default-directory
92 nil "^\\(org\\|ob\\|ox\\|ol\\)\\(-.*\\)?\\.el$")))
92 nil "^\\(org\\|ob\\|ox\\|ol\\|oc\\)\\(-.*\\)?\\.el$")))
9393 (mapc (lambda (f) (generate-file-autoloads f)) files))
9494 (insert "\f\n(provide 'org-loaddefs)\n")
9595 (insert "\f\n;; Local Variables:\n;; version-control: never\n")
2323
2424 sub rep_esc{
2525 my $s = shift @_;
26 $s =~ s/\\kbd{([^}]+)}/$1/g;
26 $s =~ s/\\kbd\{([^}]+)\}/$1/g;
2727 $s =~ s/\$\^([0-9])\$/[$1]/g;
2828 $s =~ s/\\rm //g;
2929 $s =~ s/\\\///g;
30 $s =~ s/\\\^{}/^/g;
30 $s =~ s/\\\^\{\}/^/g;
3131 $s =~ s/\\}/}/g;
32 $s =~ s/\\{/{/g;
32 $s =~ s/\\\{/{/g;
3333 $s =~ s/\\\#/#/g;
3434 $s =~ s/\\\^/^/g;
3535 $s =~ s/\\\%/%/g;
3838 $s =~ s/\\\$/\$/g;
3939 $s =~ s/\$\\leftrightarrow\$/<->/g;
4040 $s =~ s/\$\\pm 1\$/±1/g;
41 $s =~ s/``{\\tt ([^}]+)}''/`$1'/g;
41 $s =~ s/``\{\\tt ([^}]+)}''/`$1'/g;
4242 return $s;
4343 }
4444 my $page=0;
4545 my $orgversionnumber;
4646
47 open(IN,$ARGV[0]);
47 open(IN,"org-version.tex");
4848 while(<IN>){
4949 last if(/\f/);
50 $orgversionnumber = $1 if /\\def\\orgversionnumber{([^}]+)}/;
50 $orgversionnumber = $1 if /\\def\\orgversionnumber\{([^}]+)}/;
5151 }
5252 close(IN);
5353
7474 next if($page != 1);
7575 next if(/^%/);
7676 next if /Org Mode Reference Card \([12]\/2\)/;
77 next if /\\centerline{\(for version \\orgversionnumber\)}/;
77 next if /\\centerline\{\(for version \\orgversionnumber\)}/;
7878 next if /\(for version \)/;
7979 next if /\\newcolumn/;
8080 next if /\\copyrightnotice/;
8181 next if /\\bye/;
82 next if /\\title{([^}]+)}/;
82 next if /\\title\{([^}]+)}/;
8383 chomp;
8484 # print "b:$_\n";
8585 s/([^\\])\%.+$/$1/;
8686 # print "a:$_\n";
87 if (/\\section{(.+)}/){
87 if (/\\section\{(.+)}/){
8888 my $sec = rep_esc($1);
8989 print "================================================================================\n";
9090 print "$sec\n";
105105 print "--------------------------------------------------------------------------------\n";
106106 next;
107107 }
108 if(/^\\key{(.+)}\s*$/||/^\\metax{(.+)}\s*$/){
109 my ($k,$v) = split(/}{/,$1);
108 if(/^\\key\{(.+)}\s*$/||/^\\metax\{(.+)}\s*$/){
109 my ($k,$v) = split(/}\{/,$1);
110110 my $k2 = &rep_esc($k);
111111 my $v2 = &rep_esc($v);
112112 # print "$k2\t$v2\n";
4343
4444 doc-up: info pdf card html
4545 $(MAKE) -C doc manual guide
46 $(CP) doc/org.html $(SERVROOT)
47 $(CP) doc/org.pdf $(SERVROOT)
48 $(CP) doc/orgguide.html $(SERVROOT)
49 $(CP) doc/orgguide.pdf $(SERVROOT)
50 $(CP) doc/manual/* $(SERVROOT)/manual
51 $(CP) doc/guide/* $(SERVROOT)/guide
46 $(CP) doc/org.html $(SERVROOT)
47 $(CP) doc/orgcard.pdf $(SERVROOT)
48 $(CP) doc/orgcard_letter.pdf $(SERVROOT)
49 $(CP) doc/org.pdf $(SERVROOT)
50 $(CP) doc/orgguide.html $(SERVROOT)
51 $(CP) doc/orgguide.pdf $(SERVROOT)
52 $(CP) doc/manual/* $(SERVROOT)/manual
53 $(CP) doc/guide/* $(SERVROOT)/guide
5254
5355 upload: cleanall doc-up
00 .EXPORT_ALL_VARIABLES:
11 .NOTPARALLEL: .PHONY
22 # Additional distribution files
3 DISTFILES_extra= Makefile request-assign-future.txt etc
3 DISTFILES_extra= Makefile etc
44
55 LISPDIRS = lisp
66 OTHERDIRS = doc etc
1010 ORG_MAKE_DOC ?= info html pdf
1111
1212 ifneq ($(wildcard .git),)
13 ORGVERSION ?= $(subst release_,,$(shell git describe --match release\* --abbrev=0 HEAD))
14 ifeq ($(ORGVERSION),)
15 # In elpa.git, there are no tags available. Fall back to using
16 # the org.el header.
17 ORGVERSION := $(patsubst %-dev,%,$(shell $(BATCH) --eval "(require 'lisp-mnt)" \
18 --visit lisp/org.el --eval '(princ (lm-header "version"))'))
19 GITVERSION ?= $(ORGVERSION)-g$(shell git rev-parse --short=6 HEAD)
20 else
21 GITVERSION ?= $(shell git describe --match release\* --abbrev=6 HEAD)
22 endif
13 # Use the org.el header.
14 ORGVERSION := $(patsubst %-dev,%,$(shell $(BATCH) --eval "(require 'lisp-mnt)" \
15 --visit lisp/org.el --eval '(princ (lm-header "version"))'))
16 GITVERSION ?= $(shell git describe --match release\* --abbrev=6 HEAD)
2317 GITSTATUS ?= $(shell git status -uno --porcelain)
2418 else
2519 -include mk/version.mk
4034 cleanlisp cleandoc cleandocs cleantest \
4135 compile compile-dirty uncompiled \
4236 config config-test config-exe config-all config-eol config-version \
43 vanilla
37 vanilla repro
4438
4539 CONF_BASE = EMACS DESTDIR ORGCM ORG_MAKE_DOC
4640 CONF_DEST = lispdir infodir datadir testdir
131125 autoloads: lisp
132126 $(MAKE) -C $< $@
133127
128 repro: cleanall autoloads
129 -@$(REPRO) &
130
134131 cleandirs:
135132 $(foreach dir, $(SUBDIRS), $(MAKE) -C $(dir) cleanall;)
136133